From 91b06cde25a5fede6018ef2afcf1e7030b513e43 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 16 Nov 2026 09:04:29 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=A4=B1=E8=B4=A5=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E6=8C=89=E9=97=B4=E9=9A=94=E9=87=8D=E8=AF=95=EF=BC=8C=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E5=B9=B6=E5=8F=91=E4=B8=8D=E5=86=8D=E5=8D=A0=E6=BB=A1?= =?UTF-8?q?=E6=95=B4=E6=AE=B5=E5=AD=A6=E4=B9=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/euniv/api.py | 3 + backend/euniv/autostudy.py | 157 +++++++++++++++++++++-------- backend/euniv/client.py | 11 +- backend/euniv/courses.py | 4 + backend/euniv/service.py | 4 + backend/tests/conftest.py | 3 + web/src/features/home/HomeView.vue | 1 + 7 files changed, 137 insertions(+), 46 deletions(-) diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 41bd17b..a883808 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -433,6 +433,9 @@ def post_study_control(body: StudyControlBody, request: Request, db: Session = D halt_work(employee_id) else: + from euniv.autostudy import clear_study_hold + + clear_study_hold(employee_id) start_now(account) db.commit() sync_work(employee_id) diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index ab8cee6..fd80705 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -58,6 +58,10 @@ _user_halts: dict[str, asyncio.Event] = {} _wanted: dict[str, int] = {} _wanted_seq = 0 _running: set[str] = set() +_retry_at: dict[str, float] = {} +_retry_count: dict[str, int] = {} +_done_month: dict[str, str] = {} +_RETRY_STEPS = (5 * 60, 15 * 60, 60 * 60) _worker = None @@ -314,6 +318,31 @@ def request_wake() -> None: worker.wake() +def clear_study_hold(employee_id: str) -> None: + key = (employee_id or "").strip() + _retry_at.pop(key, None) + _retry_count.pop(key, None) + _done_month.pop(key, None) + + +def note_attempt_end(employee_id: str) -> None: + with _lock: + info = (_status.get("users") or {}).get(employee_id) or {} + state = str(info.get("state") or "") + if state in ("学习失败", "会话失效"): + count = _retry_count.get(employee_id, 0) + delay = _RETRY_STEPS[min(count, len(_RETRY_STEPS) - 1)] + _retry_count[employee_id] = count + 1 + _retry_at[employee_id] = time.time() + delay + return + if state == "已学完": + from euniv.study_window import month_key + + _done_month[employee_id] = month_key() + _retry_at.pop(employee_id, None) + _retry_count.pop(employee_id, None) + + def want_work(employee_id: str) -> None: key = (employee_id or "").strip() if not key: @@ -606,6 +635,9 @@ class StudySession: self._use_pool = use_pool self._referer = EUNIV + "/" self._submit_logs = 0 + self._proxy_lock: asyncio.Lock | None = None + self._closing: list[httpx.AsyncClient] = [] + self._switches = 0 self._client: httpx.AsyncClient | None = None async def __aenter__(self) -> "StudySession": @@ -618,49 +650,72 @@ class StudySession: headers={"User-Agent": USER_AGENT}, ) _load_cookies(self._client, self._initial_cookies) + self._proxy_lock = asyncio.Lock() return self async def __aexit__(self, *args: object) -> None: + for client in self._closing: + await client.aclose() + self._closing.clear() if self._client: await self._client.aclose() - async def _rotate_proxy(self) -> bool: + async def _rotate_proxy(self, used: str | None = None) -> bool: if not self._use_pool: return False - from euniv.proxy import parse_proxy - from euniv.proxy_pool import acquire, mark_failed + from euniv.proxy import async_httpx_client, parse_proxy + from euniv.proxy_pool import MAX_SWITCHES, 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 - from euniv.proxy import async_httpx_client - - client = async_httpx_client( - parsed, - timeout=30, - follow_redirects=True, - 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 + if self._proxy_lock is None: + self._proxy_lock = asyncio.Lock() + failed = self._proxy if used is None else used + async with self._proxy_lock: + if failed != self._proxy: + return True + if self._switches >= MAX_SWITCHES: + return False + self._switches += 1 + await asyncio.to_thread(mark_failed, self._employee_id, failed) + nxt = await asyncio.to_thread(acquire, self._employee_id) + parsed = parse_proxy(nxt) + if parsed == failed: + return False + client = async_httpx_client( + parsed, + timeout=30, + follow_redirects=True, + headers={"User-Agent": USER_AGENT}, + ) + cookies = self._initial_cookies + if self._client is not None: + cookies = [ + (cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/") + for cookie in self._client.cookies.jar + ] or self._initial_cookies + self._closing.append(self._client) + _load_cookies(client, cookies) + self._client = client + self._proxy = parsed + return True async def _http(self, method: str, url: str, **kw: object) -> httpx.Response: assert self._client is not None + limit = getattr(self, "_request_limit", None) + + async def once() -> httpx.Response: + assert self._client is not None + if limit is None: + return await self._client.request(method, url, **kw) + async with limit: + return await self._client.request(method, url, **kw) + + used = self._proxy try: - return await self._client.request(method, url, **kw) + return await once() 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) + if self._use_pool and used and is_proxy_failure(exc): + if await self._rotate_proxy(used): + return await once() raise def _api_headers(self) -> dict[str, str]: @@ -1317,6 +1372,7 @@ class AutoStudyWorker: def _tick(self) -> float: from euniv.db import SessionLocal + from euniv.study_window import CN_TZ, month_key now = as_cn() soonest = next_month_start(now) @@ -1341,6 +1397,17 @@ class AutoStudyWorker: if is_studying(eid) or is_wanted(eid): halt_work(eid) continue + retry_hold = _retry_at.get(eid) + if retry_hold and time.time() < retry_hold and not is_wanted(eid): + retry_at = datetime.fromtimestamp(retry_hold, CN_TZ) + if retry_at < soonest: + soonest = retry_at + continue + if retry_hold and time.time() >= retry_hold: + want_work(eid) + _retry_at.pop(eid, None) + if _done_month.get(eid) == month_key(now) and not is_wanted(eid): + continue if not (study_eligible(row) or is_wanted(eid)): continue if self._busy(eid): @@ -1367,7 +1434,7 @@ class AutoStudyWorker: else: label = soonest.strftime("%m-%d %H:%M:%S") _set_status(running=False, message=f"下一次定时 {label}") - return wait + return min(wait, 3600.0) def _launch(self, job: tuple, course_list: list[tuple[str, str, str]]) -> bool: eid = job[0] @@ -1377,6 +1444,7 @@ class AutoStudyWorker: _set_user_status(eid, state="学习失败", message="没有可用的课程") drop_work(eid) return False + _set_user_status(eid, state="排队中", course="") want_work(eid) with _halt_lock: generation = _wanted.get(eid, 0) @@ -1412,6 +1480,7 @@ class AutoStudyWorker: drop_work(emp_id) elif current is not None and self._kick is not None: self._kick.set() + note_attempt_end(emp_id) self._tasks.pop(emp_id, None) async def _study_user(self, employee_id: str, target: int, @@ -1427,22 +1496,22 @@ class AutoStudyWorker: _user_halts[employee_id] = user_stop _running.add(employee_id) try: - async with sem: - if user_stop.is_set(): - _set_user_status(employee_id, state="已停止") - return - _set_user_status(employee_id, state="准备", course="", workers={}) - 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="会话失效", message="无法连接学习平台") - return + if user_stop.is_set(): + _set_user_status(employee_id, state="已停止") + return + _set_user_status(employee_id, state="准备", course="", workers={}) + 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="会话失效", message="无法连接学习平台") + return - async with StudySession( - token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool - ) as session: + 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] + session._request_limit = sem _set_user_status(employee_id, state="学习中") hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source) if await hours.refresh(): diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 91047f4..268a2f7 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -1354,8 +1354,15 @@ class EunivClient: response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"") except SessionExpired: return False - payload = response.json() - return isinstance(payload, dict) and bool(payload.get("cnName")) + if response.status_code >= 500 or response.status_code == 429: + raise RuntimeError("学习平台暂时不可用") + try: + payload = response.json() + except ValueError as exc: + raise RuntimeError("学习平台暂时不可用") from exc + if not isinstance(payload, dict): + raise RuntimeError("学习平台暂时不可用") + return bool(payload.get("cnName")) def _pages(self, url: str, headers: dict, html: str, parse, identity: str) -> list[dict]: items = parse(html) diff --git a/backend/euniv/courses.py b/backend/euniv/courses.py index 0435ae0..67b9c8e 100644 --- a/backend/euniv/courses.py +++ b/backend/euniv/courses.py @@ -211,6 +211,10 @@ def _fetch_and_store(trigger: str) -> bool: sync.next_allowed_at = sync.finished_at + next_gap() sync.course_count = len(courses) db.commit() + from euniv.autostudy import clear_study_hold, request_wake + + clear_study_hold(employee_id) + request_wake() return True diff --git a/backend/euniv/service.py b/backend/euniv/service.py index f338ade..b3c133f 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -498,6 +498,10 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None: stamp_hours(account, hours) db.commit() + if valid is True: + from euniv.autostudy import request_wake + + request_wake() if checked_alive: _request_course_sync(employee_id) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index b7be43b..c17e7cd 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -47,6 +47,9 @@ def fresh_database(): autostudy_mod._wanted.clear() autostudy_mod._running.clear() + autostudy_mod._retry_at.clear() + autostudy_mod._retry_count.clear() + autostudy_mod._done_month.clear() autostudy_mod._user_halts.clear() users = autostudy_mod._status.get("users") if isinstance(users, dict): diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index d330cb9..3fa3a11 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -97,6 +97,7 @@ const studyLabel = computed(() => { if (state === "已停止" || studyControl.value.paused) return "任务已停止"; if (state === "已学完") return "课程已学完"; if (studyFailed.value) return message || state; + if (state === "排队中") return "排队中"; if (state === "准备") return "正在连接学习平台"; if (studyingWorkers.value.length) return studyControl.value.course || "学习中"; if (state === "学习中") return "正在领取课程";