"""自动学习:asyncio 并发遍历用户和课程,发送心跳积累学时。 架构: - 一个后台线程运行独立的 asyncio 事件循环 - 每个用户一个协程,asyncio.gather 并行 - 全局 Semaphore 控制总并发,避免压爆上游 - 每个用户一个 StudySession(httpx.AsyncClient),支持独立 proxy - 每个用户可配置同时学几门课(当前默认 1,结构已预留) - 心跳间隔用 asyncio.sleep,不占线程 """ from __future__ import annotations import asyncio import hashlib import json import logging import random import re import threading import time from datetime import datetime, timezone import httpx from sqlalchemy import select from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired from euniv.models import Account, Course log = logging.getLogger(__name__) _SCORM_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696" _MAX_CONCURRENT_USERS = 8 _MAX_COURSE_PER_USER = 1 _lock = threading.Lock() _status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""} def autostudy_status() -> dict: with _lock: return dict(_status) def _set_status(**kw: object) -> None: with _lock: _status.update(kw) _status["updated_at"] = datetime.now(timezone.utc).isoformat() def _set_user_status(employee_id: str, **kw: object) -> None: with _lock: users = _status.setdefault("users", {}) info = users.setdefault(employee_id, {}) info.update(kw) _status["updated_at"] = datetime.now(timezone.utc).isoformat() def _clear_user_status(employee_id: str) -> None: with _lock: _status.get("users", {}).pop(employee_id, None) # ── 课程路径解析 ── _ID_RE = re.compile(r"([0-9a-fA-F]{32})") def _knowledge_id_from_path(path: str) -> str: m = _ID_RE.search(path.replace("-", "").split(".")[0].split("/")[-1]) return m.group(1) if m else "" def _course_type(kind: str, path: str) -> str: if kind == "课程包" or "/package/" in path: return "package" if kind == "课程" or "/scorm/" in path: return "scorm" if kind == "视频" or "/video/" in path: return "video" if kind in ("文档", "") or "/document/" in path: return "document" return "unknown" def _play_path(kind: str, path: str, kid: str) -> str: ctype = _course_type(kind, path) if ctype == "video": return f"/kng/view/video/{kid}.html" if ctype == "document": return f"/kng/view/document/{kid}.html" if ctype == "scorm": return f"/kng/view/scorm/{kid}.html" return path def _jitter(seconds: int) -> float: delta = random.uniform(-3.0, 3.0) return max(5.0, seconds + delta) def _scorm_md5(body_json: str) -> str: return hashlib.md5((body_json + _SCORM_MD5_KEY).encode("utf-8")).hexdigest() def _parse_minutes(value: str) -> int: if not value: return 0 m = re.search(r"(\d+)", value) return int(m.group(1)) if m else 0 # ── Async 学习会话 ── class StudySession: """一个用户的异步学习会话。包装 httpx.AsyncClient,提供心跳提交方法。 支持 proxy 参数(当前未启用,架构预留)。 """ def __init__(self, token: str, cookies: list[tuple[str, str, str, str]], proxy: str | None = None) -> None: self._token = token self._initial_cookies = cookies self._proxy = proxy self._client: httpx.AsyncClient | None = None async def __aenter__(self) -> "StudySession": self._client = httpx.AsyncClient( timeout=30, follow_redirects=True, proxy=self._proxy, headers={"User-Agent": USER_AGENT}, ) for name, value, domain, path in self._initial_cookies: self._client.cookies.set(name, value, domain=domain, path=path) return self async def __aexit__(self, *args: object) -> None: if self._client: await self._client.aclose() def _api_headers(self) -> dict[str, str]: return { "Accept": "application/json, text/plain, */*", "Content-Type": "application/json", "Origin": EUNIV, "Referer": EUNIV + "/", "source": "501", "token": self._token, "User-Agent": USER_AGENT, } async def _api(self, method: str, url: str, **kw: object) -> httpx.Response: assert self._client is not None headers = self._api_headers() extra = kw.pop("headers", None) if extra and isinstance(extra, dict): headers.update(extra) resp = await self._client.request(method, url, headers=headers, **kw) refreshed = resp.headers.get("token") or resp.headers.get("Token") if refreshed: self._token = refreshed if resp.status_code in (401, 403): raise SessionExpired("学习平台登录已失效") 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 return resp async def update_progress(self, kid: str, pkg_id: str = "") -> dict: resp = await self._api("POST", f"{STUDY_API}/v1/study/updateprogress", json={"knowledgeId": kid, "packageId": pkg_id, "masterId": "", "masterType": ""}) return resp.json() async def sync_package(self, kid: str) -> dict: resp = await self._api("GET", f"{STUDY_API}/v1/uk/syncpackage", params={"knowledgeId": kid, "sourceType": "SingleStudy", "masterId": ""}) return resp.json() async def get_encrypt_request(self, body_json: str) -> str: assert self._client is not None resp = await self._client.post( f"{EUNIV}/kng/services/KngComService.svc/GetEncryptRequest", json={"body": body_json}, headers={"Content-Type": "text/json", "User-Agent": USER_AGENT}, ) data = resp.json() if isinstance(data, str): data = json.loads(data) if data.get("Status") == "OK": return str(data["Data"]) raise RuntimeError(f"GetEncryptRequest 失败: {data}") async def submit_video_heartbeat(self, kid: str, pkg_id: str, study_time: int, view_schedule: int) -> dict: param = { "knowledgeId": kid, "masterId": "", "masterType": "", "packageId": pkg_id, "pageSize": 1, "studySize": 1, "studyTime": study_time, "type": 0, "offLine": False, "end": False, "care": True, "deviceId": "", "studyChapterIds": "", "viewSchedule": view_schedule, } encrypt_body = json.dumps(param, separators=(",", ":")) encryption = await self.get_encrypt_request(encrypt_body) param["encryption"] = encryption param["multiple"] = 1 param["realHour"] = study_time resp = await self._api("POST", f"{STUDY_API}/v1/study/submitpro", content=json.dumps(param, separators=(",", ":"))) text = resp.text.strip() return resp.json() if text else {} async def submit_document_heartbeat(self, kid: str, pkg_id: str, page_size: int, study_time: int, view_schedule: int) -> None: param = { "knowledgeId": kid, "masterId": "", "masterType": "", "packageId": pkg_id, "pageSize": page_size, "studySize": page_size, "studyTime": study_time, "type": 1, "offLine": False, "end": False, "care": True, "deviceId": "", "studyChapterIds": "", "viewSchedule": view_schedule, } encrypt_body = json.dumps(param, separators=(",", ":")) encryption = await self.get_encrypt_request(encrypt_body) param["multiple"] = 1 param["realHour"] = study_time await self._api("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", content=json.dumps(param, separators=(",", ":"))) async def submit_scorm_heartbeat(self, kid: str, pkg_id: str, study_time: int, sco_id: str = "", end: bool = False) -> None: param = { "knowledgeId": kid, "masterId": "", "masterType": "", "packageId": pkg_id, "pageSize": -1 if end else 1, "studySize": -1 if end else 1, "studyTime": study_time, "type": 2, "offLine": False, "end": end, "care": True, "deviceId": "", "studyChapterIds": sco_id, "viewSchedule": 0, } if end: encryption = _scorm_md5(json.dumps(param, separators=(",", ":"))) else: encrypt_body = json.dumps(param, separators=(",", ":")) encryption = await self.get_encrypt_request(encrypt_body) param["multiple"] = 1 param["realHour"] = study_time await self._api("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}", content=json.dumps(param, separators=(",", ":"))) async def scorm_count(self, kid: str) -> int: resp = await self._api("GET", f"{STUDY_API}/v1/kng/scorm/count/", params={"knowledgeId": kid}) return int(resp.json().get("scocnt") or 1) async def scorm_get(self, user_id: str, sco_id: str) -> dict: resp = await self._api("GET", f"https://api-mall.yxt.com/v1/scormstudy/{user_id}/{sco_id}") text = resp.text.strip() return resp.json() if text else {} async def scorm_save(self, session_id: str, org_id: str, user_id: str, scorm_id: str, scorm_id_ori: str, sco_cnt: int, pkg_id: str, data: dict) -> None: await self._api("POST", "https://api-mall.yxt.com/v1/scormstudy", json={ "sessionId": session_id, "orgId": org_id, "userId": user_id, "scormId": scorm_id, "scormIdOri": scorm_id_ori, "masterId": "", "masterType": "", "packageId": pkg_id, "scocnt": sco_cnt, "data": data, }) async def course_page_params(self, path: str) -> dict: assert self._client is not None resp = await self._client.get( f"{EUNIV}{path}", headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}, ) html = resp.text def _var(name: str, default: str = "") -> str: m = re.search(rf'(?:var\s+)?{name}\s*=\s*["\']?([^"\';\r\n]+)', html) return m.group(1).strip() if m else default return { "submitProTimes": int(_var("submitProTimes", "30") or 30), "validtimeSpan": int(_var("validtimeSpan", "120") or 120), "pageSize": int(_var("pageSize", "1") or 1), "userID": _var("userID"), "orgID": _var("orgID"), } async def scorm_extract_answers(self, kid: str) -> list[dict]: assert self._client is not None index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{kid}/h5/js/index-scorm.js" resp = await self._client.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/{kid}/h5/js/{raw}") answers: list[dict] = [] for url in urls: try: r = await self._client.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 month_hours_text(self) -> str: assert self._client is not None resp = await self._client.get( f"{EUNIV}/study/myperiod.htm", headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"}, ) m = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', resp.text) return m.group(1) if m else "" # ── 单门课程的学习协程 ── async def _study_video(session: StudySession, kid: str, pkg_id: str, interval: int, stop: asyncio.Event, check_target) -> None: view = 0 while not stop.is_set(): progress = await session.update_progress(kid, pkg_id) schedule = float(progress.get("studyschedule", 0)) if schedule >= 100: return view = int(progress.get("viewSchedule", view)) view += interval result = await session.submit_video_heartbeat(kid, pkg_id, interval, view) new_schedule = result.get("studySchedule") if new_schedule is not None and float(new_schedule) >= 100: return if await check_target(): return await asyncio.sleep(_jitter(interval)) async def _study_document(session: StudySession, kid: str, pkg_id: str, page_size: int, interval: int, stop: asyncio.Event, check_target) -> None: view = 1 while not stop.is_set(): progress = await session.update_progress(kid, pkg_id) if float(progress.get("studyschedule", 0)) >= 100: return await session.submit_document_heartbeat(kid, pkg_id, page_size, interval, view) if await check_target(): return await asyncio.sleep(_jitter(interval)) async def _study_scorm(session: StudySession, kid: str, pkg_id: str, interval: int, stop: asyncio.Event, check_target, user_id: str, org_id: str) -> None: import uuid as _uuid sco_cnt = await session.scorm_count(kid) session_id = str(_uuid.uuid4()) sco_id = kid existing = await session.scorm_get(user_id, sco_id) scorm_data = existing.get("data") if existing else None if not scorm_data or not isinstance(scorm_data, dict): scorm_data = { "cmi__core__lesson_status": "completed", "cmi__core__lesson_location": "1", "cmi__core__lesson_progress": "1.00", "cmi__core__session_time": "00:00:01", "cmi__core__exit": "suspend", "cmi__suspend_data": "", } else: scorm_data["cmi__core__lesson_status"] = "completed" scorm_data["cmi__core__lesson_progress"] = "1.00" answers = await session.scorm_extract_answers(kid) total_pages = max(len(answers), 10) for page_idx in range(total_pages): if stop.is_set(): return scorm_data["cmi__core__lesson_location"] = str(page_idx + 1) scorm_data["cmi__core__session_time"] = "00:00:01" await session.scorm_save( session_id=session_id, org_id=org_id, user_id=user_id, scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt, pkg_id=pkg_id, data=scorm_data, ) await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True) if await check_target(): return progress = await session.update_progress(kid, pkg_id) if float(progress.get("studyschedule", 0)) >= 100: return await asyncio.sleep(_jitter(min(interval, 5))) while not stop.is_set(): progress = await session.update_progress(kid, pkg_id) if float(progress.get("studyschedule", 0)) >= 100: return await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False) if await check_target(): return await asyncio.sleep(_jitter(interval)) async def _study_package(session: StudySession, kid: str, intervals: dict, auto_mode: bool, stop: asyncio.Event, check_target, user_id: str, org_id: str) -> None: pkg = await session.sync_package(kid) chapters = pkg.get("userKnowledgeList") or [] for ch in chapters: if stop.is_set(): return if float(ch.get("studySchedule", 0)) >= 100: continue ch_kid = str(ch.get("knowledgeId") or "").replace("-", "") ch_title = ch.get("title") or ch_kid if not ch_kid: continue _set_user_status(session._employee_id, course=ch_title) is_video = "Video" in str(ch.get("knowledgeType") or "") ch_type = "video" if is_video else "document" ch_interval = intervals.get(ch_type, 30 if is_video else 120) page_size = 1 if auto_mode: try: params = await session.course_page_params( f"/kng/course/package/{ch_type}/{kid}_{ch_kid}.html") ch_interval = params.get("submitProTimes" if is_video else "validtimeSpan", ch_interval) page_size = params.get("pageSize", 1) except Exception: pass if is_video: await _study_video(session, ch_kid, kid, ch_interval, stop, check_target) else: await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, check_target) if await check_target(): return # ── 同步准备:用 EunivClient 建立会话,导出 cookies ── def _prepare_session(employee_id: str, password: str, credential: dict) -> tuple[str, str, str, list[tuple[str, str, str, str]]]: """同步:恢复会话并导出 token + cookies。返回 (token, user_id, org_id, cookies)。""" client = EunivClient(employee_id, password) try: client.restore(credential) if not client.credential_alive(): return "", "", "", [] client._ensure_site() token = client.session_token() user_id = str(client._profile.get("userId") or "") org_id = str(client._profile.get("accountId") or "") cookies: list[tuple[str, str, str, str]] = [] for cookie in client.client.cookies.jar: cookies.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/")) return token, user_id, org_id, cookies finally: client.close() # ── Worker 主循环 ── class AutoStudyWorker: """后台 asyncio 事件循环,管理所有用户的自动学习。""" def __init__(self) -> None: self._stop_flag = threading.Event() self._thread: threading.Thread | None = None self._loop: asyncio.AbstractEventLoop | None = None self._async_stop: asyncio.Event | None = None def start(self) -> None: self._thread = threading.Thread(target=self._run_thread, name="euniv-autostudy", daemon=True) self._thread.start() def stop(self) -> None: self._stop_flag.set() if self._loop and self._async_stop: self._loop.call_soon_threadsafe(self._async_stop.set) def _run_thread(self) -> None: self._loop = asyncio.new_event_loop() asyncio.set_event_loop(self._loop) self._async_stop = asyncio.Event() try: self._loop.run_until_complete(self._main_loop()) finally: self._loop.close() async def _main_loop(self) -> None: assert self._async_stop is not None await asyncio.sleep(15) while not self._async_stop.is_set(): try: await self._run_cycle() except Exception as exc: log.exception("自动学习周期异常: %s", exc) _set_status(message=f"异常: {exc}") try: await asyncio.wait_for(self._async_stop.wait(), timeout=random.uniform(300, 600)) return except asyncio.TimeoutError: pass async def _run_cycle(self) -> None: assert self._async_stop is not None from admin.settings import heartbeat_intervals from euniv.crypto import decrypt_secret from euniv.db import SessionLocal intervals_cfg = heartbeat_intervals() auto_mode = intervals_cfg["mode"] == "auto" intervals = { "video": intervals_cfg["video"], "document": intervals_cfg["document"], "scorm": intervals_cfg["scorm"], } with SessionLocal() as db: users = db.execute( select(Account.employee_id, Account.monthly_target, Account.month_hours, Account.credential_cipher, Account.password_cipher) .where(Account.credential_cipher != "") .where(Account.credential_valid == True) .order_by(Account.employee_id) ).all() courses = db.scalars(select(Course).order_by(Course.title)).all() course_list = [(c.path, c.title, c.kind) for c in courses] if not users or not course_list: _set_status(running=False, message="没有可用的用户或课程") return eligible = [] for row in users: target = row.monthly_target or 600 current = _parse_minutes(row.month_hours) if target > 0 and current < target: try: password = decrypt_secret(row.password_cipher) credential = json.loads(decrypt_secret(row.credential_cipher)) except Exception: continue eligible.append((row.employee_id, target, password, credential)) if not eligible: _set_status(running=False, message="所有用户已达标或无有效凭据") return _set_status(running=True, message=f"本轮 {len(eligible)} 个用户") sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS) tasks = [ self._study_user(emp_id, target, pw, cred, course_list, intervals, auto_mode, sem) for emp_id, target, pw, cred in eligible ] results = await asyncio.gather(*tasks, return_exceptions=True) for emp_id_tuple, result in zip(eligible, results): if isinstance(result, Exception): log.warning("用户 %s 自动学习失败: %s", emp_id_tuple[0], result) _clear_user_status(emp_id_tuple[0]) _set_status(running=False, message="本轮完成") async def _study_user(self, employee_id: str, target: int, password: str, credential: dict, course_list: list, intervals: dict, auto_mode: bool, sem: asyncio.Semaphore) -> None: assert self._async_stop is not None async with sem: _set_user_status(employee_id, state="准备", course="") loop = asyncio.get_event_loop() token, user_id, org_id, cookies = await loop.run_in_executor( None, _prepare_session, employee_id, password, credential) if not token: _set_user_status(employee_id, state="会话失效") return # 未来扩展:从数据库读取该用户的 proxy 和 max_concurrent_courses proxy = None max_courses = _MAX_COURSE_PER_USER async with StudySession(token, cookies, proxy=proxy) as session: session._employee_id = employee_id # type: ignore[attr-defined] _set_user_status(employee_id, state="学习中") async def check_target() -> bool: try: minutes_text = await session.month_hours_text() current = _parse_minutes(minutes_text) if minutes_text: _update_month_hours(employee_id, minutes_text) if current >= target: _set_user_status(employee_id, state="已达标") return True except Exception: pass return False if max_courses <= 1: await self._study_courses_serial( session, employee_id, course_list, intervals, auto_mode, check_target, user_id, org_id) else: await self._study_courses_parallel( session, employee_id, course_list, intervals, auto_mode, check_target, user_id, org_id, max_courses) async def _study_courses_serial(self, session: StudySession, employee_id: str, course_list: list, intervals: dict, auto_mode: bool, check_target, user_id: str, org_id: str) -> None: assert self._async_stop is not None for path, title, kind in course_list: if self._async_stop.is_set(): return await self._study_one_course( session, employee_id, path, title, kind, intervals, auto_mode, check_target, user_id, org_id) async def _study_courses_parallel(self, session: StudySession, employee_id: str, course_list: list, intervals: dict, auto_mode: bool, check_target, user_id: str, org_id: str, max_courses: int) -> None: """同一用户同时学多门课。共享 session 和 check_target。""" assert self._async_stop is not None course_sem = asyncio.Semaphore(max_courses) async def guarded(path: str, title: str, kind: str) -> None: async with course_sem: await self._study_one_course( session, employee_id, path, title, kind, intervals, auto_mode, check_target, user_id, org_id) tasks = [guarded(p, t, k) for p, t, k in course_list] await asyncio.gather(*tasks, return_exceptions=True) async def _study_one_course(self, session: StudySession, employee_id: str, path: str, title: str, kind: str, intervals: dict, auto_mode: bool, check_target, user_id: str, org_id: str) -> None: assert self._async_stop is not None ctype = _course_type(kind, path) if ctype == "unknown": return kid = _knowledge_id_from_path(path) if not kid: return _set_user_status(employee_id, course=title) try: if ctype == "package": await _study_package(session, kid, intervals, auto_mode, self._async_stop, check_target, user_id, org_id) else: progress = await session.update_progress(kid, "") if float(progress.get("studyschedule", 0)) >= 100: return interval = intervals.get(ctype, 120) page_size = 1 if auto_mode: try: params = await session.course_page_params(_play_path(kind, path, kid)) if ctype == "video": interval = params.get("submitProTimes", interval) else: interval = params.get("validtimeSpan", interval) page_size = params.get("pageSize", 1) except Exception: pass if ctype == "video": await _study_video(session, kid, "", interval, self._async_stop, check_target) elif ctype == "document": await _study_document(session, kid, "", page_size, interval, self._async_stop, check_target) elif ctype == "scorm": await _study_scorm(session, kid, "", interval, self._async_stop, check_target, user_id, org_id) except SessionExpired: _set_user_status(employee_id, state="会话过期") log.info("用户 %s 会话过期", employee_id) except Exception as exc: log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc) if await check_target(): return # ── 数据库更新 ── def _update_month_hours(employee_id: str, hours: str) -> None: from euniv.db import SessionLocal with SessionLocal() as db: account = db.get(Account, employee_id) if account: account.month_hours = hours db.commit() # ── 启动入口 ── _worker: AutoStudyWorker | None = None def start_autostudy() -> AutoStudyWorker: global _worker w = AutoStudyWorker() _worker = w w.start() return w