fix: 默认心跳先等够再报,新登录账号可以立刻开始
This commit is contained in:
+31
-12
@@ -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)
|
||||
|
||||
@@ -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"}:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user