From 2fc5a0421b6e2db102cf90dbe8aa2856ef4e641a Mon Sep 17 00:00:00 2001 From: Nixevol Date: Tue, 17 Nov 2026 21:15:41 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=87=AA=E5=8A=A8=E4=BB=A3=E7=90=86?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E5=90=91=E6=8E=A5=E5=8F=A3=E9=A2=86=E5=8F=96?= =?UTF-8?q?=EF=BC=8C=E5=8E=BB=E6=8E=89=20ProxyHub=20=E5=92=8C=E4=BB=A3?= =?UTF-8?q?=E7=90=86=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/admin/routes.py | 47 +- .../alembic/versions/0011_drop_proxy_list.py | 50 ++ backend/euniv/api.py | 7 +- backend/euniv/autostudy.py | 164 +++- backend/euniv/collectors.py | 264 ------ backend/euniv/courses.py | 22 + backend/euniv/models.py | 38 +- backend/euniv/proxy_pool.py | 772 +++--------------- backend/euniv/service.py | 51 +- backend/tests/conftest.py | 3 +- backend/tests/test_proxy_pool.py | 437 ++++------ web/src/features/admin/ProxiesView.vue | 434 ---------- web/src/shell/AdminShell.vue | 8 +- web/src/shell/adminNavigation.ts | 5 +- 14 files changed, 559 insertions(+), 1743 deletions(-) create mode 100644 backend/alembic/versions/0011_drop_proxy_list.py delete mode 100644 backend/euniv/collectors.py delete mode 100644 web/src/features/admin/ProxiesView.vue diff --git a/backend/admin/routes.py b/backend/admin/routes.py index e42b534..33d89f6 100644 --- a/backend/admin/routes.py +++ b/backend/admin/routes.py @@ -2,7 +2,7 @@ from __future__ import annotations -from fastapi import APIRouter, Depends, HTTPException, Path, Query, Request, Response +from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response from pydantic import BaseModel from sqlalchemy.orm import Session @@ -24,12 +24,6 @@ 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 ProxyProbeError -from euniv.proxy_pool import page as proxy_page -from euniv.proxy_pool import probe_state as proxy_probe_state -from euniv.proxy_pool import request_probe as request_proxy_probe -from euniv.proxy_pool import probe_one as probe_proxy_one -from euniv.proxy_pool import request_refresh as request_proxy_refresh public_router = APIRouter() admin_router = APIRouter(prefix="/api/admin") @@ -79,10 +73,6 @@ class AdminStudySettingsBody(BaseModel): password: str | None = None -class AdminProxyProbeBody(BaseModel): - ids: list[int] | None = None - - def require_admin(request: Request, db: Session = Depends(get_db)) -> str: if not admin_session_active(request.cookies, load_config(db).admin_sessions_valid_after): raise HTTPException(status_code=401, detail="未登录") @@ -141,41 +131,6 @@ def get_courses( return course_page(db, q, start, bounded, kind) -@admin_router.get("/proxies") -def get_proxies( - q: str = "", - status: str = "", - offset: int = Query(default=0, ge=0, le=10**9), - limit: int = Query(default=50, ge=1, le=10**9), - 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.post("/proxies/probe") -def post_proxies_probe(body: AdminProxyProbeBody, _: str = Depends(require_admin)) -> dict: - return request_proxy_probe(body.ids) - - -@admin_router.get("/proxies/probe") -def get_proxies_probe(_: str = Depends(require_admin)) -> dict: - return proxy_probe_state() - - -@admin_router.post("/proxies/{proxy_id}/probe") -def post_proxy_probe(proxy_id: int = Path(ge=1, le=10**9), _: str = Depends(require_admin)) -> dict: - try: - return probe_proxy_one(proxy_id) - except ProxyProbeError as exc: - raise HTTPException(status_code=404, detail=str(exc)) from exc - - @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/alembic/versions/0011_drop_proxy_list.py b/backend/alembic/versions/0011_drop_proxy_list.py new file mode 100644 index 0000000..166a23b --- /dev/null +++ b/backend/alembic/versions/0011_drop_proxy_list.py @@ -0,0 +1,50 @@ +"""去掉本地维护的代理列表。自动代理改为用时向接口领取。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0011_drop_proxy_list" +down_revision = "0010_schedule_off_by_default" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.drop_index("ix_proxy_nodes_status", table_name="proxy_nodes") + op.drop_table("proxy_nodes") + op.drop_table("proxy_pool_sync") + + +def downgrade() -> None: + op.create_table( + "proxy_nodes", + sa.Column("id", sa.Integer(), nullable=False), + 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), server_default="", nullable=False), + sa.Column("anonymity", sa.String(length=32), server_default="", nullable=False), + sa.Column("source", sa.String(length=64), server_default="", nullable=False), + sa.Column("status", sa.String(length=16), server_default="new", nullable=False), + 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), server_default="", nullable=False), + sa.Column("assigns", sa.Integer(), server_default="0", nullable=False), + sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint("id"), + 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(), nullable=False), + 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(), server_default=sa.text("0"), nullable=False), + sa.Column("message", sa.String(length=200), server_default="", nullable=False), + sa.Column("alive_count", sa.Integer(), server_default="0", nullable=False), + sa.Column("dead_count", sa.Integer(), server_default="0", nullable=False), + sa.Column("new_count", sa.Integer(), server_default="0", nullable=False), + sa.PrimaryKeyConstraint("id"), + ) diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 385cf22..600a11c 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -97,7 +97,7 @@ async def lifespan(_app: FastAPI): acquire_instance_lock() if os.environ.get("EUNIV_DISABLE_REFRESH") == "1": - logging.getLogger("euniv.api").warning("EUNIV_DISABLE_REFRESH=1,后台刷新、自动学习和代理池都不会启动") + logging.getLogger("euniv.api").warning("EUNIV_DISABLE_REFRESH=1,后台刷新和自动学习都不会启动") init_db() ensure_admin_seed() from admin.settings import ensure_key_check @@ -109,20 +109,15 @@ async def lifespan(_app: FastAPI): attach_loop(asyncio.get_running_loop()) 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() start_pending_cleaner() 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 cd9821d..6aed4bc 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -936,7 +936,7 @@ class StudySession: def __init__(self, token: str, cookies: list[tuple[str, str, str, str]], proxy: str | None = None, employee_id: str = "", - use_pool: bool = False) -> None: + use_pool: bool = False, password: str = "") -> None: from euniv.proxy import parse_proxy self._token = token @@ -948,7 +948,8 @@ class StudySession: self._submit_logs = 0 self._proxy_lock: asyncio.Lock | None = None self._closing: list[httpx.AsyncClient] = [] - self._switches = 0 + self._password = password + self._gave_direct = False self._client: httpx.AsyncClient | None = None async def __aenter__(self) -> "StudySession": @@ -976,7 +977,7 @@ class StudySession: if not self._use_pool: return False from euniv.proxy import async_httpx_client, parse_proxy - from euniv.proxy_pool import MAX_SWITCHES, acquire, retire_if_dead + from euniv.proxy_pool import acquire, retire_if_dead if self._proxy_lock is None: self._proxy_lock = asyncio.Lock() @@ -984,15 +985,12 @@ class StudySession: async with self._proxy_lock: if failed != self._proxy: return True - if self._switches >= MAX_SWITCHES: + if self._gave_direct: return False - dead = await asyncio.to_thread(retire_if_dead, self._employee_id, failed) - if not dead: - return True - self._switches += 1 + await asyncio.to_thread(retire_if_dead, self._employee_id, failed) nxt = await asyncio.to_thread(acquire, self._employee_id) parsed = parse_proxy(nxt) - if parsed == failed: + if nxt and parsed == failed: return False client = async_httpx_client( parsed, @@ -1011,6 +1009,9 @@ class StudySession: _load_cookies(client, cookies) self._client = client self._proxy = parsed + if not parsed: + self._gave_direct = True + _set_user_status(self._employee_id, message="正在直连") return True async def _http(self, method: str, url: str, **kw: object) -> httpx.Response: @@ -1040,6 +1041,46 @@ class StudySession: "User-Agent": USER_AGENT, } + def _logged_out(self, resp: httpx.Response) -> bool: + if resp.status_code == 401: + return True + if resp.headers.get("content-type", "").startswith("application/json"): + try: + payload = resp.json() + except (json.JSONDecodeError, ValueError): + payload = None + if isinstance(payload, dict) and str(payload.get("code")) == "401": + return True + return False + + async def _switch_direct_login(self) -> bool: + """经代理访问时像是未登录。先用保存的凭据走直连复查,还有效就继续,不再登录。""" + if self._gave_direct or not self._proxy: + return False + self._gave_direct = True + packed = await asyncio.to_thread(_continue_direct, self._employee_id, self._password) + token, _user_id, _org_id, cookies, _proxy, reason = packed + if reason or not token: + return False + from euniv.proxy import async_httpx_client + + client = async_httpx_client( + None, + timeout=30, + follow_redirects=True, + headers={"User-Agent": USER_AGENT}, + event_hooks={"request": [guard_https_async]}, + ) + _load_cookies(client, cookies) + if self._client is not None: + self._closing.append(self._client) + self._client = client + self._initial_cookies = cookies + self._proxy = None + self._token = token + _set_user_status(self._employee_id, message="正在直连") + return True + async def _api(self, method: str, url: str, **kw: object) -> httpx.Response: assert self._client is not None headers = self._api_headers() @@ -1047,6 +1088,11 @@ class StudySession: if extra and isinstance(extra, dict): headers.update(extra) resp = await self._http(method, url, headers=headers, **kw) + if self._logged_out(resp) and await self._switch_direct_login(): + headers = self._api_headers() + if extra and isinstance(extra, dict): + headers.update(extra) + resp = await self._http(method, url, headers=headers, **kw) refreshed = resp.headers.get("token") or resp.headers.get("Token") if refreshed: self._token = refreshed @@ -1222,6 +1268,13 @@ class StudySession: headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}, ) html = resp.text + if _page_is_login(html) and await self._switch_direct_login(): + resp = await self._http( + "GET", + f"{EUNIV}{path}", + headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}, + ) + html = resp.text if _page_is_login(html): raise SessionExpired("学习平台登录已失效") from euniv.encrypt import note_play_html @@ -1726,6 +1779,81 @@ async def _study_package(session: StudySession, kid: str, # ── 同步准备:用 EunivClient 建立会话,导出 cookies ── +def _session_export(client: EunivClient, proxy: str | None) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]: + 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, proxy, "" + + +def _stored_credential(employee_id: str) -> dict: + """从账号记录里取出已保存的登录凭据。""" + import json + + from euniv.crypto import decrypt_secret + from euniv.db import SessionLocal + from euniv.models import Account + + with SessionLocal() as db: + account = db.get(Account, (employee_id or "").strip()) + raw = account.credential_cipher if account is not None else "" + if not raw: + return {} + try: + data = json.loads(decrypt_secret(raw)) + except Exception: + log.warning("用户 %s 的已保存凭据无法读取", employee_id, exc_info=True) + return {} + return data if isinstance(data, dict) else {} + + +def _login_direct_client(client: EunivClient, employee_id: str, password: str + ) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]: + from euniv.client import LoginRejected, ManualJigsaw + from euniv.db import SessionLocal + from euniv.service import _persist + + if not password: + return "", "", "", [], None, "expired" + try: + profile = client.login(manual=False) + with SessionLocal() as db: + _persist(db, employee_id, password, client, profile) + log.info("用户 %s 直连复查确认凭据已失效,已用本机网络重新登录", employee_id) + return _session_export(client, None) + except (SessionExpired, LoginRejected, ManualJigsaw, RuntimeError) as exc: + log.warning("用户 %s 直连重新登录失败: %s", employee_id, exc) + return "", "", "", [], None, "expired" + + +def _continue_direct(employee_id: str, password: str + ) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]: + """代理上像是未登录。用账号里的凭据走本机网络再查一次,还有效就继续,不再登录。""" + from euniv.proxy_pool import force_direct + + force_direct(employee_id) + credential = _stored_credential(employee_id) + client = EunivClient(employee_id, password, proxy=None) + try: + if credential.get("yxt_token") or credential.get("ucs_token"): + client.restore(credential) + try: + alive = client.credential_alive() + except Exception as exc: + log.warning("用户 %s 直连复查凭据失败: %s", employee_id, exc) + return "", "", "", [], None, "network" + if alive: + client._ensure_site() + log.info("用户 %s 凭据经直连复查仍然有效,改为直连继续,不重新登录", employee_id) + return _session_export(client, None) + return _login_direct_client(client, employee_id, password) + finally: + client.close() + + def _prepare_session(employee_id: str, password: str, credential: dict, proxy: str | None = None, use_pool: bool = False @@ -1740,16 +1868,14 @@ def _prepare_session(employee_id: str, password: str, try: client.restore(credential) if not client.credential_alive(): + if use_pool and current: + return _continue_direct(employee_id, password) return "", "", "", [], current, "expired" 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, "" + return _session_export(client, current) except SessionExpired: + if use_pool and current: + return _continue_direct(employee_id, password) return "", "", "", [], current, "expired" except Exception as exc: log.warning("用户 %s 准备会话失败: %s", employee_id, exc) @@ -2007,8 +2133,9 @@ class AutoStudyWorker: _set_user_status(employee_id, state="已停止") return if use_pool: - from euniv.proxy_pool import acquire + from euniv.proxy_pool import acquire, reset_budget + await asyncio.to_thread(reset_budget, employee_id) proxy = await asyncio.to_thread(acquire, employee_id) if user_stop.is_set(): _set_user_status(employee_id, state="已停止") @@ -2035,7 +2162,8 @@ class AutoStudyWorker: return async with StudySession( - token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool + token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool, + password=password, ) as session: if user_stop.is_set(): _set_user_status(employee_id, state="已停止") diff --git a/backend/euniv/collectors.py b/backend/euniv/collectors.py deleted file mode 100644 index ff7b941..0000000 --- a/backend/euniv/collectors.py +++ /dev/null @@ -1,264 +0,0 @@ -"""代理上游采集。新增平台时实现 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()) diff --git a/backend/euniv/courses.py b/backend/euniv/courses.py index 439feb0..4f5b103 100644 --- a/backend/euniv/courses.py +++ b/backend/euniv/courses.py @@ -200,6 +200,7 @@ 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.client import is_qr_password from euniv.proxy import bind_url, is_proxy_failure, uses_pool from euniv.proxy_pool import MAX_SWITCHES, retire_if_dead @@ -211,6 +212,27 @@ def _fetch_and_store(trigger: str) -> bool: try: client.restore(credential) if not client.credential_alive(): + if uses_pool(account) and proxy: + from euniv.proxy_pool import force_direct + + force_direct(employee_id) + client.close() + client = EunivClient(employee_id, password, proxy=None) + proxy = None + client.restore(credential) + if client.credential_alive(): + courses = client.list_courses() + last_exc = None + break + if password and not is_qr_password(password): + from euniv.service import _persist + + profile = client.login(manual=False) + with SessionLocal() as saved: + _persist(saved, employee_id, password, client, profile) + courses = client.list_courses() + last_exc = None + break _cool_failed_sync(employee_id, invalid=True) return False courses = client.list_courses() diff --git a/backend/euniv/models.py b/backend/euniv/models.py index 8b46360..3b475d1 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, Index, String, Text, UniqueConstraint, false as sql_false, text +from sqlalchemy import Boolean, DateTime, String, Text, UniqueConstraint, false as sql_false, text from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column @@ -83,39 +83,3 @@ class Account(Base): password_login_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), nullable=False, server_default=text("CURRENT_TIMESTAMP") ) - - -class ProxyNode(Base): - __tablename__ = "proxy_nodes" - __table_args__ = ( - UniqueConstraint("scheme", "host", "port", name="uq_proxy_node_addr"), - Index("ix_proxy_nodes_status", "status"), - ) - - 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=text("''")) - anonymity: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default=text("''")) - source: Mapped[str] = mapped_column(String(64), nullable=False, default="", server_default=text("''")) - 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) - last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) - fail_reason: Mapped[str] = mapped_column(String(200), nullable=False, default="", server_default=text("''")) - 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=text("''")) - 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_pool.py b/backend/euniv/proxy_pool.py index 26906f9..f6dc513 100644 --- a/backend/euniv/proxy_pool.py +++ b/backend/euniv/proxy_pool.py @@ -1,178 +1,38 @@ -"""自有代理池:多上游汇聚、延迟检测、均匀分配、失效剔除。""" +"""自动代理:一个任务最多向 proxy.scdn.io 领取 8 批中国代理,每批 8 个。 + +每批按顺序检查,第一个能打开学习平台的就用。学习过程中这个代理失效,再领下一批。 +8 批都用完任务还没结束,就改走本机网络。 + +接口的 https 表示这个代理能访问 HTTPS 网站。这类节点本身仍是 HTTP 代理, +用 HTTP CONNECT 转发。SOCKS4 常因 ident 校验被拒绝,不用。 +""" from __future__ import annotations import logging import threading import time -from concurrent.futures import ThreadPoolExecutor, as_completed -from datetime import datetime, timedelta, timezone -from urllib.parse import urlparse import httpx -from sqlalchemy import case, func, select -from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm import Session -from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API -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, sync_httpx_client +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__) - -class ProxyProbeError(ValueError): - """延迟测试目标不存在。""" - -FETCH_INTERVAL = 300 +MAX_FETCHES = 8 +MAX_SWITCHES = MAX_FETCHES +BATCH_SIZE = 8 LATENCY_LIMIT = 3.0 LATENCY_LIMIT_MS = 3000 -PROBE_CONCURRENCY = 16 -MAX_PROBES = 80 -PROBE_BATCH_TIMEOUT = 20.0 -ALIVE_REPROBE_SLOTS = 20 -MAX_SWITCHES = 8 PROBE_URL = EUNIV + "/" -PROBE_URLS = ( - EUNIV + "/", - STUDY_API + "/", - YXT_API + "/", -) -STATUS_ALIVE = "alive" -STATUS_DEAD = "dead" -STATUS_NEW = "new" +SOURCE_URL = "https://proxy.scdn.io/api/get_proxy.php" +SOURCE_PROTOCOL = "https" +CLIENT_SCHEME = "http" -_ANONYMITY = {"elite": "高匿名", "anonymous": "匿名", "transparent": "透明"} -_STATUS = {STATUS_ALIVE: "可用", STATUS_DEAD: "失效", STATUS_NEW: "待检测"} - -_assign_lock = threading.Lock() -_holds: dict[str, int] = {} -_refresh_lock = threading.Lock() -_probe_guard = threading.Lock() -_probe_state = {"running": False, "count": 0, "error": ""} - - -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 not None: - return row - row = ProxyPoolSync(id=1) - try: - with db.begin_nested(): - db.add(row) - db.flush() - except IntegrityError: - if row in db: - db.expunge(row) - found = db.get(ProxyPoolSync, 1) - if found is None: - raise - return found - 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 +_lock = threading.Lock() +_holds: dict[str, str] = {} +_fetches: dict[str, int] = {} def _elapsed_ms(started: float) -> int: @@ -190,19 +50,18 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]: follow_redirects=True, headers={"User-Agent": USER_AGENT}, ) as client: - for target in (PROBE_URL,): - started = time.perf_counter() - try: - response = client.get(target) - latency = _elapsed_ms(started) - if response.status_code >= 500: - samples.append(latency) - reasons.append(f"HTTP {response.status_code}") - continue + started = time.perf_counter() + try: + response = client.get(PROBE_URL) + latency = _elapsed_ms(started) + if response.status_code >= 500: samples.append(latency) - except Exception as exc: - samples.append(_elapsed_ms(started)) - reasons.append(_short_reason(exc)) + 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))) @@ -213,21 +72,6 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]: return True, average, "" -def _direct_reaches_target() -> bool: - """节点全灭时对照直连,区分代理故障和目标站故障。""" - try: - with sync_httpx_client( - None, - timeout=LATENCY_LIMIT, - follow_redirects=True, - headers={"User-Agent": USER_AGENT}, - ) as client: - response = client.get(PROBE_URL) - return response.status_code < 500 - except Exception: - return False - - def _clip_reason(reason: str, fallback: str = "失效") -> str: text = (reason or "").strip() or fallback if len(text) <= 200: @@ -252,480 +96,120 @@ def _short_reason(exc: BaseException) -> str: return _clip_reason(stored) -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: +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 - parsed = urlparse(text) - host = parsed.hostname - if not host or parsed.port is None: + host, raw_port = text.rsplit(":", 1) + host = host.strip() + try: + port = int(raw_port) + except ValueError: return None - return (parsed.scheme or "http").lower(), host, int(parsed.port) + if not host or not 1 <= port <= 65535: + return None + try: + assert_public_host(host) + except ProxyError: + return None + return host, 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 _fetch_batch() -> list[tuple[str, int]]: + """向接口要一批中国代理。接口失败时返回空列表,这一批仍然算一次领取。""" + try: + with httpx.Client(timeout=10, trust_env=False, verify=shared_tls()) as client: + response = client.get( + SOURCE_URL, + params={"protocol": SOURCE_PROTOCOL, "count": BATCH_SIZE, "country_code": "CN"}, + ) + payload = response.json() + except Exception: + log.warning("代理接口没有获取到", exc_info=True) + return [] + 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]] = [] + seen: set[tuple[str, int]] = set() + for item in proxies: + parsed = _parse_endpoint(item) + if parsed is None or parsed in seen: + continue + seen.add(parsed) + found.append(parsed) + if len(found) >= BATCH_SIZE: + break + 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 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) - if held is not None: - held.assigns = _occupancy(held.id) - nodes = list(db.scalars(select(ProxyNode).where(ProxyNode.status == STATUS_ALIVE)).all()) - if not nodes: - db.commit() - 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 - for node in nodes: - node.assigns = load[node.id] - nodes.sort(key=lambda node: (load[node.id], _latency_rank(node), node.assigns, node.id)) - pick = nodes[0] - _holds[key] = pick.id - pick.assigns = load[pick.id] + 1 - db.commit() - return _url(pick) - - -def _latency_rank(node: ProxyNode) -> int: - if node.latency_ms is None: - return 1_000_000_000 - return int(node.latency_ms) - - -def _occupancy(node_id: int) -> int: - return sum(1 for held in _holds.values() if held == node_id) + 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 host, port in _fetch_batch(): + ok, _latency, reason = probe(CLIENT_SCHEME, host, port) + if not ok: + log.info("代理 %s:%s 不能访问学习平台:%s", host, port, reason or "失效") + continue + url = build_proxy_url(CLIENT_SCHEME, host, port) + with _lock: + current = _holds.get(key) + if current: + return current + _holds[key] = url + return url def release(employee_id: str) -> None: - key = (employee_id or "").strip() - with SessionLocal() as db, _assign_lock: - node_id = _holds.pop(key, None) - if node_id is None: - return - node = db.get(ProxyNode, node_id) - if node is None: - return - node.assigns = _occupancy(node_id) - db.commit() - - -def retire_if_dead(employee_id: str, proxy_url: str | None, reason: str = "") -> bool: - """立刻复测当前节点。还通就继续用;不通就标死。""" - parsed = _parse_proxy_url(proxy_url) - if parsed is None: - mark_failed(employee_id, proxy_url, reason) - return True - ok, _latency, why = probe(parsed[0], parsed[1], parsed[2]) - if ok: - return False - mark_failed(employee_id, proxy_url, why or reason) - return True + 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() - parsed = _parse_proxy_url(proxy_url) - with SessionLocal() as db, _assign_lock: - node = _find_node(db, parsed[0], parsed[1], parsed[2]) if parsed is not None else None - held = _holds.get(key) - if node is None and held is not None: - node = db.get(ProxyNode, held) - if node is None: - return - if held == node.id: - _holds.pop(key, None) - node.status = STATUS_DEAD - node.fail_reason = _clip_reason(reason) - node.last_checked_at = _now() - node.assigns = 0 - _evict_node(node.id) - db.commit() + with _lock: + _holds.pop(key, None) -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] = [] - dead_ids: list[int] = [] - seen_at = _now() - 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, - last_seen_at=seen_at, - ) - 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 - node.last_seen_at = seen_at - if node.status == STATUS_DEAD: - dead_ids.append(node.id) - continue - if node.status == STATUS_NEW: - new_ids.append(node.id) - elif node.status == STATUS_ALIVE: - alive_ids.append(node.id) - stale_before = seen_at - timedelta(days=7) - held = set(_holds.values()) - for node in list(existing.values()): - if node.id in held or node.status != STATUS_DEAD: - continue - seen = _aware(node.last_seen_at) - if seen is not None and seen < stale_before: - db.delete(node) - existing.pop((node.scheme, node.host, int(node.port)), None) - for node in existing.values(): - if node.id in alive_ids or node.id in new_ids or node.id in dead_ids: - continue - if node.status == STATUS_ALIVE: - alive_ids.append(node.id) - elif node.status == STATUS_NEW: - new_ids.append(node.id) - db.commit() - probe_ids = _pick_probe_ids(db, new_ids, alive_ids, dead_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) - probed = len(results) - failed = sum(1 for _node_id, ok, _latency, _reason in results if not ok) - if probed >= 3 and failed == probed and not _direct_reaches_target(): - results = [] - elif probed < 3: - results = [row for row in results if row[1]] - 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 - _apply_probe(node, ok, latency, reason) - sync.checked_at = _now() - sync.running = False - db.flush() - _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 _aware(value: datetime | None) -> datetime | None: - if value is None: - return None - if value.tzinfo is None: - return value.replace(tzinfo=timezone.utc) - return value - - -def _load_nodes(db: Session, ids: list[int]) -> list[ProxyNode]: - nodes: list[ProxyNode] = [] - seen: set[int] = set() - for node_id in ids: - if node_id in seen: - continue - seen.add(node_id) - node = db.get(ProxyNode, node_id) - if node is not None: - nodes.append(node) - return nodes - - -def _unchecked_first(node: ProxyNode) -> tuple: - checked = _aware(node.last_checked_at) - return (checked is not None, checked or datetime.min.replace(tzinfo=timezone.utc), node.id) - - -def _pick_probe_ids(db: Session, new_ids: list[int], alive_ids: list[int], dead_ids: list[int] | None = None) -> list[int]: - new_nodes = _load_nodes(db, new_ids) - new_nodes.sort(key=_unchecked_first) - alive_nodes = _load_nodes(db, alive_ids) - alive_nodes.sort(key=_unchecked_first) - reserve = min(ALIVE_REPROBE_SLOTS, len(alive_nodes)) - new_budget = MAX_PROBES - reserve - ordered: list[int] = [] - seen: set[int] = set() - - def add(node_id: int) -> None: - if node_id in seen or len(ordered) >= MAX_PROBES: - return - seen.add(node_id) - ordered.append(node_id) - - for node in new_nodes: - if len(ordered) >= new_budget: - break - add(node.id) - for node in alive_nodes: - if len(ordered) >= MAX_PROBES: - break - add(node.id) - for node in new_nodes: - if len(ordered) >= MAX_PROBES: - break - add(node.id) - cutoff = _now() - timedelta(minutes=30) - for node_id in dead_ids or []: - if len(ordered) >= MAX_PROBES or node_id in seen: - continue - node = db.get(ProxyNode, node_id) - checked = _aware(node.last_checked_at) if node is not None else None - if checked is None or checked > cutoff: - continue - add(node_id) - 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]] = [] - pool = ThreadPoolExecutor(max_workers=workers) - try: - futures = { - pool.submit(probe, scheme, host, port): node_id - for node_id, scheme, host, port in nodes - } - try: - for future in as_completed(futures, timeout=PROBE_BATCH_TIMEOUT): - node_id = futures[future] - try: - ok, latency, reason = future.result() - except Exception as exc: - ok, latency, reason = False, 0, _short_reason(exc) - results.append((node_id, ok, latency, reason)) - except TimeoutError: - pass - finally: - pool.shutdown(wait=False, cancel_futures=True) - return results - - -def _apply_probe(node: ProxyNode, ok: bool, latency: int, reason: str) -> None: - 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 = _clip_reason(reason) - node.assigns = 0 - _evict_node(node.id) - - -def probe_one(node_id: int) -> dict: - with SessionLocal() as db: - node = db.get(ProxyNode, node_id) - if node is None: - raise ProxyProbeError("代理不存在") - snapshot = (node.id, node.scheme, node.host, int(node.port)) - ok, latency, reason = probe(snapshot[1], snapshot[2], snapshot[3]) - with SessionLocal() as db, _assign_lock: - node = db.get(ProxyNode, node_id) - if node is None: - raise ProxyProbeError("代理不存在") - _apply_probe(node, ok, latency, reason) - db.commit() - return view_item(node) - - -def request_probe(ids: list[int] | None = None) -> dict: - """整表探测放到后台,避免一次请求卡住到超时。""" - with _probe_guard: - if _probe_state["running"]: - return {"running": True, "count": _probe_state["count"], "items": []} - _probe_state["running"] = True - _probe_state["error"] = "" - _probe_state["count"] = 0 - - def work() -> None: - try: - result = probe_ids(ids) - with _probe_guard: - _probe_state["count"] = int(result.get("count") or 0) - _probe_state["error"] = "" - except Exception as exc: - log.warning("代理探测失败:%s", exc, exc_info=True) - with _probe_guard: - text = str(exc).strip() or "探测失败" - _probe_state["error"] = text[:200] - finally: - with _probe_guard: - _probe_state["running"] = False - - threading.Thread(target=work, name="euniv-proxy-probe", daemon=True).start() - return {"running": True, "count": 0, "items": []} - - -def probe_state() -> dict: - with _probe_guard: - return { - "running": _probe_state["running"], - "count": _probe_state["count"], - "error": _probe_state["error"], - } - - -def probe_ids(ids: list[int] | None = None) -> dict: - if ids is not None and not ids: - return {"ok": True, "count": 0, "items": []} - with SessionLocal() as db: - if ids: - wanted = [] - seen: set[int] = set() - for raw in ids: - node_id = int(raw) - if node_id in seen: - continue - seen.add(node_id) - wanted.append(node_id) - nodes = [ - node - for node in (db.get(ProxyNode, node_id) for node_id in wanted) - if node is not None - ] - if len(nodes) != len(wanted): - raise ProxyProbeError("代理不存在") - else: - nodes = list(db.scalars(select(ProxyNode).order_by(ProxyNode.id)).all()) - snapshot = [(node.id, node.scheme, node.host, int(node.port)) for node in nodes] - results = _probe_many(snapshot) - items = [] - with SessionLocal() as db, _assign_lock: - for node_id, ok, latency, reason in results: - node = db.get(ProxyNode, node_id) - if node is None: - continue - _apply_probe(node, ok, latency, reason) - items.append(view_item(node)) - db.commit() - return {"ok": True, "count": len(items), "items": items} - - -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 _reset_pool_running() -> None: - with _probe_guard: - _probe_state["running"] = False - with SessionLocal() as db: - row = db.get(ProxyPoolSync, 1) - if row is not None and row.running: - row.running = False - db.commit() - - -def start_proxy_pool() -> threading.Event: - _reset_pool_running() - stop = threading.Event() - - 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 +def retire_if_dead(employee_id: str, proxy_url: str | None, reason: str = "") -> bool: + """请求已经失败。放掉当前代理,让下一次重新领取。""" + mark_failed(employee_id, proxy_url, reason) + return True diff --git a/backend/euniv/service.py b/backend/euniv/service.py index a6ddbbd..093a415 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -507,11 +507,29 @@ def _live(db: Session, employee_id: str, client_factory, read): except SessionExpired: if is_qr_password(password): raise RuntimeError("扫码登录已失效,请重新扫码登录") from None - try: - client.authorize(client.login(manual=False, auto_attempts=attempts)) - except ManualJigsaw: - raise RuntimeError("登录需要重新验证,请重新登录") from None - data = read(client) + from euniv.proxy import uses_pool + + if uses_pool(account) and getattr(client, "proxy", None): + from euniv.proxy_pool import force_direct + + force_direct(employee_id) + client.close() + client = client_factory(employee_id, password, None) + client.restore(credential) + if client.credential_alive(): + data = read(client) + else: + try: + client.authorize(client.login(manual=False, auto_attempts=attempts)) + except ManualJigsaw: + raise RuntimeError("登录需要重新验证,请重新登录") from None + data = read(client) + else: + 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) @@ -609,9 +627,26 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None: elif is_qr_password(password): valid = False else: - profile = client.login(manual=False, auto_attempts=attempts) - _persist(db, employee_id, password, client, profile) - valid = True + from euniv.proxy import uses_pool + + if uses_pool(account) and getattr(client, "proxy", None): + from euniv.proxy_pool import force_direct + + force_direct(employee_id) + client.close() + client = client_factory(employee_id, password, None) + client.restore(previous) + if client.credential_alive(): + valid = True + checked_alive = True + else: + profile = client.login(manual=False, auto_attempts=attempts) + _persist(db, employee_id, password, client, profile) + valid = 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 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 4be562b..715f221 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -38,9 +38,10 @@ def fresh_database(): from euniv.login_limit import reset as reset_login reset_login() - from euniv.proxy_pool import _holds + from euniv.proxy_pool import _fetches, _holds _holds.clear() + _fetches.clear() from euniv import autostudy as autostudy_mod autostudy_mod._wanted.clear() diff --git a/backend/tests/test_proxy_pool.py b/backend/tests/test_proxy_pool.py index 6f7237c..50f032a 100644 --- a/backend/tests/test_proxy_pool.py +++ b/backend/tests/test_proxy_pool.py @@ -1,228 +1,172 @@ -import os - 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 PROBE_URL, acquire, mark_failed, page, probe, refresh_once, release -from euniv.proxy_pool import _holds - -INITIAL_PASSWORD = os.environ["EUNIV_ADMIN_PASSWORD"] +from euniv.models import Account +from euniv.proxy import is_proxy_failure +from euniv.proxy_pool import ( + BATCH_SIZE, + MAX_FETCHES, + PROBE_URL, + SOURCE_PROTOCOL, + _fetch_batch, + _fetches, + _holds, + acquire, + force_direct, + probe, + release, + reset_budget, +) -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: +def _clear() -> 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 + _fetches.clear() + + +def test_fetch_batch_asks_for_eight_chinese_https_proxies(monkeypatch) -> None: + seen: dict = {} + + class FakeResponse: + def json(self) -> dict: + return { + "code": 200, + "message": "success", + "data": { + "proxies": ["1.2.3.4:8080", "10.0.0.1:3128", "bad", "8.8.8.8:9"], + "count": 4, + }, + } + + class FakeClient: + def __init__(self, *_args, **_kwargs) -> None: + return None + + def __enter__(self): + return self + + def __exit__(self, *_args) -> bool: + return False + + def get(self, url: str, params: dict | None = None): + seen["url"] = url + seen["params"] = params + return FakeResponse() + + monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient) + assert _fetch_batch() == [("1.2.3.4", 8080), ("8.8.8.8", 9)] + assert seen["url"].endswith("/api/get_proxy.php") + assert seen["params"] == {"protocol": SOURCE_PROTOCOL, "count": BATCH_SIZE, "country_code": "CN"} + + +def test_acquire_stops_at_the_first_usable_proxy(monkeypatch) -> None: + _clear() + batches = [[("1.1.1.1", 1), ("2.2.2.2", 2), ("3.3.3.3", 3)]] + probed: list[str] = [] + + monkeypatch.setattr("euniv.proxy_pool._fetch_batch", lambda: list(batches.pop(0))) + + def fake_probe(_scheme: str, host: str, _port: int): + probed.append(host) + return host == "2.2.2.2", 10, "" + + monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe) + assert acquire("u1") == "http://2.2.2.2:2" + assert probed == ["1.1.1.1", "2.2.2.2"] + assert acquire("u1") == "http://2.2.2.2:2" + assert batches == [] + + +def test_acquire_uses_eight_batches_then_direct(monkeypatch) -> None: + _clear() + calls = {"n": 0} + + def fetch() -> list[tuple[str, int]]: + calls["n"] += 1 + return [(f"1.2.3.{calls['n']}", 8000)] + + monkeypatch.setattr("euniv.proxy_pool._fetch_batch", fetch) + monkeypatch.setattr("euniv.proxy_pool.probe", lambda *_args: (False, 8, "无法连接")) + assert acquire("u1") is None + assert calls["n"] == MAX_FETCHES + assert acquire("u1") is None + assert calls["n"] == MAX_FETCHES + + +def test_failed_proxy_fetches_the_next_batch_until_budget(monkeypatch) -> None: + _clear() + calls = {"n": 0} + + def fetch() -> list[tuple[str, int]]: + calls["n"] += 1 + return [(f"1.2.3.{calls['n']}", 8000)] + + monkeypatch.setattr("euniv.proxy_pool._fetch_batch", fetch) + monkeypatch.setattr("euniv.proxy_pool.probe", lambda *_args: (True, 20, "")) + first = acquire("u1") + assert first == "http://1.2.3.1:8000" + force_direct("u1") + assert acquire("u1") is None + assert calls["n"] == 1 + reset_budget("u1") + assert acquire("u1") == "http://1.2.3.2:8000" + + +def test_direct_recheck_keeps_valid_credential_without_login(monkeypatch) -> None: + from euniv.autostudy import _continue_direct + + class Fake: + login_called = False + + def __init__(self, employee_id: str, password: str, proxy: str | None = None) -> None: + assert proxy is None + self.client = self + self.cookies = self + self.jar: list = [] + self._profile = {"userId": "u", "accountId": employee_id} + + def restore(self, credential: dict) -> None: + assert credential["yxt_token"] == "saved" + + def credential_alive(self) -> bool: + return True + + def _ensure_site(self) -> str: + return "" + + def session_token(self) -> str: + return "saved" + + def login(self, manual: bool = False) -> dict: + Fake.login_called = True + raise AssertionError("凭据仍有效,不应重新登录") + + def close(self) -> None: + return None + + monkeypatch.setattr("euniv.autostudy.EunivClient", Fake) + monkeypatch.setattr("euniv.autostudy._stored_credential", lambda _employee_id: {"yxt_token": "saved"}) + monkeypatch.setattr("euniv.proxy_pool.force_direct", lambda _employee_id: None) + token, _user_id, _org_id, _cookies, proxy, reason = _continue_direct("100", "pw") + assert token == "saved" + assert proxy is None + assert reason == "" + assert Fake.login_called is False + + +def test_release_lets_the_next_task_fetch_again(monkeypatch) -> None: + _clear() + monkeypatch.setattr("euniv.proxy_pool._fetch_batch", lambda: [("8.8.4.4", 8080)]) + monkeypatch.setattr("euniv.proxy_pool.probe", lambda *_args: (True, 15, "")) + assert acquire("u1") == "http://8.8.4.4:8080" release("u1") - release("u2") - release("u3") + assert "u1" not in _holds + assert "u1" not in _fetches -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", "1.1.1.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://1.1.1.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", "4.4.4.4", 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"] == 2 - assert payload["message"] == "" - 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_old_dead_proxy_is_reprobed(monkeypatch) -> None: - from datetime import datetime, timedelta, timezone - - _holds.clear() - stale = _node("8.8.8.8", 88, status="dead") - with SessionLocal() as db: - node = db.get(ProxyNode, stale.id) - assert node is not None - node.last_checked_at = datetime.now(timezone.utc) - timedelta(hours=1) - db.commit() - monkeypatch.setattr( - "euniv.proxy_pool.collect_all", - lambda: [ProxyCandidate("http", "8.8.8.8", 88, "cn", "elite", "proxyhub")], - ) - called: list[str] = [] - - def fake_probe(scheme: str, host: str, port: int): - called.append(host) - return True, 20, "" - - monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe) - refresh_once() - assert called == ["8.8.8.8"] - with SessionLocal() as db: - node = db.get(ProxyNode, stale.id) - assert node is not None - assert node.status == "alive" - - -def test_probe_averages_euniv_related_sites(monkeypatch) -> None: +def test_probe_reaches_euniv_home(monkeypatch) -> None: seen: list[str] = [] class FakeResponse: @@ -269,43 +213,12 @@ def test_probe_instant_connect_error_keeps_elapsed_latency(monkeypatch) -> None: ticks = iter([0.0, 0.008]) monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient) monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks)) - ok, latency, reason = probe("socks4", "10.0.0.9", 1080) + ok, latency, reason = probe("http", "1.1.1.1", 8080) assert ok is False assert latency == 8 assert reason == "无法连接" -def test_admin_can_probe_one_and_all_proxies(monkeypatch) -> None: - import euniv.api as api_module - - _holds.clear() - one = _node("10.0.0.7", 8007) - two = _node("10.0.0.8", 8008, status="new") - monkeypatch.setattr("euniv.proxy_pool.probe", lambda scheme, host, port: (True, 321 if host.endswith("7") else 654, "")) - client = TestClient(api_module.app) - assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 - single = client.post(f"/api/admin/proxies/{one.id}/probe") - assert single.status_code == 200 - assert single.json()["latency_ms"] == 321 - assert single.json()["status"] == "alive" - bulk = client.post("/api/admin/proxies/probe", json={"ids": [two.id]}) - assert bulk.status_code == 200 - assert bulk.json()["running"] is True - finished = {"running": True} - for _ in range(40): - finished = client.get("/api/admin/proxies/probe").json() - if finished["running"] is False: - break - import time - time.sleep(0.05) - assert finished["running"] is False - listed = client.get("/api/admin/proxies").json() - probed = next(item for item in listed["items"] if item["id"] == two.id) - assert probed["latency_ms"] == 654 - missing = client.post("/api/admin/proxies/99999/probe") - assert missing.status_code == 404 - - def test_is_proxy_failure_detects_connect_errors() -> None: assert is_proxy_failure(httpx.ConnectError("boom")) assert is_proxy_failure(httpx.ConnectTimeout("late")) @@ -315,37 +228,6 @@ def test_is_proxy_failure_detects_connect_errors() -> None: 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/study-settings", - 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(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module @@ -406,3 +288,4 @@ def test_user_can_enable_pool_proxy(monkeypatch) -> None: 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 deleted file mode 100644 index 9d38f8e..0000000 --- a/web/src/features/admin/ProxiesView.vue +++ /dev/null @@ -1,434 +0,0 @@ - - - diff --git a/web/src/shell/AdminShell.vue b/web/src/shell/AdminShell.vue index 8f9f4f6..3480e17 100644 --- a/web/src/shell/AdminShell.vue +++ b/web/src/shell/AdminShell.vue @@ -6,7 +6,6 @@ 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 }>(); @@ -14,7 +13,7 @@ const emit = defineEmits<{ logout: []; refresh: [] }>(); const page = ref(pageFromHash()); const collapsed = ref(window.innerWidth < 800); const holdOpen = ref(false); -const pages = new Set(["users", "courses", "proxies", "settings"]); +const pages = new Set(["users", "courses", "settings"]); function hashName() { return window.location.hash.replace(/^#\/?/, ""); @@ -22,7 +21,7 @@ function hashName() { function pageFromHash(): AdminPageKey { const name = hashName(); - if (name === "courses" || name === "proxies" || name === "settings" || name === "users") return name; + if (name === "courses" || name === "settings" || name === "users") return name; return "users"; } @@ -73,7 +72,7 @@ onUnmounted(() => { }); function onMenu(key: string) { - if (key === "users" || key === "courses" || key === "proxies" || key === "settings") show(key); + if (key === "users" || key === "courses" || key === "settings") show(key); } @@ -132,7 +131,6 @@ function onMenu(key: string) { - diff --git a/web/src/shell/adminNavigation.ts b/web/src/shell/adminNavigation.ts index e243e1d..1bc385d 100644 --- a/web/src/shell/adminNavigation.ts +++ b/web/src/shell/adminNavigation.ts @@ -1,17 +1,16 @@ import type { Component } from "vue"; import { h } from "vue"; import { NIcon } from "naive-ui"; -import { GlobeOutline, LibraryOutline, PeopleOutline, SettingsOutline } from "@vicons/ionicons5"; +import { LibraryOutline, PeopleOutline, SettingsOutline } from "@vicons/ionicons5"; function renderIcon(icon: Component) { return () => h(NIcon, null, { default: () => h(icon) }); } -export type AdminPageKey = "users" | "courses" | "proxies" | "settings"; +export type AdminPageKey = "users" | "courses" | "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) }, ];