From ce2d6e08dd25e5c54a6c5c44b6797427a84a8654 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 15 Nov 2026 02:18:17 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=BB=B4=E6=8A=A4=E4=B8=AD=E5=9B=BD?= =?UTF-8?q?=E4=BB=A3=E7=90=86=E6=B1=A0=E5=B9=B6=E6=94=AF=E6=8C=81=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E8=87=AA=E5=8A=A8=E5=9D=87=E5=8C=80=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/admin/routes.py | 19 + backend/admin/users.py | 4 +- backend/alembic/versions/0011_proxy_pool.py | 53 +++ backend/euniv/api.py | 6 + backend/euniv/autostudy.py | 201 ++++++--- backend/euniv/collectors.py | 214 +++++++++ backend/euniv/courses.py | 33 +- backend/euniv/models.py | 35 +- backend/euniv/proxy.py | 63 ++- backend/euniv/proxy_pool.py | 452 ++++++++++++++++++++ backend/euniv/service.py | 185 +++++--- backend/tests/conftest.py | 5 + backend/tests/test_api.py | 1 + backend/tests/test_autostudy.py | 12 + backend/tests/test_proxy_pool.py | 284 ++++++++++++ web/src/features/admin/ProxiesView.vue | 273 ++++++++++++ web/src/features/admin/UsersView.vue | 21 +- web/src/features/home/HomeView.vue | 23 +- web/src/shell/AdminShell.vue | 6 +- web/src/shell/adminNavigation.ts | 5 +- 20 files changed, 1733 insertions(+), 162 deletions(-) create mode 100644 backend/alembic/versions/0011_proxy_pool.py create mode 100644 backend/euniv/collectors.py create mode 100644 backend/euniv/proxy_pool.py create mode 100644 backend/tests/test_proxy_pool.py create mode 100644 web/src/features/admin/ProxiesView.vue diff --git a/backend/admin/routes.py b/backend/admin/routes.py index 7db58c2..b10b04c 100644 --- a/backend/admin/routes.py +++ b/backend/admin/routes.py @@ -26,6 +26,8 @@ from admin.users import ( ) from euniv.courses import course_page, request_course_sync_now from euniv.db import get_db +from euniv.proxy_pool import page as proxy_page +from euniv.proxy_pool import request_refresh as request_proxy_refresh public_router = APIRouter() admin_router = APIRouter(prefix="/api/admin") @@ -129,6 +131,23 @@ def get_courses( return course_page(db, q, start, bounded, kind) +@admin_router.get("/proxies") +def get_proxies( + q: str = "", + status: str = "", + offset: int = 0, + limit: int = 50, + db: Session = Depends(get_db), + _: str = Depends(require_admin), +) -> dict: + return proxy_page(db, q, status, offset, limit) + + +@admin_router.post("/proxies/refresh") +def post_proxies_refresh(_: str = Depends(require_admin)) -> dict: + return request_proxy_refresh() + + @admin_router.get("/users") def get_users(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict]: return list_users(db) diff --git a/backend/admin/users.py b/backend/admin/users.py index c76c833..8d6b196 100644 --- a/backend/admin/users.py +++ b/backend/admin/users.py @@ -15,7 +15,7 @@ from euniv.course_workers import CourseWorkersError from euniv.course_workers import apply as apply_workers from euniv.course_workers import of as workers_of from euniv.course_workers import view_of as workers_view -from euniv.proxy import ProxyError, apply, clear, summary_of, url_of, view_of +from euniv.proxy import ProxyError, apply, clear, enabled, summary_of, url_of, view_of from euniv.study_window import StudyWindowError from euniv.study_window import apply as apply_start from euniv.study_window import label_of as start_label @@ -73,7 +73,7 @@ def list_users(db: Session) -> list[dict]: "last_refresh_at": _iso_time(account.last_refresh_at), "credential_valid": _optional_bool(account.credential_valid), "month_hours": account.month_hours or "", - "has_proxy": bool(account.proxy_scheme and account.proxy_host and account.proxy_port), + "has_proxy": enabled(account), "proxy": summary_of(account), "study_start": start_label(account), "study_start_day": int(account.study_start_day or 1), diff --git a/backend/alembic/versions/0011_proxy_pool.py b/backend/alembic/versions/0011_proxy_pool.py new file mode 100644 index 0000000..474af18 --- /dev/null +++ b/backend/alembic/versions/0011_proxy_pool.py @@ -0,0 +1,53 @@ +"""代理池节点、同步记录,以及账号是否使用自动代理。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0011_proxy_pool" +down_revision = "0010_course_workers" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.add_column( + sa.Column("use_proxy_pool", sa.Boolean(), nullable=False, server_default=sa.false()) + ) + op.create_table( + "proxy_nodes", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("scheme", sa.String(length=16), nullable=False), + sa.Column("host", sa.String(length=255), nullable=False), + sa.Column("port", sa.Integer(), nullable=False), + sa.Column("country", sa.String(length=32), nullable=False, server_default=""), + sa.Column("anonymity", sa.String(length=32), nullable=False, server_default=""), + sa.Column("source", sa.String(length=64), nullable=False, server_default=""), + sa.Column("status", sa.String(length=16), nullable=False, server_default="new"), + sa.Column("latency_ms", sa.Integer(), nullable=True), + sa.Column("last_checked_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("last_ok_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("fail_reason", sa.String(length=200), nullable=False, server_default=""), + sa.Column("assigns", sa.Integer(), nullable=False, server_default="0"), + sa.UniqueConstraint("scheme", "host", "port", name="uq_proxy_node_addr"), + ) + op.create_index("ix_proxy_nodes_status", "proxy_nodes", ["status"]) + op.create_table( + "proxy_pool_sync", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("fetched_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("checked_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("running", sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column("message", sa.String(length=200), nullable=False, server_default=""), + sa.Column("alive_count", sa.Integer(), nullable=False, server_default="0"), + sa.Column("dead_count", sa.Integer(), nullable=False, server_default="0"), + sa.Column("new_count", sa.Integer(), nullable=False, server_default="0"), + ) + + +def downgrade() -> None: + op.drop_table("proxy_pool_sync") + op.drop_index("ix_proxy_nodes_status", table_name="proxy_nodes") + op.drop_table("proxy_nodes") + with op.batch_alter_table("accounts") as batch: + batch.drop_column("use_proxy_pool") diff --git a/backend/euniv/api.py b/backend/euniv/api.py index ba8d225..c8d319f 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -64,13 +64,19 @@ async def lifespan(_app: FastAPI): load_admin_identity() stop_refresh = None study_worker = None + stop_pool = None if os.environ.get("EUNIV_DISABLE_REFRESH") != "1": stop_refresh = start_credential_refresh() from euniv.autostudy import start_autostudy + from euniv.proxy_pool import start_proxy_pool + study_worker = start_autostudy() + stop_pool = start_proxy_pool() yield if study_worker is not None: study_worker.stop() + if stop_pool is not None: + stop_pool.set() if stop_refresh is not None: stop_refresh.set() diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index 8f87a7d..e06354e 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -27,6 +27,7 @@ from sqlalchemy import select from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired, _load_cookies from euniv.course_workers import of as course_workers_of from euniv.models import Account, Course +from euniv.proxy import bind_url, is_proxy_failure, uses_pool from euniv.study_window import window_open log = logging.getLogger(__name__) @@ -175,12 +176,15 @@ class StudySession: """ def __init__(self, token: str, cookies: list[tuple[str, str, str, str]], - proxy: str | None = None) -> None: + proxy: str | None = None, employee_id: str = "", + use_pool: bool = False) -> None: from euniv.proxy import parse_proxy self._token = token self._initial_cookies = cookies self._proxy = parse_proxy(proxy) + self._employee_id = employee_id + self._use_pool = use_pool self._client: httpx.AsyncClient | None = None async def __aenter__(self) -> "StudySession": @@ -197,6 +201,43 @@ class StudySession: if self._client: await self._client.aclose() + async def _rotate_proxy(self) -> bool: + if not self._use_pool: + return False + from euniv.proxy import parse_proxy + from euniv.proxy_pool import acquire, mark_failed + + old = self._proxy + await asyncio.to_thread(mark_failed, self._employee_id, old) + nxt = await asyncio.to_thread(acquire, self._employee_id) + parsed = parse_proxy(nxt) + if parsed == old: + return False + client = httpx.AsyncClient( + timeout=30, + follow_redirects=True, + proxy=parsed, + headers={"User-Agent": USER_AGENT}, + ) + _load_cookies(client, self._initial_cookies) + prev = self._client + self._client = client + self._proxy = parsed + if prev is not None: + await prev.aclose() + return True + + async def _http(self, method: str, url: str, **kw: object) -> httpx.Response: + assert self._client is not None + try: + return await self._client.request(method, url, **kw) + except Exception as exc: + if self._use_pool and self._proxy and is_proxy_failure(exc): + if await self._rotate_proxy(): + assert self._client is not None + return await self._client.request(method, url, **kw) + raise + def _api_headers(self) -> dict[str, str]: return { "Accept": "application/json, text/plain, */*", @@ -214,7 +255,7 @@ class StudySession: extra = kw.pop("headers", None) if extra and isinstance(extra, dict): headers.update(extra) - resp = await self._client.request(method, url, headers=headers, **kw) + resp = await self._http(method, url, headers=headers, **kw) refreshed = resp.headers.get("token") or resp.headers.get("Token") if refreshed: self._token = refreshed @@ -243,9 +284,18 @@ class StudySession: async def get_encrypt_request(self, body_json: str) -> str: from euniv.encrypt import fetch_encryption_async assert self._client is not None - return await fetch_encryption_async( - self._client, body_json, origin=EUNIV, user_agent=USER_AGENT - ) + try: + return await fetch_encryption_async( + self._client, body_json, origin=EUNIV, user_agent=USER_AGENT + ) + except Exception as exc: + if self._use_pool and self._proxy and is_proxy_failure(exc): + if await self._rotate_proxy(): + assert self._client is not None + return await fetch_encryption_async( + self._client, body_json, origin=EUNIV, user_agent=USER_AGENT + ) + raise async def submit_video_heartbeat(self, kid: str, pkg_id: str, study_time: int, view_schedule: int) -> dict: @@ -323,7 +373,8 @@ class StudySession: async def course_page_params(self, path: str) -> dict: assert self._client is not None - resp = await self._client.get( + resp = await self._http( + "GET", f"{EUNIV}{path}", headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}, ) @@ -346,7 +397,7 @@ class StudySession: async def scorm_extract_answers(self, kid: str) -> list[dict]: assert self._client is not None index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{kid}/h5/js/index-scorm.js" - resp = await self._client.get(index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}) + resp = await self._http("GET", index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}) urls: list[str] = [] for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text): raw = m.group(1) @@ -361,7 +412,7 @@ class StudySession: answers: list[dict] = [] for url in urls: try: - r = await self._client.get(url, headers={"User-Agent": USER_AGENT}) + r = await self._http("GET", url, headers={"User-Agent": USER_AGENT}) for block in re.finditer(r'单选题([\s\S]*?)正确答案[::]\s*([A-D])', r.text): answers.append({"page_url": url, "answer": block.group(2)}) except Exception: @@ -370,7 +421,8 @@ class StudySession: async def month_hours_text(self) -> str: assert self._client is not None - resp = await self._client.get( + resp = await self._http( + "GET", f"{EUNIV}/study/myperiod.htm", headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"}, ) @@ -524,24 +576,40 @@ async def _study_package(session: StudySession, kid: str, intervals: dict, # ── 同步准备:用 EunivClient 建立会话,导出 cookies ── def _prepare_session(employee_id: str, password: str, - credential: dict, proxy: str | None = None - ) -> tuple[str, str, str, list[tuple[str, str, str, str]]]: - """同步:恢复会话并导出 token + cookies。返回 (token, user_id, org_id, cookies)。""" - client = EunivClient(employee_id, password, proxy=proxy) - try: - client.restore(credential) - if not client.credential_alive(): - return "", "", "", [] - client._ensure_site() - token = client.session_token() - user_id = str(client._profile.get("userId") or "") - org_id = str(client._profile.get("accountId") or "") - cookies: list[tuple[str, str, str, str]] = [] - for cookie in client.client.cookies.jar: - cookies.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/")) - return token, user_id, org_id, cookies - finally: - client.close() + credential: dict, proxy: str | None = None, + use_pool: bool = False + ) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None]: + """同步:恢复会话并导出 cookies。返回 (token, user_id, org_id, cookies, proxy)。""" + from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed + + current = proxy + last_exc: BaseException | None = None + for _ in range(MAX_SWITCHES + 1): + client = EunivClient(employee_id, password, proxy=current) + try: + client.restore(credential) + if not client.credential_alive(): + return "", "", "", [], current + client._ensure_site() + token = client.session_token() + user_id = str(client._profile.get("userId") or "") + org_id = str(client._profile.get("accountId") or "") + cookies: list[tuple[str, str, str, str]] = [] + for cookie in client.client.cookies.jar: + cookies.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/")) + return token, user_id, org_id, cookies, current + except Exception as exc: + last_exc = exc + if use_pool and current and is_proxy_failure(exc): + mark_failed(employee_id, current, str(exc)[:200]) + current = acquire(employee_id) + continue + return "", "", "", [], current + finally: + client.close() + if last_exc is not None: + log.warning("用户 %s 准备会话失败: %s", employee_id, last_exc) + return "", "", "", [], current # ── Worker 主循环 ── @@ -603,8 +671,6 @@ class AutoStudyWorker: } with SessionLocal() as db: - from euniv.proxy import url_of - users = db.scalars( select(Account) .where(Account.credential_cipher != "") @@ -625,11 +691,19 @@ class AutoStudyWorker: try: password = decrypt_secret(row.password_cipher) credential = json.loads(decrypt_secret(row.credential_cipher)) - proxy = url_of(row) + proxy = bind_url(row) except Exception: continue eligible.append( - (row.employee_id, target, password, credential, proxy, course_workers_of(row)) + ( + row.employee_id, + target, + password, + credential, + proxy, + course_workers_of(row), + uses_pool(row), + ) ) if not course_list: @@ -647,8 +721,11 @@ class AutoStudyWorker: sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS) tasks = [ - self._study_user(emp_id, target, pw, cred, proxy, workers, course_list, intervals, auto_mode, sem) - for emp_id, target, pw, cred, proxy, workers in eligible + self._study_user( + emp_id, target, pw, cred, proxy, workers, use_pool, + course_list, intervals, auto_mode, sem, + ) + for emp_id, target, pw, cred, proxy, workers, use_pool in eligible ] results = await asyncio.gather(*tasks, return_exceptions=True) for emp_id_tuple, result in zip(eligible, results): @@ -660,34 +737,42 @@ class AutoStudyWorker: async def _study_user(self, employee_id: str, target: int, password: str, credential: dict, proxy: str | None, - workers: int, course_list: list, intervals: dict, + workers: int, use_pool: bool, course_list: list, intervals: dict, auto_mode: bool, sem: asyncio.Semaphore) -> None: assert self._async_stop is not None - async with sem: - _set_user_status(employee_id, state="准备", course="") - loop = asyncio.get_event_loop() - token, user_id, org_id, cookies = await loop.run_in_executor( - None, _prepare_session, employee_id, password, credential, proxy) - if not token: - _set_user_status(employee_id, state="会话失效") - return - - async with StudySession(token, cookies, proxy=proxy) as session: - session._employee_id = employee_id # type: ignore[attr-defined] - _set_user_status(employee_id, state="学习中") - user_stop = asyncio.Event() - hours = HoursWatcher(session, employee_id, target, user_stop) - if await hours.refresh(): + try: + async with sem: + _set_user_status(employee_id, state="准备", course="") + loop = asyncio.get_event_loop() + token, user_id, org_id, cookies, proxy = await loop.run_in_executor( + None, _prepare_session, employee_id, password, credential, proxy, use_pool) + if not token: + _set_user_status(employee_id, state="会话失效") return - ticker = asyncio.create_task(hours.ticker(self._async_stop)) - try: - await self._study_courses( - session, employee_id, course_list, intervals, - auto_mode, hours, user_id, org_id, workers) - finally: - ticker.cancel() - with contextlib.suppress(asyncio.CancelledError): - await ticker + + async with StudySession( + token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool + ) as session: + session._employee_id = employee_id # type: ignore[attr-defined] + _set_user_status(employee_id, state="学习中") + user_stop = asyncio.Event() + hours = HoursWatcher(session, employee_id, target, user_stop) + if await hours.refresh(): + return + ticker = asyncio.create_task(hours.ticker(self._async_stop)) + try: + await self._study_courses( + session, employee_id, course_list, intervals, + auto_mode, hours, user_id, org_id, workers) + finally: + ticker.cancel() + with contextlib.suppress(asyncio.CancelledError): + await ticker + finally: + if use_pool: + from euniv.proxy_pool import release + + release(employee_id) async def _study_courses(self, session: StudySession, employee_id: str, course_list: list, intervals: dict, diff --git a/backend/euniv/collectors.py b/backend/euniv/collectors.py new file mode 100644 index 0000000..623fed7 --- /dev/null +++ b/backend/euniv/collectors.py @@ -0,0 +1,214 @@ +"""代理上游采集。新增平台时实现 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()) diff --git a/backend/euniv/courses.py b/backend/euniv/courses.py index 705e9ef..0435ae0 100644 --- a/backend/euniv/courses.py +++ b/backend/euniv/courses.py @@ -173,18 +173,31 @@ def _fetch_and_store(trigger: str) -> bool: return False password = decrypt_secret(account.password_cipher) credential = json.loads(decrypt_secret(account.credential_cipher)) - from euniv.proxy import url_of + from euniv.proxy import bind_url, is_proxy_failure, uses_pool + from euniv.proxy_pool import MAX_SWITCHES, mark_failed - proxy = url_of(account) - client = EunivClient(employee_id, password, proxy=proxy) - try: - client.restore(credential) - if not client.credential_alive(): + proxy = bind_url(account) + courses = None + last_exc: BaseException | None = None + for _ in range(MAX_SWITCHES + 1): + client = EunivClient(employee_id, password, proxy=proxy) + try: + client.restore(credential) + if not client.credential_alive(): + return False + courses = client.list_courses() + last_exc = None + break + except Exception as exc: + last_exc = exc + if uses_pool(account) and proxy and is_proxy_failure(exc): + mark_failed(employee_id, proxy, str(exc)[:200]) + proxy = bind_url(account) + continue return False - courses = client.list_courses() - finally: - client.close() - if not courses: + finally: + client.close() + if last_exc is not None or not courses: return False with SessionLocal() as db: db.execute(delete(Course)) diff --git a/backend/euniv/models.py b/backend/euniv/models.py index 95d8f48..b59f959 100644 --- a/backend/euniv/models.py +++ b/backend/euniv/models.py @@ -4,7 +4,7 @@ from __future__ import annotations from datetime import datetime -from sqlalchemy import Boolean, DateTime, String, Text, false as sql_false +from sqlalchemy import Boolean, DateTime, String, Text, UniqueConstraint, false as sql_false from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column @@ -57,3 +57,36 @@ class Account(Base): study_start_minute: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") study_start_second: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") course_workers: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1") + use_proxy_pool: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false()) + + +class ProxyNode(Base): + __tablename__ = "proxy_nodes" + __table_args__ = (UniqueConstraint("scheme", "host", "port", name="uq_proxy_node_addr"),) + + id: Mapped[int] = mapped_column(primary_key=True) + scheme: Mapped[str] = mapped_column(String(16), nullable=False) + host: Mapped[str] = mapped_column(String(255), nullable=False) + port: Mapped[int] = mapped_column(nullable=False) + country: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default="") + anonymity: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default="") + source: Mapped[str] = mapped_column(String(64), nullable=False, default="", server_default="") + status: Mapped[str] = mapped_column(String(16), nullable=False, default="new", server_default="new") + latency_ms: Mapped[int | None] = mapped_column(nullable=True) + last_checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + last_ok_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + fail_reason: Mapped[str] = mapped_column(String(200), nullable=False, default="", server_default="") + assigns: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") + + +class ProxyPoolSync(Base): + __tablename__ = "proxy_pool_sync" + + id: Mapped[int] = mapped_column(primary_key=True) + fetched_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + running: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false()) + message: Mapped[str] = mapped_column(String(200), nullable=False, default="", server_default="") + alive_count: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") + dead_count: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") + new_count: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0") diff --git a/backend/euniv/proxy.py b/backend/euniv/proxy.py index 3270451..3d5e5ab 100644 --- a/backend/euniv/proxy.py +++ b/backend/euniv/proxy.py @@ -1,11 +1,14 @@ -"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。账号密码可选。""" +"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。账号密码可选。也可使用代理池。""" from __future__ import annotations from urllib.parse import quote, urlparse +import httpx + SCHEMES = ("http", "https", "socks4", "socks5", "socks5h") OFF_SCHEMES = ("", "off", "none", "direct", "close") +POOL_SCHEMES = ("pool", "auto") class ProxyError(ValueError): @@ -66,12 +69,31 @@ def is_off(scheme: str | None) -> bool: return (scheme or "").strip().lower() in OFF_SCHEMES +def is_pool(scheme: str | None) -> bool: + return (scheme or "").strip().lower() in POOL_SCHEMES + + +def uses_pool(account) -> bool: + return bool(getattr(account, "use_proxy_pool", False)) + + def enabled(account) -> bool: + if uses_pool(account): + return True return bool(account.proxy_scheme and account.proxy_host and account.proxy_port) def view_of(account) -> dict: - on = enabled(account) + if uses_pool(account): + return { + "enabled": True, + "scheme": "pool", + "host": "", + "port": None, + "username": "", + "has_password": False, + } + on = bool(account.proxy_scheme and account.proxy_host and account.proxy_port) return { "enabled": on, "scheme": account.proxy_scheme if on else "off", @@ -83,13 +105,15 @@ def view_of(account) -> dict: def summary_of(account) -> str: - if not enabled(account): + if uses_pool(account): + return "自动" + if not (account.proxy_scheme and account.proxy_host and account.proxy_port): return "" return f"{account.proxy_scheme.upper()} {account.proxy_host}:{account.proxy_port}" def url_of(account) -> str | None: - if not enabled(account): + if uses_pool(account) or not (account.proxy_scheme and account.proxy_host and account.proxy_port): return None password = "" if account.proxy_password_cipher: @@ -109,6 +133,16 @@ def apply(account, scheme: str, host: str = "", port: object = None, username: s if is_off(scheme): clear(account) return + if is_pool(scheme): + clear(account) + account.use_proxy_pool = True + return + employee_id = getattr(account, "employee_id", "") + if uses_pool(account) and employee_id: + from euniv.proxy_pool import release + + release(str(employee_id)) + account.use_proxy_pool = False kind, address, number, user = validate_parts(scheme, host, port, username) if password is not None and len(str(password)) > 256: raise ProxyError("代理密码过长") @@ -132,3 +166,24 @@ def clear(account) -> None: account.proxy_port = None account.proxy_username = "" account.proxy_password_cipher = "" + account.use_proxy_pool = False + employee_id = getattr(account, "employee_id", "") + if employee_id: + from euniv.proxy_pool import release + + release(str(employee_id)) + + +def bind_url(account) -> str | None: + if uses_pool(account): + from euniv.proxy_pool import acquire + + return acquire(str(account.employee_id)) + return url_of(account) + + +def is_proxy_failure(exc: BaseException) -> bool: + if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, httpx.ConnectTimeout)): + return True + text = f"{type(exc).__name__} {exc}".lower() + return "proxy" in text or "socks" in text diff --git a/backend/euniv/proxy_pool.py b/backend/euniv/proxy_pool.py new file mode 100644 index 0000000..28e545e --- /dev/null +++ b/backend/euniv/proxy_pool.py @@ -0,0 +1,452 @@ +"""自有代理池:多上游汇聚、延迟检测、均匀分配、失效剔除。""" + +from __future__ import annotations + +import logging +import threading +import time +from concurrent.futures import ThreadPoolExecutor, as_completed +from datetime import datetime, timezone +from urllib.parse import urlparse + +import httpx +from sqlalchemy import case, func, select +from sqlalchemy.orm import Session + +from euniv.client import EUNIV, USER_AGENT +from euniv.collectors import collect_all, is_china, source_title +from euniv.db import SessionLocal +from euniv.models import ProxyNode, ProxyPoolSync +from euniv.proxy import build_proxy_url + +log = logging.getLogger(__name__) + +FETCH_INTERVAL = 300 +LATENCY_LIMIT = 3.0 +LATENCY_LIMIT_MS = 3000 +PROBE_CONCURRENCY = 16 +MAX_PROBES = 80 +MAX_SWITCHES = 8 +PROBE_URL = EUNIV + "/" +STATUS_ALIVE = "alive" +STATUS_DEAD = "dead" +STATUS_NEW = "new" + +_ANONYMITY = {"elite": "高匿名", "anonymous": "匿名", "transparent": "透明"} +_STATUS = {STATUS_ALIVE: "可用", STATUS_DEAD: "失效", STATUS_NEW: "待检测"} + +_assign_lock = threading.Lock() +_holds: dict[str, int] = {} +_refresh_lock = threading.Lock() +_stop: threading.Event | None = None + + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +def _url(node: ProxyNode) -> str: + return build_proxy_url(node.scheme, node.host, int(node.port)) + + +def _sync_row(db: Session) -> ProxyPoolSync: + row = db.get(ProxyPoolSync, 1) + if row is None: + row = ProxyPoolSync(id=1) + db.add(row) + db.flush() + return row + + +def _counts(db: Session) -> tuple[int, int, int]: + rows = db.execute(select(ProxyNode.status, func.count()).group_by(ProxyNode.status)).all() + tallies = {str(status): int(count) for status, count in rows} + return tallies.get(STATUS_ALIVE, 0), tallies.get(STATUS_DEAD, 0), tallies.get(STATUS_NEW, 0) + + +def _store_counts(db: Session, sync: ProxyPoolSync) -> None: + sync.alive_count, sync.dead_count, sync.new_count = _counts(db) + + +def _iso(value: datetime | None) -> str | None: + if value is None: + return None + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value.isoformat() + + +def _anonymity_label(value: str) -> str: + return _ANONYMITY.get((value or "").strip().lower(), value or "—") + + +def _country_label(value: str) -> str: + text = (value or "").strip() + if not text: + return "—" + if text.lower() in {"cn", "chn", "china"} or "中国" in text: + return "中国" + return text + + +def _status_label(value: str) -> str: + return _STATUS.get(value, value or "—") + + +def view_item(node: ProxyNode) -> dict: + return { + "id": node.id, + "scheme": node.scheme, + "host": node.host, + "port": int(node.port), + "country": _country_label(node.country), + "anonymity": _anonymity_label(node.anonymity), + "source": source_title(node.source), + "status": node.status, + "status_text": _status_label(node.status), + "latency_ms": node.latency_ms, + "last_checked_at": _iso(node.last_checked_at), + "last_ok_at": _iso(node.last_ok_at), + "note": node.fail_reason or "", + } + + +def sync_view(db: Session) -> dict: + sync = _sync_row(db) + alive, dead, pending = _counts(db) + return { + "fetched_at": _iso(sync.fetched_at), + "checked_at": _iso(sync.checked_at), + "running": bool(sync.running), + "message": sync.message or "", + "alive": alive, + "dead": dead, + "pending": pending, + "total": alive + dead + pending, + } + + +def page(db: Session, q: str = "", status: str = "", offset: int = 0, limit: int = 50) -> dict: + bounded = min(max(int(limit), 1), 100) + start = max(int(offset), 0) + query = select(ProxyNode) + count_query = select(func.count()).select_from(ProxyNode) + kind = (status or "").strip().lower() + if kind in {STATUS_ALIVE, STATUS_DEAD, STATUS_NEW}: + query = query.where(ProxyNode.status == kind) + count_query = count_query.where(ProxyNode.status == kind) + text = (q or "").strip() + if text: + like = f"%{text}%" + query = query.where(ProxyNode.host.like(like)) + count_query = count_query.where(ProxyNode.host.like(like)) + rank = case((ProxyNode.status == STATUS_ALIVE, 0), (ProxyNode.status == STATUS_NEW, 1), else_=2) + query = query.order_by(rank, ProxyNode.latency_ms.is_(None), ProxyNode.latency_ms, ProxyNode.id) + total = int(db.scalar(count_query) or 0) + nodes = db.scalars(query.offset(start).limit(bounded)).all() + payload = sync_view(db) + payload["items"] = [view_item(node) for node in nodes] + payload["total"] = total + payload["offset"] = start + payload["limit"] = bounded + return payload + + +def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]: + url = build_proxy_url(scheme, host, port) + started = time.perf_counter() + try: + with httpx.Client( + proxy=url, + timeout=LATENCY_LIMIT, + follow_redirects=True, + headers={"User-Agent": USER_AGENT}, + ) as client: + response = client.get(PROBE_URL) + latency = int((time.perf_counter() - started) * 1000) + if latency > LATENCY_LIMIT_MS: + return False, latency, "超时" + if response.status_code >= 500: + return False, latency, f"HTTP {response.status_code}" + return True, latency, "" + except Exception as exc: + latency = int((time.perf_counter() - started) * 1000) + return False, latency, _short_reason(exc) + + +def _short_reason(exc: BaseException) -> str: + if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException)): + return "超时" + if isinstance(exc, (httpx.ProxyError, httpx.ConnectError)): + return "无法连接" + text = str(exc).strip() or type(exc).__name__ + return text[:200] + + +def _find_node(db: Session, scheme: str, host: str, port: int) -> ProxyNode | None: + return db.scalars( + select(ProxyNode).where( + ProxyNode.scheme == scheme, + ProxyNode.host == host, + ProxyNode.port == port, + ) + ).first() + + +def _parse_proxy_url(value: str | None) -> tuple[str, str, int] | None: + text = (value or "").strip() + if not text: + return None + parsed = urlparse(text) + host = parsed.hostname + if not host or parsed.port is None: + return None + return (parsed.scheme or "http").lower(), host, int(parsed.port) + + +def _evict_node(node_id: int) -> None: + for employee_id, held in list(_holds.items()): + if held == node_id: + _holds.pop(employee_id, None) + + +def acquire(employee_id: str) -> str | None: + key = (employee_id or "").strip() + if not key: + return None + with SessionLocal() as db, _assign_lock: + held_id = _holds.get(key) + if held_id: + held = db.get(ProxyNode, held_id) + if held is not None and held.status == STATUS_ALIVE: + return _url(held) + _holds.pop(key, None) + nodes = list(db.scalars(select(ProxyNode).where(ProxyNode.status == STATUS_ALIVE)).all()) + if not nodes: + return None + load = {node.id: 0 for node in nodes} + for node_id in _holds.values(): + if node_id in load: + load[node_id] += 1 + nodes.sort(key=lambda node: (load[node.id], node.assigns, node.id)) + pick = nodes[0] + _holds[key] = pick.id + pick.assigns = int(pick.assigns or 0) + 1 + db.commit() + return _url(pick) + + +def release(employee_id: str) -> None: + with _assign_lock: + _holds.pop((employee_id or "").strip(), None) + + +def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None: + key = (employee_id or "").strip() + parsed = _parse_proxy_url(proxy_url) + with SessionLocal() as db, _assign_lock: + node = None + node_id = _holds.pop(key, None) + if node_id: + node = db.get(ProxyNode, node_id) + if node is None and parsed is not None: + node = _find_node(db, parsed[0], parsed[1], parsed[2]) + if node is None: + return + node.status = STATUS_DEAD + node.fail_reason = (reason or "失效")[:200] + node.last_checked_at = _now() + _evict_node(node.id) + db.commit() + + +def refresh_once() -> dict: + if not _refresh_lock.acquire(blocking=False): + with SessionLocal() as db: + return sync_view(db) + try: + return _refresh_body() + finally: + _refresh_lock.release() + + +def _refresh_body() -> dict: + with SessionLocal() as db: + sync = _sync_row(db) + sync.running = True + sync.message = "" + db.commit() + try: + candidates = collect_all() + with SessionLocal() as db: + sync = _sync_row(db) + sync.fetched_at = _now() + existing = { + (node.scheme, node.host, int(node.port)): node + for node in db.scalars(select(ProxyNode)).all() + } + new_ids: list[int] = [] + alive_ids: list[int] = [] + for item in candidates: + if not is_china(item.country): + continue + key = (item.scheme, item.host, item.port) + node = existing.get(key) + if node is None: + node = ProxyNode( + scheme=item.scheme, + host=item.host, + port=item.port, + country=item.country, + anonymity=item.anonymity, + source=item.source, + status=STATUS_NEW, + ) + db.add(node) + db.flush() + existing[key] = node + new_ids.append(node.id) + continue + node.country = item.country or node.country + node.anonymity = item.anonymity or node.anonymity + node.source = item.source or node.source + if node.status == STATUS_DEAD: + continue + if node.status == STATUS_NEW: + new_ids.append(node.id) + elif node.status == STATUS_ALIVE: + alive_ids.append(node.id) + for node in existing.values(): + if node.status == STATUS_ALIVE and node.id not in alive_ids and node.id not in new_ids: + alive_ids.append(node.id) + db.commit() + probe_ids = _pick_probe_ids(db, new_ids, alive_ids) + nodes = [db.get(ProxyNode, node_id) for node_id in probe_ids] + snapshot = [ + (node.id, node.scheme, node.host, int(node.port)) + for node in nodes + if node is not None + ] + + results = _probe_many(snapshot) + with SessionLocal() as db, _assign_lock: + sync = _sync_row(db) + for node_id, ok, latency, reason in results: + node = db.get(ProxyNode, node_id) + if node is None: + continue + if node.status == STATUS_DEAD: + continue + node.last_checked_at = _now() + node.latency_ms = latency + if ok: + node.status = STATUS_ALIVE + node.last_ok_at = node.last_checked_at + node.fail_reason = "" + else: + node.status = STATUS_DEAD + node.fail_reason = reason or "失效" + _evict_node(node.id) + sync.checked_at = _now() + sync.running = False + _store_counts(db, sync) + if sync.alive_count: + sync.message = "" + elif not candidates: + sync.message = "没有获取到可用代理" + else: + sync.message = "当前没有可用代理" + db.commit() + return sync_view(db) + except Exception: + log.exception("代理池更新失败") + with SessionLocal() as db: + sync = _sync_row(db) + sync.running = False + sync.message = "没有更新" + db.commit() + return sync_view(db) + + +def _pick_probe_ids(db: Session, new_ids: list[int], alive_ids: list[int]) -> list[int]: + ordered: list[int] = [] + seen: set[int] = set() + for node_id in new_ids: + if node_id not in seen: + seen.add(node_id) + ordered.append(node_id) + if len(ordered) >= MAX_PROBES: + return ordered[:MAX_PROBES] + alive_nodes = [ + node + for node in (db.get(ProxyNode, node_id) for node_id in alive_ids) + if node is not None + ] + alive_nodes.sort(key=lambda node: (node.last_checked_at is not None, node.last_checked_at or _now(), node.id)) + for node in alive_nodes: + if node.id in seen: + continue + seen.add(node.id) + ordered.append(node.id) + if len(ordered) >= MAX_PROBES: + break + return ordered + + +def _probe_many(nodes: list[tuple[int, str, str, int]]) -> list[tuple[int, bool, int, str]]: + if not nodes: + return [] + workers = min(PROBE_CONCURRENCY, len(nodes)) + results: list[tuple[int, bool, int, str]] = [] + with ThreadPoolExecutor(max_workers=workers) as pool: + futures = { + pool.submit(probe, scheme, host, port): node_id + for node_id, scheme, host, port in nodes + } + for future in as_completed(futures): + node_id = futures[future] + try: + ok, latency, reason = future.result() + except Exception as exc: + ok, latency, reason = False, LATENCY_LIMIT_MS, _short_reason(exc) + results.append((node_id, ok, latency, reason)) + return results + + +def request_refresh() -> dict: + with SessionLocal() as db: + sync = _sync_row(db) + already = bool(sync.running) + if not already: + sync.running = True + sync.message = "" + db.commit() + payload = sync_view(db) + else: + payload = sync_view(db) + if not already: + threading.Thread(target=refresh_once, name="euniv-proxy-pool-once", daemon=True).start() + payload["running"] = True + return payload + + +def start_proxy_pool() -> threading.Event: + global _stop + stop = threading.Event() + _stop = stop + + def loop() -> None: + if stop.wait(8): + return + while not stop.is_set(): + started = time.monotonic() + try: + refresh_once() + except Exception: + log.exception("代理池更新失败") + delay = max(1.0, FETCH_INTERVAL - (time.monotonic() - started)) + if stop.wait(delay): + return + + threading.Thread(target=loop, name="euniv-proxy-pool", daemon=True).start() + return stop diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 7210991..f1aade2 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -69,15 +69,28 @@ def _persist(db: Session, employee_id: str, password: str, client: EunivClient, def _client(factory, employee_id: str, password: str, account: Account | None = None): - from euniv.proxy import url_of + from euniv.proxy import bind_url - proxy = url_of(account) if account is not None else None + proxy = bind_url(account) if account is not None else None try: return factory(employee_id, password, proxy) except TypeError: return factory(employee_id, password) +def _switch_proxy(account: Account | None, client, exc: BaseException) -> bool: + from euniv.proxy import is_proxy_failure, uses_pool + from euniv.proxy_pool import mark_failed + + if account is None or not uses_pool(account): + return False + proxy = getattr(client, "proxy", None) + if not proxy or not is_proxy_failure(exc): + return False + mark_failed(account.employee_id, proxy, str(exc)[:200]) + return True + + def login_and_store( db: Session, employee_id: str, @@ -93,33 +106,55 @@ def login_and_store( _request_course_sync(employee_id) return {"employee_id": employee_id} _drop_employee(employee_id) - client = _client(client_factory, employee_id, password, account) + from euniv.proxy_pool import MAX_SWITCHES + held = False + client = None + last_exc: BaseException | None = None try: - try: - profile = client.login(manual=manual, auto_attempts=auto_attempts) - except ManualJigsaw as exc: - attempt_id = secrets.token_urlsafe(18) - _pending[attempt_id] = PendingLogin(client, employee_id, password, time.time()) - held = True - return {"attempt_id": attempt_id, "jigsaw": exc.puzzle} - _persist(db, employee_id, password, client, profile) - _request_course_sync(employee_id) - return {"employee_id": employee_id} + for _ in range(MAX_SWITCHES + 1): + client = _client(client_factory, employee_id, password, account) + try: + profile = client.login(manual=manual, auto_attempts=auto_attempts) + except ManualJigsaw as exc: + attempt_id = secrets.token_urlsafe(18) + _pending[attempt_id] = PendingLogin(client, employee_id, password, time.time()) + held = True + return {"attempt_id": attempt_id, "jigsaw": exc.puzzle} + except Exception as exc: + last_exc = exc + if _switch_proxy(account, client, exc): + client.close() + client = None + continue + raise + _persist(db, employee_id, password, client, profile) + _request_course_sync(employee_id) + return {"employee_id": employee_id} + if last_exc is not None: + raise last_exc + raise RuntimeError("登录失败") finally: - if not held: + if client is not None and not held: client.close() def _credential_still_valid(account: Account, client_factory) -> bool: - client = _client(client_factory, account.employee_id, decrypt_secret(account.password_cipher), account) - try: - client.restore(json.loads(decrypt_secret(account.credential_cipher))) - return bool(client.credential_alive()) - except Exception: - return False - finally: - client.close() + from euniv.proxy_pool import MAX_SWITCHES + + password = decrypt_secret(account.password_cipher) + for _ in range(MAX_SWITCHES + 1): + client = _client(client_factory, account.employee_id, password, account) + try: + client.restore(json.loads(decrypt_secret(account.credential_cipher))) + return bool(client.credential_alive()) + except Exception as exc: + if _switch_proxy(account, client, exc): + continue + return False + finally: + client.close() + return False def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict: @@ -177,39 +212,54 @@ def _auto_attempts(db: Session) -> int: def _live(db: Session, employee_id: str, client_factory, read): + from euniv.proxy_pool import MAX_SWITCHES + account = db.get(Account, employee_id) if account is None: raise RuntimeError("请先登录") credential = json.loads(decrypt_secret(account.credential_cipher)) if account.credential_cipher else {} attempts = _auto_attempts(db) - client = _client(client_factory, employee_id, decrypt_secret(account.password_cipher), account) - try: - if credential.get("yxt_token"): - client.restore(credential) - else: - try: - client.authorize(client.login(manual=False, auto_attempts=attempts)) - except ManualJigsaw: - raise RuntimeError("登录需要重新验证,请重新登录") from None + password = decrypt_secret(account.password_cipher) + last_exc: BaseException | None = None + for _ in range(MAX_SWITCHES + 1): + client = _client(client_factory, employee_id, password, account) try: - data = read(client) - except SessionExpired: + if credential.get("yxt_token"): + client.restore(credential) + else: + try: + client.authorize(client.login(manual=False, auto_attempts=attempts)) + except ManualJigsaw: + raise RuntimeError("登录需要重新验证,请重新登录") from None try: - client.authorize(client.login(manual=False, auto_attempts=attempts)) - except ManualJigsaw: - raise RuntimeError("登录需要重新验证,请重新登录") from None - data = read(client) - updated = client.export_credential() - with _credential_lock(employee_id): - db.refresh(account) - current_raw = account.credential_cipher - current = json.loads(decrypt_secret(current_raw)) if current_raw else {} - if _dump(updated) != _dump(current) and _dump(current) == _dump(credential): - account.credential_cipher = encrypt_secret(_dump(updated)) - db.commit() - return data - finally: - client.close() + data = read(client) + except SessionExpired: + try: + client.authorize(client.login(manual=False, auto_attempts=attempts)) + except ManualJigsaw: + raise RuntimeError("登录需要重新验证,请重新登录") from None + data = read(client) + updated = client.export_credential() + with _credential_lock(employee_id): + db.refresh(account) + current_raw = account.credential_cipher + current = json.loads(decrypt_secret(current_raw)) if current_raw else {} + if _dump(updated) != _dump(current) and _dump(current) == _dump(credential): + account.credential_cipher = encrypt_secret(_dump(updated)) + db.commit() + return data + except RuntimeError: + raise + except Exception as exc: + last_exc = exc + if _switch_proxy(account, client, exc): + continue + raise + finally: + client.close() + if last_exc is not None: + raise last_exc + raise RuntimeError("请先登录") def revoke_credential(db: Session, employee_id: str) -> None: @@ -245,22 +295,33 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None: checked_alive = False hours = "" try: + from euniv.proxy_pool import MAX_SWITCHES + password = decrypt_secret(account.password_cipher) previous = json.loads(decrypt_secret(account.credential_cipher)) - client = _client(client_factory, employee_id, password, account) - client.restore(previous) - if client.credential_alive(): - updated = client.export_credential() - if _dump(updated) != _dump(previous): - account.credential_cipher = encrypt_secret(_dump(updated)) - valid = True - checked_alive = True - else: - profile = client.login(manual=False, auto_attempts=attempts) - _persist(db, employee_id, password, client, profile) - valid = True - if valid: - hours = _month_hours(client) + for _ in range(MAX_SWITCHES + 1): + client = _client(client_factory, employee_id, password, account) + try: + client.restore(previous) + if client.credential_alive(): + updated = client.export_credential() + if _dump(updated) != _dump(previous): + account.credential_cipher = encrypt_secret(_dump(updated)) + valid = True + checked_alive = True + else: + profile = client.login(manual=False, auto_attempts=attempts) + _persist(db, employee_id, password, client, profile) + valid = True + if valid: + hours = _month_hours(client) + break + except Exception as exc: + if _switch_proxy(account, client, exc): + client.close() + client = None + continue + raise except Exception: db.rollback() valid = False diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 7f27ac6..4b4c65d 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -26,7 +26,12 @@ def fresh_database(): connection.execute(text("DROP TABLE IF EXISTS system_config")) connection.execute(text("DROP TABLE IF EXISTS courses")) connection.execute(text("DROP TABLE IF EXISTS course_sync")) + connection.execute(text("DROP TABLE IF EXISTS proxy_nodes")) + connection.execute(text("DROP TABLE IF EXISTS proxy_pool_sync")) connection.execute(text("DROP TABLE IF EXISTS alembic_version")) init_db() ensure_admin_seed() load_admin_identity() + from euniv.proxy_pool import _holds + + _holds.clear() diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index d96c968..9fbc9a7 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -122,6 +122,7 @@ def test_login_stores_password_and_credential_only() -> None: "study_start_minute", "study_start_second", "course_workers", + "use_proxy_pool", } home = client.get("/api/home") diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index 855205e..94a5a88 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -244,3 +244,15 @@ def test_proxy_off_scheme_clears_settings() -> None: assert account.proxy_scheme == "" assert account.proxy_host == "" assert account.proxy_port is None + + +def test_proxy_pool_scheme_enables_auto() -> None: + account = _ProxyAccount() + apply_proxy(account, "pool") + view = proxy_view(account) + assert view["enabled"] is True + assert view["scheme"] == "pool" + assert account.use_proxy_pool is True + apply_proxy(account, "http", "10.0.0.1", 8080) + assert account.use_proxy_pool is False + assert proxy_view(account)["scheme"] == "http" diff --git a/backend/tests/test_proxy_pool.py b/backend/tests/test_proxy_pool.py new file mode 100644 index 0000000..87040cc --- /dev/null +++ b/backend/tests/test_proxy_pool.py @@ -0,0 +1,284 @@ +import httpx +from fastapi.testclient import TestClient + +from euniv.collectors import ProxyCandidate, collect_all, is_china, parse_proxyhub_result +from euniv.crypto import encrypt_secret +from euniv.db import SessionLocal +from euniv.models import Account, ProxyNode +from euniv.proxy import apply as apply_proxy +from euniv.proxy import bind_url, is_proxy_failure, view_of +from euniv.proxy_pool import acquire, mark_failed, page, refresh_once, release +from euniv.proxy_pool import _holds + +INITIAL_PASSWORD = "242520" + + +def _node(host: str, port: int, status: str = "alive", scheme: str = "http", assigns: int = 0) -> ProxyNode: + node = ProxyNode( + scheme=scheme, + host=host, + port=port, + country="cn", + anonymity="elite", + source="proxyhub", + status=status, + latency_ms=200 if status == "alive" else None, + assigns=assigns, + ) + with SessionLocal() as db: + db.add(node) + db.commit() + db.refresh(node) + return node + + +def _account(employee_id: str) -> None: + with SessionLocal() as db: + db.add( + Account( + employee_id=employee_id, + password_cipher=encrypt_secret("secret"), + credential_cipher="", + ) + ) + db.commit() + + +def test_parse_proxyhub_keeps_structured_rows() -> None: + payload = { + "jsonrpc": "2.0", + "id": 1, + "result": { + "isError": False, + "structuredContent": { + "proxies": [ + {"ip": "1.1.1.1", "port": 8080, "country": "cn", "type": "http", "anonymity": "elite"}, + {"ip": "2.2.2.2", "port": 1080, "country": "cn", "type": "socks5", "anonymity": "anonymous"}, + ], + "count": 2, + }, + }, + } + rows = parse_proxyhub_result(payload) + assert [(item.scheme, item.host, item.port, item.source) for item in rows] == [ + ("http", "1.1.1.1", 8080, "proxyhub"), + ("socks5", "2.2.2.2", 1080, "proxyhub"), + ] + + +def test_china_filter_and_collect_all(monkeypatch) -> None: + assert is_china("cn") + assert is_china("中国") + assert not is_china("us") + + class Dummy: + name = "dummy" + + def collect(self): + return [ + ProxyCandidate("http", "1.1.1.1", 80, "cn", "elite", "dummy"), + ProxyCandidate("http", "8.8.8.8", 80, "us", "elite", "dummy"), + ] + + monkeypatch.setattr("euniv.collectors.collectors", lambda: [Dummy()]) + items = collect_all() + assert [(item.host, item.country) for item in items] == [("1.1.1.1", "cn")] + + +def test_acquire_spreads_accounts_and_skips_dead() -> None: + _holds.clear() + first = _node("10.0.0.1", 8001) + second = _node("10.0.0.2", 8002) + _node("10.0.0.3", 8003, status="dead") + a = acquire("u1") + b = acquire("u2") + assert {a, b} == {"http://10.0.0.1:8001", "http://10.0.0.2:8002"} + c = acquire("u3") + assert c in {a, b} + mark_failed("u1", a, "无法连接") + again = acquire("u1") + assert again == b + with SessionLocal() as db: + dead_id = first.id if a.endswith(":8001") else second.id + dead = db.get(ProxyNode, dead_id) + assert dead is not None + assert dead.status == "dead" + assert acquire("u1") == again + release("u1") + release("u2") + release("u3") + + +def test_empty_pool_returns_direct() -> None: + _holds.clear() + _node("10.0.0.9", 9, status="dead") + assert acquire("nobody") is None + + +def test_bind_url_uses_pool_or_manual() -> None: + _holds.clear() + _node("10.0.0.4", 8004) + _account("pool-user") + _account("manual-user") + with SessionLocal() as db: + pool_user = db.get(Account, "pool-user") + manual_user = db.get(Account, "manual-user") + assert pool_user is not None and manual_user is not None + apply_proxy(pool_user, "pool") + apply_proxy(manual_user, "http", "127.0.0.1", 7890) + db.commit() + db.refresh(pool_user) + db.refresh(manual_user) + assert view_of(pool_user)["scheme"] == "pool" + assert bind_url(pool_user) == "http://10.0.0.4:8004" + assert bind_url(manual_user) == "http://127.0.0.1:7890" + apply_proxy(pool_user, "off") + db.commit() + db.refresh(pool_user) + assert bind_url(pool_user) is None + + +def test_refresh_marks_slow_and_keeps_fast(monkeypatch) -> None: + _holds.clear() + monkeypatch.setattr( + "euniv.proxy_pool.collect_all", + lambda: [ + ProxyCandidate("http", "1.1.1.1", 80, "cn", "elite", "proxyhub"), + ProxyCandidate("http", "2.2.2.2", 80, "cn", "elite", "proxyhub"), + ProxyCandidate("http", "3.3.3.3", 80, "us", "elite", "proxyhub"), + ], + ) + + def fake_probe(scheme: str, host: str, port: int): + if host == "1.1.1.1": + return True, 800, "" + return False, 4000, "超时" + + monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe) + payload = refresh_once() + assert payload["alive"] == 1 + assert payload["dead"] == 1 + with SessionLocal() as db: + listed = page(db) + hosts = {item["host"]: item for item in listed["items"]} + assert hosts["1.1.1.1"]["status"] == "alive" + assert hosts["1.1.1.1"]["latency_ms"] == 800 + assert hosts["2.2.2.2"]["status"] == "dead" + assert "3.3.3.3" not in hosts + + +def test_failed_proxy_is_not_reprobed(monkeypatch) -> None: + _holds.clear() + dead = _node("9.9.9.9", 99, status="dead") + monkeypatch.setattr( + "euniv.proxy_pool.collect_all", + lambda: [ProxyCandidate("http", "9.9.9.9", 99, "cn", "elite", "proxyhub")], + ) + called = [] + + def fake_probe(scheme: str, host: str, port: int): + called.append(host) + return True, 10, "" + + monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe) + refresh_once() + assert called == [] + with SessionLocal() as db: + node = db.get(ProxyNode, dead.id) + assert node is not None + assert node.status == "dead" + + +def test_is_proxy_failure_detects_connect_errors() -> None: + assert is_proxy_failure(httpx.ConnectError("boom")) + assert is_proxy_failure(httpx.ConnectTimeout("late")) + assert not is_proxy_failure(RuntimeError("登录需要重新验证")) + + +def test_admin_proxy_page_and_pool_assignment() -> None: + import euniv.api as api_module + + _holds.clear() + _node("10.0.0.5", 8005) + _account("a-user") + _account("b-user") + client = TestClient(api_module.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + listed = client.get("/api/admin/proxies") + assert listed.status_code == 200 + body = listed.json() + assert body["alive"] == 1 + assert body["items"][0]["host"] == "10.0.0.5" + assert body["items"][0]["status_text"] == "可用" + saved = client.put( + "/api/admin/users/proxy", + json={"employee_ids": ["a-user", "b-user"], "scheme": "pool"}, + ) + assert saved.status_code == 200 + users = client.get("/api/admin/users").json() + one = next(item for item in users if item["employee_id"] == "a-user") + two = next(item for item in users if item["employee_id"] == "b-user") + assert one["has_proxy"] is True + assert one["proxy"] == "自动" + assert two["proxy"] == "自动" + detail = client.get("/api/admin/users/a-user/proxy") + assert detail.json()["scheme"] == "pool" + assert detail.json()["enabled"] is True + + +def test_user_can_enable_pool_proxy() -> None: + import euniv.api as api_module + import euniv.service as service_module + + class FakeClient: + def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: + self.login_name = login_name + self.password = password + self.proxy = proxy + self._profile = { + "token": "ucs-1", + "accountId": login_name, + "userId": "u1", + "ssoinfo": "sso", + "unionId": "", + } + self._token = "yxt-1" + + def close(self) -> None: + return None + + def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: + return dict(self._profile) + + def authorize(self, profile: dict) -> None: + return None + + def export_credential(self) -> dict: + return { + "ucs_token": "ucs-1", + "ucs_account_id": self.login_name, + "ucs_user_id": "u1", + "ucs_ssoinfo": "sso", + "ucs_union_id": "", + "yxt_token": "yxt-1", + } + + def restore(self, credential: dict) -> None: + return None + + def credential_alive(self) -> bool: + return True + + api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( + db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts + ) + client = TestClient(api_module.app) + assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 + saved = client.put("/api/settings/proxy", json={"scheme": "pool"}) + assert saved.status_code == 200 + assert saved.json()["scheme"] == "pool" + assert saved.json()["enabled"] is True + with SessionLocal() as db: + account = db.get(Account, "6650000146") + assert account is not None + assert account.use_proxy_pool is True diff --git a/web/src/features/admin/ProxiesView.vue b/web/src/features/admin/ProxiesView.vue new file mode 100644 index 0000000..c9e62d4 --- /dev/null +++ b/web/src/features/admin/ProxiesView.vue @@ -0,0 +1,273 @@ + + + diff --git a/web/src/features/admin/UsersView.vue b/web/src/features/admin/UsersView.vue index 5d1092c..b6add2e 100644 --- a/web/src/features/admin/UsersView.vue +++ b/web/src/features/admin/UsersView.vue @@ -49,9 +49,10 @@ const proxyPort = ref(null); const proxyUser = ref(""); const proxyPassword = ref(""); const proxyHasPassword = ref(false); -const proxyOff = computed(() => proxyScheme.value === "off"); +const proxyManual = computed(() => proxyScheme.value !== "off" && proxyScheme.value !== "pool"); const proxyOptions = [ { label: "关闭", value: "off" }, + { label: "自动", value: "pool" }, { label: "HTTP", value: "http" }, { label: "HTTPS", value: "https" }, { label: "SOCKS4", value: "socks4" }, @@ -388,7 +389,7 @@ function proxyPasswordPayload() { async function saveProxy() { if (proxySaving.value || !proxyIds.value.length) return; proxyError.value = ""; - if (!proxyOff.value) { + if (proxyManual.value) { if (!proxyHost.value.trim()) { proxyError.value = "请填写代理地址"; return; @@ -404,16 +405,16 @@ async function saveProxy() { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify( - proxyOff.value - ? { employee_ids: proxyIds.value, scheme: "off" } - : { + proxyManual.value + ? { employee_ids: proxyIds.value, scheme: proxyScheme.value, host: proxyHost.value.trim(), port: proxyPort.value, username: proxyUser.value.trim(), password: proxyPasswordPayload(), - }, + } + : { employee_ids: proxyIds.value, scheme: proxyScheme.value }, ), }); const payload: unknown = await response.json().catch(() => ({})); @@ -694,15 +695,15 @@ onMounted(() => {
- +
- +
- +
@@ -713,7 +714,7 @@ onMounted(() => { show-password-on="click" :placeholder="proxyIds.length === 1 && proxyHasPassword ? '已保存,留空则保持' : '可不填'" autocomplete="new-password" - :disabled="proxyOff" + :disabled="!proxyManual" />
diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index 76a541e..ef78ba2 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -220,9 +220,10 @@ const proxyPort = ref(null); const proxyUser = ref(""); const proxyPassword = ref(""); const proxyHasPassword = ref(false); -const proxyOff = computed(() => proxyScheme.value === "off"); +const proxyManual = computed(() => proxyScheme.value !== "off" && proxyScheme.value !== "pool"); const proxyOptions = [ { label: "关闭", value: "off" }, + { label: "自动", value: "pool" }, { label: "HTTP", value: "http" }, { label: "HTTPS", value: "https" }, { label: "SOCKS4", value: "socks4" }, @@ -253,7 +254,7 @@ function proxyPasswordPayload() { async function saveProxy() { if (proxySaving.value) return; proxyError.value = ""; - if (!proxyOff.value) { + if (proxyManual.value) { if (!proxyHost.value.trim()) { proxyError.value = "请填写代理地址"; return; @@ -269,15 +270,15 @@ async function saveProxy() { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify( - proxyOff.value - ? { scheme: "off" } - : { + proxyManual.value + ? { scheme: proxyScheme.value, host: proxyHost.value.trim(), port: proxyPort.value, username: proxyUser.value.trim(), password: proxyPasswordPayload(), - }, + } + : { scheme: proxyScheme.value }, ), }); const data = await res.json().catch(() => ({})); @@ -287,7 +288,7 @@ async function saveProxy() { } proxyPassword.value = ""; proxyHasPassword.value = data.has_password === true; - if (proxyOff.value) { + if (!proxyManual.value) { proxyHost.value = ""; proxyPort.value = null; proxyUser.value = ""; @@ -424,15 +425,15 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadWorkers(); loadProxy
- +
- +
- +
@@ -444,7 +445,7 @@ onMounted(() => { refresh(); loadTarget(); loadStart(); loadWorkers(); loadProxy show-password-on="click" :placeholder="proxyHasPassword ? '已保存,留空则保持' : '可不填'" autocomplete="new-password" - :disabled="proxyOff" + :disabled="!proxyManual" />
diff --git a/web/src/shell/AdminShell.vue b/web/src/shell/AdminShell.vue index eba4dd8..748fbe8 100644 --- a/web/src/shell/AdminShell.vue +++ b/web/src/shell/AdminShell.vue @@ -6,6 +6,7 @@ import { isDark, toggleTheme } from "../shared/theme"; import { adminNavOptions, type AdminPageKey } from "./adminNavigation"; import UsersView from "../features/admin/UsersView.vue"; import CoursesView from "../features/admin/CoursesView.vue"; +import ProxiesView from "../features/admin/ProxiesView.vue"; import SettingsView from "../features/admin/SettingsView.vue"; defineProps<{ username: string }>(); @@ -15,7 +16,7 @@ const collapsed = ref(window.innerWidth < 800); function pageFromHash(): AdminPageKey { const name = window.location.hash.replace(/^#\/?/, ""); - if (name === "courses" || name === "settings" || name === "users") return name; + if (name === "courses" || name === "proxies" || name === "settings" || name === "users") return name; return "users"; } @@ -43,7 +44,7 @@ onUnmounted(() => { }); function onMenu(key: string) { - if (key === "users" || key === "courses" || key === "settings") { + if (key === "users" || key === "courses" || key === "proxies" || key === "settings") { page.value = key; remember(key); } @@ -105,6 +106,7 @@ function onMenu(key: string) { + diff --git a/web/src/shell/adminNavigation.ts b/web/src/shell/adminNavigation.ts index 1bc385d..e243e1d 100644 --- a/web/src/shell/adminNavigation.ts +++ b/web/src/shell/adminNavigation.ts @@ -1,16 +1,17 @@ import type { Component } from "vue"; import { h } from "vue"; import { NIcon } from "naive-ui"; -import { LibraryOutline, PeopleOutline, SettingsOutline } from "@vicons/ionicons5"; +import { GlobeOutline, LibraryOutline, PeopleOutline, SettingsOutline } from "@vicons/ionicons5"; function renderIcon(icon: Component) { return () => h(NIcon, null, { default: () => h(icon) }); } -export type AdminPageKey = "users" | "courses" | "settings"; +export type AdminPageKey = "users" | "courses" | "proxies" | "settings"; export const adminNavOptions = [ { label: "用户管理", key: "users" as const, icon: renderIcon(PeopleOutline) }, { label: "课程清单", key: "courses" as const, icon: renderIcon(LibraryOutline) }, + { label: "代理", key: "proxies" as const, icon: renderIcon(GlobeOutline) }, { label: "系统配置", key: "settings" as const, icon: renderIcon(SettingsOutline) }, ];