From e27b3002a421487a960135fed10ab3f4699af50a Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 16 Nov 2026 02:44:54 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=BB=98=E8=AE=A4=E5=BF=83=E8=B7=B3?= =?UTF-8?q?=E5=85=88=E7=AD=89=E5=A4=9F=E5=86=8D=E6=8A=A5=EF=BC=8C=E6=96=B0?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E8=B4=A6=E5=8F=B7=E5=8F=AF=E4=BB=A5=E7=AB=8B?= =?UTF-8?q?=E5=88=BB=E5=BC=80=E5=A7=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/euniv/autostudy.py | 43 ++++++++++++++++++++++++--------- backend/euniv/client.py | 4 ++- backend/euniv/service.py | 14 ++++++++--- backend/tests/conftest.py | 7 ++++++ backend/tests/test_autostudy.py | 16 +++++++----- 5 files changed, 62 insertions(+), 22 deletions(-) diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index f0a07a1..ed405e4 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -472,10 +472,11 @@ def _count_total(sent: int, progress: float, origin: float = 0.0) -> int: def _jitter(seconds: int) -> float: + """只往晚了偏,避免心跳比页面节奏更早发出。间隔为 0 时至少等 1 秒。""" if seconds <= 0: - return 0.0 - spread = min(3.0, max(0.0, float(seconds) * 0.2)) - return max(0.0, float(seconds) + random.uniform(-spread, spread)) + return 1.0 + spread = min(3.0, max(0.3, float(seconds) * 0.1)) + return float(seconds) + random.uniform(0.3, spread) def _parse_minutes(value: str) -> int: @@ -647,15 +648,21 @@ class StudySession: refreshed = resp.headers.get("token") or resp.headers.get("Token") if refreshed: self._token = refreshed - if resp.status_code in (401, 403): + for domain in ("euniv.zte.com.cn", "api-mall.yxt.com"): + self._client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/") + if resp.status_code == 401: raise SessionExpired("学习平台登录已失效") + if resp.status_code == 403: + raise PermissionError("当前课程没有权限") if resp.headers.get("content-type", "").startswith("application/json"): try: payload = resp.json() - if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}: - raise SessionExpired("学习平台登录已失效") except (json.JSONDecodeError, ValueError): - pass + payload = None + if isinstance(payload, dict) and str(payload.get("code")) == "401": + raise SessionExpired("学习平台登录已失效") + if isinstance(payload, dict) and str(payload.get("code")) == "403": + raise PermissionError("当前课程没有权限") return resp async def update_progress(self, kid: str, pkg_id: str = "") -> dict: @@ -903,6 +910,11 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, started = True view = int(progress.get("viewSchedule") or view) view += step + page_rhythm = interval > 0 and interval == step + if page_rhythm and await _heartbeat_wait(worker, interval, stop, hours, schedule): + return + if _halted(stop, hours): + return try: result = await session.submit_video_heartbeat(kid, pkg_id, step, view) except Exception: @@ -915,8 +927,9 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, if schedule >= 100: await hours.refresh() return - if await _heartbeat_wait(worker, interval, stop, hours, schedule): - return + if not page_rhythm: + if await _heartbeat_wait(worker, 1 if interval <= 0 else interval, stop, hours, schedule): + return async def _study_document(session: StudySession, kid: str, pkg_id: str, @@ -941,6 +954,11 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str, return started = True view = int(progress.get("viewSchedule") or 1) + page_rhythm = interval > 0 and interval == step + if page_rhythm and await _heartbeat_wait(worker, interval, stop, hours, schedule): + return + if _halted(stop, hours): + return try: await session.submit_document_heartbeat(kid, pkg_id, page_size, step, view) progress = await session.update_progress(kid, pkg_id) @@ -952,8 +970,9 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str, if _completed(progress): await hours.refresh() return - if await _heartbeat_wait(worker, interval, stop, hours, schedule): - return + if not page_rhythm: + if await _heartbeat_wait(worker, 1 if interval <= 0 else interval, stop, hours, schedule): + return async def _study_scorm(session: StudySession, kid: str, pkg_id: str, @@ -1408,7 +1427,7 @@ class AutoStudyWorker: except SessionExpired: hours.user_stop.set() _touch(worker, ok=False) - _set_user_status(employee_id, state="会话过期") + _set_user_status(employee_id, state="会话失效", message="请重新登录") log.info("用户 %s 会话过期", employee_id) except Exception as exc: _touch(worker, ok=False) diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 0e55ebf..d843d60 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -1043,8 +1043,10 @@ class EunivClient: for cookie in self.client.cookies.jar: if cookie.name == "ELEARNING_00024" and cookie.value: self._yxt_token = cookie.value - if response.status_code in (401, 403): + if response.status_code == 401: raise SessionExpired("学习平台登录已失效") + if response.status_code == 403: + raise PermissionError("当前课程没有权限") if response.headers.get("content-type", "").startswith("application/json"): payload = response.json() if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}: diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 0ddca4a..1020b25 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -94,7 +94,11 @@ def _persist(db: Session, employee_id: str, password: str, client: EunivClient, db.add(account) account.password_cipher = encrypt_secret(password) account.credential_cipher = encrypt_secret(_dump(client.export_credential())) + account.credential_valid = True db.commit() + from euniv.autostudy import sync_work + + sync_work(employee_id) def _client(factory, employee_id: str, password: str, account: Account | None = None): @@ -464,18 +468,22 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None: continue raise except Exception as exc: + import logging + from cryptography.fernet import InvalidToken if isinstance(exc, InvalidToken): - import logging - logging.getLogger("euniv.service").exception("账号 %s 的密文无法用当前密钥解开", employee_id) return + logging.getLogger("euniv.service").exception("刷新账号 %s 的登录状态失败", employee_id) db.rollback() - valid = False account = db.get(Account, employee_id) if account is None: return + rejected = isinstance(exc, RuntimeError) and any( + word in str(exc) for word in ("登录失败", "登录页校验失败", "密码错误") + ) + valid = False if rejected else account.credential_valid finally: if client is not None: try: diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 35ca37b..6436355 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -42,3 +42,10 @@ def fresh_database(): from euniv.proxy_pool import _holds _holds.clear() + from euniv import autostudy as autostudy_mod + + autostudy_mod._wanted.clear() + autostudy_mod._user_halts.clear() + users = autostudy_mod._status.get("users") + if isinstance(users, dict): + users.clear() diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index e7837b1..e21b58e 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -120,16 +120,15 @@ def test_wait_stop_timeout_and_event() -> None: asyncio.run(main()) -def test_jitter_zero_means_no_wait() -> None: - assert _jitter(0) == 0 - assert _jitter(-1) == 0 +def test_jitter_never_sends_early() -> None: + assert _jitter(0) == 1 + assert _jitter(-1) == 1 for _ in range(30): wait = _jitter(1) - assert 0 <= wait < 5 - assert abs(wait - 1) <= 0.3 + assert 1.3 <= wait <= 4 for _ in range(30): wait = _jitter(10) - assert 7 <= wait <= 13 + assert 10.3 <= wait <= 13.3 def test_count_total_estimates_from_progress() -> None: @@ -322,6 +321,11 @@ class _VideoSession: def test_video_refresh_hours_when_finished(monkeypatch) -> None: monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None) + async def no_wait(*_args, **_kwargs) -> bool: + return False + + monkeypatch.setattr("euniv.autostudy._heartbeat_wait", no_wait) + async def main() -> None: session = _VideoSession("700") global_stop = asyncio.Event()