fix: 默认心跳先等够再报,新登录账号可以立刻开始

This commit is contained in:
2026-11-16 02:44:54 +08:00
parent ec41af9489
commit e27b3002a4
5 changed files with 62 additions and 22 deletions
+31 -12
View File
@@ -472,10 +472,11 @@ def _count_total(sent: int, progress: float, origin: float = 0.0) -> int:
def _jitter(seconds: int) -> float: def _jitter(seconds: int) -> float:
"""只往晚了偏,避免心跳比页面节奏更早发出。间隔为 0 时至少等 1 秒。"""
if seconds <= 0: if seconds <= 0:
return 0.0 return 1.0
spread = min(3.0, max(0.0, float(seconds) * 0.2)) spread = min(3.0, max(0.3, float(seconds) * 0.1))
return max(0.0, float(seconds) + random.uniform(-spread, spread)) return float(seconds) + random.uniform(0.3, spread)
def _parse_minutes(value: str) -> int: def _parse_minutes(value: str) -> int:
@@ -647,15 +648,21 @@ class StudySession:
refreshed = resp.headers.get("token") or resp.headers.get("Token") refreshed = resp.headers.get("token") or resp.headers.get("Token")
if refreshed: if refreshed:
self._token = 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("学习平台登录已失效") raise SessionExpired("学习平台登录已失效")
if resp.status_code == 403:
raise PermissionError("当前课程没有权限")
if resp.headers.get("content-type", "").startswith("application/json"): if resp.headers.get("content-type", "").startswith("application/json"):
try: try:
payload = resp.json() payload = resp.json()
if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}:
raise SessionExpired("学习平台登录已失效")
except (json.JSONDecodeError, ValueError): 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 return resp
async def update_progress(self, kid: str, pkg_id: str = "") -> dict: 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 started = True
view = int(progress.get("viewSchedule") or view) view = int(progress.get("viewSchedule") or view)
view += step 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: try:
result = await session.submit_video_heartbeat(kid, pkg_id, step, view) result = await session.submit_video_heartbeat(kid, pkg_id, step, view)
except Exception: except Exception:
@@ -915,8 +927,9 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
if schedule >= 100: if schedule >= 100:
await hours.refresh() await hours.refresh()
return return
if await _heartbeat_wait(worker, interval, stop, hours, schedule): if not page_rhythm:
return 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, 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 return
started = True started = True
view = int(progress.get("viewSchedule") or 1) 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: try:
await session.submit_document_heartbeat(kid, pkg_id, page_size, step, view) await session.submit_document_heartbeat(kid, pkg_id, page_size, step, view)
progress = await session.update_progress(kid, pkg_id) 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): if _completed(progress):
await hours.refresh() await hours.refresh()
return return
if await _heartbeat_wait(worker, interval, stop, hours, schedule): if not page_rhythm:
return 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, async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
@@ -1408,7 +1427,7 @@ class AutoStudyWorker:
except SessionExpired: except SessionExpired:
hours.user_stop.set() hours.user_stop.set()
_touch(worker, ok=False) _touch(worker, ok=False)
_set_user_status(employee_id, state="会话过期") _set_user_status(employee_id, state="会话失效", message="请重新登录")
log.info("用户 %s 会话过期", employee_id) log.info("用户 %s 会话过期", employee_id)
except Exception as exc: except Exception as exc:
_touch(worker, ok=False) _touch(worker, ok=False)
+3 -1
View File
@@ -1043,8 +1043,10 @@ class EunivClient:
for cookie in self.client.cookies.jar: for cookie in self.client.cookies.jar:
if cookie.name == "ELEARNING_00024" and cookie.value: if cookie.name == "ELEARNING_00024" and cookie.value:
self._yxt_token = cookie.value self._yxt_token = cookie.value
if response.status_code in (401, 403): if response.status_code == 401:
raise SessionExpired("学习平台登录已失效") raise SessionExpired("学习平台登录已失效")
if response.status_code == 403:
raise PermissionError("当前课程没有权限")
if response.headers.get("content-type", "").startswith("application/json"): if response.headers.get("content-type", "").startswith("application/json"):
payload = response.json() payload = response.json()
if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}: if isinstance(payload, dict) and str(payload.get("code")) in {"401", "403"}:
+11 -3
View File
@@ -94,7 +94,11 @@ def _persist(db: Session, employee_id: str, password: str, client: EunivClient,
db.add(account) db.add(account)
account.password_cipher = encrypt_secret(password) account.password_cipher = encrypt_secret(password)
account.credential_cipher = encrypt_secret(_dump(client.export_credential())) account.credential_cipher = encrypt_secret(_dump(client.export_credential()))
account.credential_valid = True
db.commit() db.commit()
from euniv.autostudy import sync_work
sync_work(employee_id)
def _client(factory, employee_id: str, password: str, account: Account | None = None): 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 continue
raise raise
except Exception as exc: except Exception as exc:
import logging
from cryptography.fernet import InvalidToken from cryptography.fernet import InvalidToken
if isinstance(exc, InvalidToken): if isinstance(exc, InvalidToken):
import logging
logging.getLogger("euniv.service").exception("账号 %s 的密文无法用当前密钥解开", employee_id) logging.getLogger("euniv.service").exception("账号 %s 的密文无法用当前密钥解开", employee_id)
return return
logging.getLogger("euniv.service").exception("刷新账号 %s 的登录状态失败", employee_id)
db.rollback() db.rollback()
valid = False
account = db.get(Account, employee_id) account = db.get(Account, employee_id)
if account is None: if account is None:
return return
rejected = isinstance(exc, RuntimeError) and any(
word in str(exc) for word in ("登录失败", "登录页校验失败", "密码错误")
)
valid = False if rejected else account.credential_valid
finally: finally:
if client is not None: if client is not None:
try: try:
+7
View File
@@ -42,3 +42,10 @@ def fresh_database():
from euniv.proxy_pool import _holds from euniv.proxy_pool import _holds
_holds.clear() _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()
+10 -6
View File
@@ -120,16 +120,15 @@ def test_wait_stop_timeout_and_event() -> None:
asyncio.run(main()) asyncio.run(main())
def test_jitter_zero_means_no_wait() -> None: def test_jitter_never_sends_early() -> None:
assert _jitter(0) == 0 assert _jitter(0) == 1
assert _jitter(-1) == 0 assert _jitter(-1) == 1
for _ in range(30): for _ in range(30):
wait = _jitter(1) wait = _jitter(1)
assert 0 <= wait < 5 assert 1.3 <= wait <= 4
assert abs(wait - 1) <= 0.3
for _ in range(30): for _ in range(30):
wait = _jitter(10) wait = _jitter(10)
assert 7 <= wait <= 13 assert 10.3 <= wait <= 13.3
def test_count_total_estimates_from_progress() -> None: def test_count_total_estimates_from_progress() -> None:
@@ -322,6 +321,11 @@ class _VideoSession:
def test_video_refresh_hours_when_finished(monkeypatch) -> None: def test_video_refresh_hours_when_finished(monkeypatch) -> None:
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: 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: async def main() -> None:
session = _VideoSession("700") session = _VideoSession("700")
global_stop = asyncio.Event() global_stop = asyncio.Event()