diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 4ba69ce..5e84531 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -462,15 +462,14 @@ def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db)) @app.get("/api/settings/study-control") def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict: - from euniv.autostudy import autostudy_status + from euniv.autostudy import account_status from euniv.study_control import assemble, settle, stamp_frame employee_id = _signed_in(request, db) account = db.get(Account, employee_id) if account is None: raise HTTPException(status_code=401, detail="未登录") - status = autostudy_status() - live = dict((status.get("users") or {}).get(employee_id) or {}) + live = account_status(employee_id) if settle(account, live): db.commit() return stamp_frame(employee_id, assemble(account, live)) diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index 85c1096..54a1165 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -94,6 +94,18 @@ def autostudy_status() -> dict: return raw +def account_status(employee_id: str) -> dict: + """只复制一个账号的状态,推送时不必复制全部账号。""" + key = (employee_id or "").strip() + with _lock: + raw = (_status.get("users") or {}).get(key) + if not isinstance(raw, dict): + return {} + info = dict(raw) + info["workers"] = _workers_list(info) + return info + + def _notify(employee_id: str = "", urgent: bool = False) -> None: try: from euniv.study_push import notify @@ -179,10 +191,7 @@ class WorkerView: self._origin = 0.0 def update(self, **kw: object) -> None: - course = kw.get("course") marker = kw.get("knowledge_id") - if not isinstance(marker, str) or not marker: - marker = course if isinstance(course, str) else "" if isinstance(marker, str) and marker and marker != self._course: self._course = marker self.sent = 0 @@ -460,6 +469,18 @@ def _release_pool(employee_id: str, pool: bool) -> None: release(employee_id) +def _release_pool_later(employee_id: str, pool: bool) -> None: + """在事件循环里把释放交给线程,避免堵住会写库的代理锁。""" + if not pool or not employee_id: + return + try: + loop = asyncio.get_running_loop() + except RuntimeError: + _release_pool(employee_id, True) + return + loop.create_task(asyncio.to_thread(_release_pool, employee_id, True)) + + def _job_from_account(row) -> tuple | None: """从账号列表行提取一次凭据。之后 work 只用这份拷贝,不再读账号表。""" from euniv.crypto import decrypt_secret @@ -472,16 +493,7 @@ def _job_from_account(row) -> tuple | None: pool = uses_pool(row) target = int(target_raw) if target_raw is not None else 600 if target <= 0: - return None - try: - proxy = bind_url(row) - if pool and not proxy and employee_id: - _set_user_status(employee_id, message="正在直连") - except Exception as exc: - log.warning("用户 %s 凭据无法读取: %s", employee_id, exc) _release_pool(employee_id, pool) - if employee_id: - _set_user_status(employee_id, state="学习失败", message="凭据无法读取") return None try: password = decrypt_secret(password_cipher) @@ -495,6 +507,16 @@ def _job_from_account(row) -> tuple | None: if not isinstance(credential, dict): _release_pool(employee_id, pool) return None + proxy = None + if not pool: + try: + proxy = bind_url(row) + except Exception as exc: + log.warning("用户 %s 凭据无法读取: %s", employee_id, exc) + _release_pool(employee_id, pool) + if employee_id: + _set_user_status(employee_id, state="学习失败", message="凭据无法读取") + return None if employee_id: _targets[employee_id] = target return ( @@ -536,6 +558,24 @@ def _course_type(kind: str, path: str) -> str: return "unknown" +def _chapter_type(raw: object) -> str: + """空串和无法识别的章节类型都不当成文档。""" + text = str(raw or "").strip().lower() + if "video" in text: + return "video" + if "document" in text: + return "document" + return "unknown" + + +def _note_unknown(skipped: dict | None, label: str) -> None: + count = 1 + if isinstance(skipped, dict): + count = int(skipped.get("n") or 0) + 1 + skipped["n"] = count + log.info("跳过未知类型课程 %s,累计 %s 门", label, count) + + def _play_path(kind: str, path: str, kid: str) -> str: compact = compact_id(kid) ctype = _course_type(kind, path) @@ -603,12 +643,16 @@ async def wait_stop(timeout: float, *events: asyncio.Event) -> bool: if timeout <= 0: return False tasks = [asyncio.create_task(event.wait()) for event in events] - done, pending = await asyncio.wait(tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED) - for task in pending: - task.cancel() - if pending: - await asyncio.gather(*pending, return_exceptions=True) - return bool(done) + try: + done, _pending = await asyncio.wait( + tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED, + ) + return bool(done) + finally: + for task in tasks: + if not task.done(): + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) class HoursWatcher: @@ -998,31 +1042,9 @@ class StudySession: return 0 return len(re.findall(r'["\']([^"\']+\.oss\.js)["\']', resp.text)) - async def scorm_extract_answers(self, kid: str) -> list[dict]: - assert self._client is not None - compact = compact_id(kid) - index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/index-scorm.js" - resp = await self._http("GET", index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}) - urls: list[str] = [] - for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text): - raw = m.group(1) - if raw.startswith("http"): - urls.append(raw) - elif raw.startswith("//"): - urls.append("https:" + raw) - elif raw.startswith("/"): - urls.append(f"https://cdn-cos-file.yunxuetang.cn{raw}") - else: - urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/{raw}") - answers: list[dict] = [] - for url in urls: - try: - r = await self._http("GET", url, headers={"User-Agent": USER_AGENT}) - for block in re.finditer(r'单选题([\s\S]*?)正确答案[::]\s*([A-D])', r.text): - answers.append({"page_url": url, "answer": block.group(2)}) - except Exception: - continue - return answers + async def scorm_extract_answers(self, kid: str) -> int: + """只取页文件列表长度,不下载课件。索引失败返回 0,不让整门课失败。""" + return await self.scorm_page_count(kid) async def month_hours_text(self) -> str: assert self._client is not None @@ -1151,13 +1173,15 @@ def _uses_new_timer(params: dict | None) -> bool: async def _study_video(session: StudySession, kid: str, pkg_id: str, interval: int, stop: asyncio.Event, hours: HoursWatcher, worker: WorkerView | None = None, - study_time: int | None = None) -> None: + study_time: int | None = None, + snapshot: dict | None = None) -> None: step = int(study_time if study_time is not None else (interval if interval > 0 else 30)) if step <= 0: step = 30 view = 0 started = False stall = _Stall() + pending = snapshot if not getattr(session, "_play_logged", False): session._play_logged = True poster = getattr(session, "post_site_log", None) @@ -1170,7 +1194,11 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, }) while not _halted(stop, hours): try: - progress = await session.update_progress(kid, pkg_id) + if pending is not None: + progress = pending + pending = None + else: + progress = await session.update_progress(kid, pkg_id) except Exception: _touch(worker, ok=False) raise @@ -1213,15 +1241,21 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str, async def _study_document(session: StudySession, kid: str, pkg_id: str, page_size: int, interval: int, stop: asyncio.Event, hours: HoursWatcher, worker: WorkerView | None = None, - study_time: int | None = None) -> None: + study_time: int | None = None, + snapshot: dict | None = None) -> None: step = int(study_time if study_time is not None else (interval if interval > 0 else 120)) if step <= 0: step = 120 started = False stall = _Stall() + pending = snapshot while not _halted(stop, hours): try: - progress = await session.update_progress(kid, pkg_id) + if pending is not None: + progress = pending + pending = None + else: + progress = await session.update_progress(kid, pkg_id) except Exception: _touch(worker, ok=False) raise @@ -1240,15 +1274,10 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str, return try: await session.submit_document_heartbeat(kid, pkg_id, page_size, step, view) - progress = await session.update_progress(kid, pkg_id) except Exception: _touch(worker, ok=False) raise - schedule = _progress_of(progress) _beat(worker, schedule, ok=True) - if _completed(progress): - await hours.refresh() - return if stall.stuck(schedule, step): raise RuntimeError("进度长时间没有变化") if not page_rhythm: @@ -1259,16 +1288,20 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str, async def _study_scorm(session: StudySession, kid: str, pkg_id: str, interval: int, stop: asyncio.Event, hours: HoursWatcher, user_id: str, org_id: str, worker: WorkerView | None = None, - study_time: int | None = None, scorm_id: str = "") -> None: + study_time: int | None = None, scorm_id: str = "", + snapshot: dict | None = None) -> None: import uuid as _uuid step = int(study_time if study_time is not None else (interval if interval > 0 else 120)) if step <= 0: step = 120 - try: - progress = await session.update_progress(kid, pkg_id) - except Exception: - _touch(worker, ok=False) - raise + if snapshot is not None: + progress = snapshot + else: + try: + progress = await session.update_progress(kid, pkg_id) + except Exception: + _touch(worker, ok=False) + raise schedule = _progress_of(progress) _touch(worker, progress=schedule, ok=True) if _completed(progress): @@ -1331,6 +1364,8 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str, scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt, pkg_id=pkg_id, data=scorm_data, ) + if _halted(stop, hours): + return await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id=sco_id, end=True) progress = await session.update_progress(kid, pkg_id) except Exception: @@ -1365,7 +1400,8 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str, async def _study_package(session: StudySession, kid: str, intervals: dict, auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher, - user_id: str, org_id: str, worker: WorkerView | None = None) -> bool: + user_id: str, org_id: str, worker: WorkerView | None = None, + skipped: dict | None = None) -> bool: pkg = await session.sync_package(kid) if _completed(pkg): _touch(worker, progress=_progress_of(pkg), ok=True) @@ -1382,16 +1418,20 @@ async def _study_package(session: StudySession, kid: str, intervals: dict, if not compact_id(ch_kid): log.info("跳过没有编号的章节 %s", ch_title) continue + ch_type = _chapter_type(ch.get("knowledgeType")) + if ch_type == "unknown": + _note_unknown(skipped, str(ch_title)) + continue _set_user_status(session._employee_id, course=ch_title) _touch(worker, course=ch_title, knowledge_id=ch_kid, progress=_progress_of(ch), ok=True) - is_video = "Video" in str(ch.get("knowledgeType") or "") - ch_type = "video" if is_video else "document" try: params = await _open_play(session, _package_chapter_path(kid, ch_kid, ch_type)) wait, study_time, page_size = _interval_plan(ch_type, intervals, auto_mode, params) - if is_video: + if ch_type == "video": + session._video_cap = _whole(params.get("standardStudyHours"), 0) await _study_video(session, ch_kid, kid, wait, stop, hours, worker, study_time=study_time) else: + session._video_cap = 0 await _study_document( session, ch_kid, kid, page_size, wait, stop, hours, worker, study_time=study_time, ) @@ -1605,6 +1645,7 @@ class AutoStudyWorker: if not course_list: _set_user_status(eid, state="学习失败", message="没有可用的课程") drop_work(eid) + _release_pool_later(eid, bool(job[6])) return False _set_user_status(eid, state="排队中", course="") want_work(eid) @@ -1620,15 +1661,20 @@ class AutoStudyWorker: try: from admin.settings import hours_source_of - hours_source = await asyncio.to_thread(hours_source_of) - intervals, auto_mode = await asyncio.to_thread(_current_intervals) + if int(target or 0) <= 0: + if use_pool: + await asyncio.to_thread(_release_pool, emp_id, True) + return if not course_list: _set_user_status(emp_id, state="学习失败", message="没有可用的课程") + if use_pool: + await asyncio.to_thread(_release_pool, emp_id, True) return + hours_source = await asyncio.to_thread(hours_source_of) assert self._sem is not None await self._study_user( emp_id, target, pw, cred, proxy, workers, use_pool, - course_list, intervals, auto_mode, hours_source, self._sem, + course_list, hours_source, self._sem, ) except Exception as exc: log.warning("用户 %s 自动学习失败: %s", emp_id, exc) @@ -1649,8 +1695,8 @@ class AutoStudyWorker: async def _study_user(self, employee_id: str, target: int, password: str, credential: dict, proxy: str | None, - workers: int, use_pool: bool, course_list: list, intervals: dict, - auto_mode: bool, hours_source: str, sem: asyncio.Semaphore) -> None: + workers: int, use_pool: bool, course_list: list, + hours_source: str, sem: asyncio.Semaphore) -> None: assert self._async_stop is not None user_stop = asyncio.Event() with _halt_lock: @@ -1660,6 +1706,18 @@ class AutoStudyWorker: _user_halts[employee_id] = user_stop _running.add(employee_id) try: + if user_stop.is_set(): + _set_user_status(employee_id, state="已停止") + return + if use_pool: + from euniv.proxy_pool import acquire + + proxy = await asyncio.to_thread(acquire, employee_id) + if user_stop.is_set(): + _set_user_status(employee_id, state="已停止") + return + if not proxy: + _set_user_status(employee_id, message="正在直连") if user_stop.is_set(): _set_user_status(employee_id, state="已停止") return @@ -1671,14 +1729,17 @@ class AutoStudyWorker: _set_user_status(employee_id, state="已停止") return if not token: - message = "请重新登录" if reason == "expired" else "无法连接学习平台" - _set_user_status(employee_id, state="会话失效", message=message) + if reason == "expired": + _set_user_status(employee_id, state="会话失效", message="请重新登录") + log.info("用户 %s 需要重新登录", employee_id) + else: + _set_user_status(employee_id, state="学习失败", message="无法连接学习平台") + log.info("用户 %s 无法连接学习平台", employee_id) return 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 if user_stop.is_set(): _set_user_status(employee_id, state="已停止") @@ -1690,8 +1751,7 @@ class AutoStudyWorker: ticker = asyncio.create_task(hours.ticker(self._async_stop)) try: failed = await self._study_courses( - session, employee_id, course_list, intervals, - auto_mode, hours, user_id, org_id, workers) + session, employee_id, course_list, hours, user_id, org_id, workers) if hours.reached or user_stop.is_set() or self._async_stop.is_set(): return if failed: @@ -1718,8 +1778,7 @@ class AutoStudyWorker: await asyncio.to_thread(release, employee_id) async def _study_courses(self, session: StudySession, employee_id: str, - course_list: list, intervals: dict, - auto_mode: bool, hours: HoursWatcher, + course_list: list, hours: HoursWatcher, user_id: str, org_id: str, workers: int) -> int: """N 个协程顺着课程表往下领,已完成的跳过,未完成的发心跳。""" assert self._async_stop is not None @@ -1728,6 +1787,7 @@ class AutoStudyWorker: finished = await asyncio.to_thread(_load_finished, employee_id) streak = {"n": 0, "wait": 60} failed = {"n": 0} + skipped = {"n": 0} streak_lock = asyncio.Lock() async def worker_loop(index: int) -> None: @@ -1741,7 +1801,7 @@ class AutoStudyWorker: path, title, kind = item result = await self._study_one_course( session, employee_id, path, title, kind, - intervals, auto_mode, hours, user_id, org_id, view, finished, + hours, user_id, org_id, view, finished, skipped, ) pause = 0 async with streak_lock: @@ -1761,25 +1821,23 @@ class AutoStudyWorker: if pause and await wait_stop(pause, self._async_stop, hours.user_stop): return - try: - async with asyncio.TaskGroup() as group: - for index in range(1, count + 1): - group.create_task(worker_loop(index)) - except ExceptionGroup: - log.warning("用户 %s 有学习协程没有跑完", employee_id) + async with asyncio.TaskGroup() as group: + for index in range(1, count + 1): + group.create_task(worker_loop(index)) return failed["n"] async def _study_one_course(self, session: StudySession, employee_id: str, path: str, title: str, kind: str, - intervals: dict, auto_mode: bool, hours: HoursWatcher, user_id: str, org_id: str, - worker: WorkerView | None = None, finished: set[str] | None = None) -> str: + worker: WorkerView | None = None, + finished: set[str] | None = None, + skipped: dict | None = None) -> str: assert self._async_stop is not None if _halted(self._async_stop, hours): return "stop" ctype = _course_type(kind, path) if ctype == "unknown": - log.info("跳过未知类型课程 %s", title or path) + _note_unknown(skipped, title or path) return "skip" kid = _knowledge_id_from_path(path) if not kid: @@ -1787,29 +1845,44 @@ class AutoStudyWorker: known = finished if finished is not None else set() if kid in known: return "skip" - intervals, auto_mode = await asyncio.to_thread(_current_intervals) _set_user_status(employee_id, course=title) try: progress = await session.update_progress(kid, "") - schedule = _progress_of(progress) - _touch(worker, course=title, knowledge_id=kid, progress=schedule, ok=True) - if _completed(progress): - known.add(kid) - await asyncio.to_thread(_remember_finished, employee_id, kid) - await wait_stop(random.uniform(0.5, 1.5), self._async_stop, hours.user_stop) - return "done" - if await wait_stop(random.uniform(2.0, 5.0), self._async_stop, hours.user_stop): - return "stop" + except SessionExpired: + hours.user_stop.set() + _touch(worker, ok=False) + _set_user_status(employee_id, state="会话失效", message="请重新登录") + log.info("用户 %s 会话失效", employee_id) + return "stop" + except Exception as exc: + _touch(worker, ok=False) + log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc) + return "fail" + + schedule = _progress_of(progress) + _touch(worker, course=title, knowledge_id=kid, progress=schedule, ok=True) + if _completed(progress): + known.add(kid) + await asyncio.to_thread(_remember_finished, employee_id, kid) + await wait_stop(random.uniform(0.5, 1.5), self._async_stop, hours.user_stop) + return "done" + if await wait_stop(random.uniform(2.0, 5.0), self._async_stop, hours.user_stop): + return "stop" + + intervals, auto_mode = await asyncio.to_thread(_current_intervals) + try: play_path = _play_path(kind, path, kid) session._referer = f"{EUNIV}{play_path}" session._play_logged = False params = await _open_play(session, play_path) if ctype == "package": _touch(worker, course=title, knowledge_id=kid, progress=0, ok=True) - ok = await _study_package(session, kid, intervals, auto_mode, - self._async_stop, hours, user_id, org_id, worker) + ok = await _study_package( + session, kid, intervals, auto_mode, + self._async_stop, hours, user_id, org_id, worker, skipped, + ) if _halted(self._async_stop, hours): return "stop" if not ok: @@ -1822,8 +1895,11 @@ class AutoStudyWorker: session._single_limit = str(params.get("isSingle") or "") == "1" if ctype == "video": session._video_cap = _whole(params.get("standardStudyHours"), 0) + else: + session._video_cap = 0 if ctype == "document" and _uses_new_timer(params) and auto_mode: - wait = max(1, _whole(params.get("submitProTimes"), 30)) + page_gap = _whole(params.get("submitProTimes"), 30) + wait = max(1, page_gap) study_time = wait if ctype == "document" and not _uses_new_timer(params): standard = _whole(params.get("standardStudyHours"), 0) @@ -1838,18 +1914,20 @@ class AutoStudyWorker: return "studied" if ctype == "video": await _study_video( - session, kid, "", wait, self._async_stop, hours, worker, study_time=study_time, + session, kid, "", wait, self._async_stop, hours, worker, + study_time=study_time, snapshot=progress, ) elif ctype == "document": await _study_document( session, kid, "", page_size, wait, self._async_stop, hours, worker, - study_time=study_time, + study_time=study_time, snapshot=progress, ) elif ctype == "scorm": await _study_scorm( session, kid, "", wait, self._async_stop, hours, str(params.get("userID") or ""), str(params.get("orgID") or ""), worker, study_time=study_time, scorm_id=str(params.get("scormId") or ""), + snapshot=progress, ) if _halted(self._async_stop, hours): return "stop" @@ -1866,7 +1944,6 @@ class AutoStudyWorker: _touch(worker, ok=False) log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc) return "fail" - return "skip" # ── 数据库更新 ── diff --git a/backend/euniv/study_control.py b/backend/euniv/study_control.py index 51f81a7..6037b66 100644 --- a/backend/euniv/study_control.py +++ b/backend/euniv/study_control.py @@ -166,7 +166,7 @@ def settle(account, live: dict | None = None, now: datetime | None = None) -> bo def payload_for(employee_id: str) -> dict: - from euniv.autostudy import autostudy_status + from euniv.autostudy import account_status from euniv.db import SessionLocal from euniv.models import Account @@ -186,8 +186,7 @@ def payload_for(employee_id: str) -> dict: account = db.get(Account, key) if account is None: return empty - status = autostudy_status() - live = dict((status.get("users") or {}).get(key) or {}) + live = account_status(key) if settle(account, live): db.commit() return stamp_frame(key, assemble(account, live)) diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index fcdf01d..0a71410 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -159,7 +159,7 @@ def test_worker_view_freezes_total_after_first_beat() -> None: _clear_user_status("u-total") view = WorkerView("u-total", 1) - view.update(course="甲", progress=38) + view.update(course="甲", knowledge_id="k-jia", progress=38) view.after_beat(39, ok=True) first = autostudy_status()["users"]["u-total"]["workers"][0]["total"] assert first == 62 @@ -933,8 +933,6 @@ def test_completed_course_skips_the_play_page(monkeypatch) -> None: f"/kng/view/video/{COMPACT_KID}.html", "已完成", "视频", - {}, - False, watcher, "", "",