"""自动学习:asyncio 并发遍历用户和课程,发送心跳积累学时。 架构: - 一个后台线程运行独立的 asyncio 事件循环 - 每个用户一个协程,asyncio.gather 并行 - 全局 Semaphore 控制总并发,避免压爆上游 - 每个用户一个 StudySession(httpx.AsyncClient),代理仅 HTTP/HTTPS/SOCKS4/SOCKS5 - 每个用户可配置同时学几门课(当前默认 1,结构已预留) - 心跳间隔用 asyncio.sleep,不占线程 - 本月学时:看完一门课后刷新,学习过程中每 1 分钟刷新;达到阈值即停止该账号 """ from __future__ import annotations import asyncio import contextlib import json import logging import math 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, _load_cookies, as_uuid, compact_id, play_page_params, study_progress_fields, ) from euniv.course_workers import of as course_workers_of from euniv.models import Account, Course from euniv.proxy import bind_url, is_proxy_failure, uses_pool from euniv.study_control import eligible as study_eligible from euniv.study_control import expire_pause, hours_met, stamp_hours from euniv.study_window import as_cn, next_fire_at, next_month_start log = logging.getLogger(__name__) _MAX_CONCURRENT_USERS = 8 _HOURS_REFRESH_SECONDS = 60.0 _KEEP_LIVE = frozenset({"已达标", "已停止", "会话失效", "学习失败", "已学完"}) _lock = threading.Lock() _status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""} _halt_lock = threading.Lock() _user_halts: dict[str, asyncio.Event] = {} _wanted: dict[str, int] = {} _wanted_seq = 0 _running: set[str] = set() _worker = None def _workers_list(info: dict) -> list[dict]: workers = info.get("workers") or {} if isinstance(workers, list): return [dict(item) for item in workers if isinstance(item, dict)] if not isinstance(workers, dict): return [] rows = [] for key in sorted(workers, key=lambda value: int(value) if str(value).isdigit() else 0): item = workers[key] if not isinstance(item, dict): continue row = dict(item) row.setdefault("id", int(key) if str(key).isdigit() else key) rows.append(row) return rows def autostudy_status() -> dict: with _lock: raw = {key: value for key, value in _status.items() if key != "users"} users_in = dict(_status.get("users") or {}) copied = {eid: dict(info) for eid, info in users_in.items()} for info in copied.values(): info["workers"] = _workers_list(info) raw["users"] = copied return raw def _notify(employee_id: str = "", urgent: bool = False) -> None: try: from euniv.study_push import notify notify(employee_id or None, urgent=urgent) except Exception: return def _set_status(**kw: object) -> None: with _lock: _status.update(kw) _status["updated_at"] = datetime.now(timezone.utc).isoformat() _notify() 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() _notify(employee_id) def _clear_user_status(employee_id: str) -> None: with _lock: _status.get("users", {}).pop(employee_id, None) _notify(employee_id) def _finish_user(employee_id: str, error: BaseException | None = None) -> None: """周期结束时保留失败/达标,避免首页只剩「等待执行」。""" if error is not None: _set_user_status(employee_id, state="学习失败", message=str(error)[:200], workers={}, course="") return with _lock: info = (_status.get("users") or {}).get(employee_id) or {} state = str(info.get("state") or "") if state in _KEEP_LIVE: _set_user_status(employee_id, workers={}, course="") return _clear_user_status(employee_id) def _set_worker_status(employee_id: str, worker_id: int, **kw: object) -> None: with _lock: users = _status.setdefault("users", {}) info = users.setdefault(employee_id, {}) workers = info.setdefault("workers", {}) if not isinstance(workers, dict): workers = {} info["workers"] = workers row = workers.setdefault(str(worker_id), {"id": worker_id}) row.update(kw) course = kw.get("course") if isinstance(course, str) and course: info["course"] = course _status["updated_at"] = datetime.now(timezone.utc).isoformat() _notify(employee_id) class WorkerView: def __init__(self, employee_id: str, worker_id: int) -> None: self.employee_id = employee_id self.worker_id = worker_id self.sent = 0 self.total = 0 self._course = "" self._origin = 0.0 def update(self, **kw: object) -> None: course = kw.get("course") if isinstance(course, str) and course != self._course: self._course = course self.sent = 0 self.total = 0 try: self._origin = float(kw.get("progress") or 0) except (TypeError, ValueError): self._origin = 0.0 kw.setdefault("sent", 0) kw.setdefault("total", 0) _set_worker_status(self.employee_id, self.worker_id, **kw) def after_beat(self, progress: float, **kw: object) -> None: self.sent += 1 planned = _count_total(self.sent, progress, self._origin) if self.total <= 0: self.total = planned elif progress >= 100: self.total = self.sent elif planned > self.total: self.total = planned if self.sent > self.total: self.total = self.sent self.update(progress=progress, sent=self.sent, total=self.total, **kw) def _touch(worker: WorkerView | None, **kw: object) -> None: if worker is not None: worker.update(**kw) def _beat(worker: WorkerView | None, progress: float, **kw: object) -> None: if worker is not None: worker.after_beat(progress, **kw) return _touch(worker, progress=progress, **kw) def _progress_of(payload: dict) -> float: raw = payload.get("studyschedule") if raw is None: raw = payload.get("studySchedule") try: return max(0.0, min(100.0, float(raw or 0))) except (TypeError, ValueError): return 0.0 class _Stall: """累计申报满 5 分钟仍无进度时放弃,避免短间隔把一门课打成死循环。""" def __init__(self) -> None: self.declared = 0 self.baseline: float | None = None def stuck(self, progress: float, sent: int) -> bool: if self.baseline is None: self.baseline = progress elif progress > self.baseline + 0.01: self.baseline = progress self.declared = 0 self.declared += max(0, sent) return self.declared >= 300 and progress <= self.baseline + 0.01 def _completed(payload: dict) -> bool: if not isinstance(payload, dict): return False if _progress_of(payload) >= 100: return True return str(payload.get("status") or "").strip().lower() == "completed" def _payload_time(wait: int, fallback: int) -> int: if wait > 0: return int(wait) return max(1, int(fallback or 1)) def _interval_plan(ctype: str, intervals: dict, auto_mode: bool, params: dict) -> tuple[int, int, int]: """返回 (等待秒, 心跳 studyTime, pageSize)。等待 0 表示连续发送,studyTime 仍用播放页间隔。""" video = ctype == "video" wait = int(intervals.get(ctype, 30 if video else 120) or 0) fallback = int((params or {}).get("submitProTimes" if video else "validtimeSpan") or (30 if video else 120)) if auto_mode: wait = fallback page_size = max(1, int((params or {}).get("pageSize") or 1)) return wait, _payload_time(wait, fallback), page_size def _current_intervals() -> tuple[dict, bool]: from admin.settings import heartbeat_intervals cfg = heartbeat_intervals() return { "video": int(cfg["video"]), "document": int(cfg["document"]), "scorm": int(cfg["scorm"]), }, cfg["mode"] == "auto" def _signal_stop(event: asyncio.Event | None) -> None: if event is None: return worker = _worker loop = getattr(worker, "_loop", None) if worker is not None else None if loop is not None and loop.is_running(): loop.call_soon_threadsafe(event.set) return event.set() def halt_work(employee_id: str) -> None: key = (employee_id or "").strip() if not key: return with _halt_lock: _wanted.pop(key, None) _running.discard(key) event = _user_halts.get(key) _signal_stop(event) _notify(key, urgent=True) def stop_account(employee_id: str) -> None: """停止学习、释放代理,并清掉内存里的状态和站点会话。""" key = (employee_id or "").strip() if not key: return request_stop(key) from euniv.client import forget_site from euniv.proxy_pool import release release(key) _clear_user_status(key) forget_site(key) def request_stop(employee_id: str) -> None: key = (employee_id or "").strip() if not key: return halt_work(key) _set_user_status(key, state="已停止", course="") def request_wake() -> None: worker = _worker if worker is not None: worker.wake() def want_work(employee_id: str) -> None: key = (employee_id or "").strip() if not key: return global _wanted_seq with _halt_lock: if key not in _wanted: _wanted_seq += 1 _wanted[key] = _wanted_seq _notify(key, urgent=True) def drop_work(employee_id: str) -> None: key = (employee_id or "").strip() if not key: return with _halt_lock: _wanted.pop(key, None) _notify(key, urgent=True) def is_wanted(employee_id: str) -> bool: key = (employee_id or "").strip() with _halt_lock: return key in _wanted def work_running(employee_id: str) -> bool: return is_studying(employee_id) or is_wanted(employee_id) def sync_work(employee_id: str) -> None: """保存配置或点开始后:达标则停,到期且未达标则拉起该账号的 work。""" from euniv.db import SessionLocal from euniv.models import Account key = (employee_id or "").strip() if not key: return with SessionLocal() as db: account = db.get(Account, key) if account is None: return if expire_pause(account): db.commit() met = hours_met(account) due = study_eligible(account) if met: halt_work(key) return if due: want_work(key) request_wake() return halt_work(key) _KIND_RANK = {"视频": 0, "文档": 1, "课程包": 2, "课程": 3} def snapshot_courses(rows) -> list[tuple[str, str, str]]: """work 启动时的课程清单快照。排序固定为 视频-文档-课程包-课程。""" items: list[tuple[str, str, str]] = [] for row in rows: if isinstance(row, (tuple, list)): path = str(row[0] if len(row) > 0 else "") title = str(row[1] if len(row) > 1 else "") kind = str(row[2] if len(row) > 2 else "") else: path = str(getattr(row, "path", "") or "") title = str(getattr(row, "title", "") or "") kind = str(getattr(row, "kind", "") or "") items.append((path, title, kind)) items.sort(key=lambda item: (_KIND_RANK.get(item[2], 9), item[1], item[0])) return items def _job_from_account(row) -> tuple | None: """从账号列表行提取一次凭据。之后 work 只用这份拷贝,不再读账号表。""" from euniv.crypto import decrypt_secret employee_id = str(getattr(row, "employee_id", "") or "") target_raw = getattr(row, "monthly_target", None) password_cipher = str(getattr(row, "password_cipher", "") or "") credential_cipher = str(getattr(row, "credential_cipher", "") or "") workers = course_workers_of(row) pool = uses_pool(row) 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) if employee_id: _set_user_status(employee_id, state="学习失败", message="凭据无法读取") return None target = int(target_raw) if target_raw is not None else 600 if target <= 0: return None try: password = decrypt_secret(password_cipher) credential = json.loads(decrypt_secret(credential_cipher)) except Exception as exc: log.warning("用户 %s 凭据无法读取: %s", employee_id, exc) if employee_id: _set_user_status(employee_id, state="学习失败", message="凭据无法读取") return None if not isinstance(credential, dict): return None return ( employee_id, target, password, credential, proxy, workers, pool, ) def is_studying(employee_id: str) -> bool: key = (employee_id or "").strip() with _halt_lock: return key in _running # ── 课程路径解析 ── _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: compact = compact_id(kid) ctype = _course_type(kind, path) if ctype == "video": return f"/kng/view/video/{compact}.html" if ctype == "document": return f"/kng/view/document/{compact}.html" if ctype == "scorm": return f"/kng/view/scorm/{compact}.html" if ctype == "package": return f"/kng/view/package/{compact}.html" return path def _package_chapter_path(pkg_id: str, ch_kid: str, ch_type: str) -> str: return f"/kng/course/package/{ch_type}/{compact_id(pkg_id)}_{compact_id(ch_kid)}.html" async def _open_play(session: "StudySession", path: str) -> dict: if not path: return {} try: return await session.course_page_params(path) except Exception: log.debug("打开播放页失败 %s", path, exc_info=True) return {} def _count_total(sent: int, progress: float, origin: float = 0.0) -> int: """按开课进度估算剩余心跳数。总数在 WorkerView 里冻结,避免每拍都变。""" if sent <= 0: return 0 if progress >= 100: return sent gained = float(progress) - float(origin) if gained <= 0: return 0 span = max(0.0, 100.0 - float(origin)) if span <= 0: return sent return max(sent, int(math.ceil(sent * span / gained))) def _jitter(seconds: int) -> float: """只往晚了偏,避免心跳比页面节奏更早发出。间隔为 0 时至少等 1 秒。""" if seconds <= 0: 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: if not value: return 0 m = re.search(r"(\d+)", value) return int(m.group(1)) if m else 0 async def wait_stop(timeout: float, *events: asyncio.Event) -> bool: """等到任一事件触发或超时。触发返回 True,超时返回 False。""" if any(event.is_set() for event in events): return True 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) class HoursWatcher: """刷新本月学时。看完一门课或每 1 分钟查一次,达标后停止该账号。""" def __init__( self, session: "StudySession", employee_id: str, target: int, user_stop: asyncio.Event, interval: float = _HOURS_REFRESH_SECONDS, source: str = "api", ) -> None: self.session = session self.employee_id = employee_id self.target = target self.user_stop = user_stop self.interval = interval self.source = source if source in ("api", "history") else "api" self._lock = asyncio.Lock() self.reached = False async def refresh(self) -> bool: async with self._lock: if self.reached or self.user_stop.is_set(): return True try: if self.source == "history": current = int(await self.session.month_history_minutes()) text = str(current) else: text = await self.session.month_hours_text() current = _parse_minutes(text) if text: await asyncio.to_thread(_update_month_hours, self.employee_id, text) if self.target > 0 and current >= self.target: self.reached = True self.user_stop.set() _set_user_status(self.employee_id, state="已达标") await asyncio.to_thread(_release_ignore_window, self.employee_id) return True except Exception: log.warning("用户 %s 刷新本月学时失败", self.employee_id, exc_info=True) return False async def ticker(self, global_stop: asyncio.Event) -> None: while not global_stop.is_set() and not self.user_stop.is_set(): if await wait_stop(self.interval, global_stop, self.user_stop): return await self.refresh() # ── Async 学习会话 ── class StudySession: """一个用户的异步学习会话。包装 httpx.AsyncClient,提供心跳提交方法。 proxy 为 httpx URL,仅 HTTP/HTTPS/SOCKS4/SOCKS5。空值直连。 """ def __init__(self, token: str, cookies: list[tuple[str, str, str, str]], proxy: str | None = None, employee_id: str = "", use_pool: bool = False) -> None: from euniv.proxy import parse_proxy self._token = token self._initial_cookies = cookies self._proxy = parse_proxy(proxy) self._employee_id = employee_id self._use_pool = use_pool self._client: httpx.AsyncClient | None = None async def __aenter__(self) -> "StudySession": from euniv.proxy import async_httpx_client self._client = async_httpx_client( self._proxy, timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT}, ) _load_cookies(self._client, self._initial_cookies) return self async def __aexit__(self, *args: object) -> None: if self._client: await self._client.aclose() async def _rotate_proxy(self) -> bool: if not self._use_pool: return False from euniv.proxy import parse_proxy from euniv.proxy_pool import acquire, mark_failed old = self._proxy await asyncio.to_thread(mark_failed, self._employee_id, old) nxt = await asyncio.to_thread(acquire, self._employee_id) parsed = parse_proxy(nxt) if parsed == old: return False from euniv.proxy import async_httpx_client client = async_httpx_client( parsed, timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT}, ) _load_cookies(client, self._initial_cookies) prev = self._client self._client = client self._proxy = parsed if prev is not None: await prev.aclose() return True async def _http(self, method: str, url: str, **kw: object) -> httpx.Response: assert self._client is not None try: return await self._client.request(method, url, **kw) except Exception as exc: if self._use_pool and self._proxy and is_proxy_failure(exc): if await self._rotate_proxy(): assert self._client is not None return await self._client.request(method, url, **kw) raise 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._http(method, url, headers=headers, **kw) refreshed = resp.headers.get("token") or resp.headers.get("Token") if refreshed: self._token = refreshed 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() except (json.JSONDecodeError, ValueError): 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: resp = await self._api("POST", f"{STUDY_API}/v1/study/updateprogress", json={"knowledgeId": as_uuid(kid), "packageId": as_uuid(pkg_id) if pkg_id else "", "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": as_uuid(kid), "sourceType": "SingleStudy", "masterId": ""}) return resp.json() async def get_encrypt_request(self, body_json: str) -> str: from euniv.encrypt import fetch_encryption_async assert self._client is not None try: return await fetch_encryption_async( self._client, body_json, origin=EUNIV, user_agent=USER_AGENT ) except Exception as exc: if self._use_pool and self._proxy and is_proxy_failure(exc): if await self._rotate_proxy(): assert self._client is not None return await fetch_encryption_async( self._client, body_json, origin=EUNIV, user_agent=USER_AGENT ) raise async def submit_video_heartbeat(self, kid: str, pkg_id: str, study_time: int, view_schedule: int) -> dict: param = study_progress_fields( kid, pkg_id, page_size=1, study_time=study_time, kind=0, view_schedule=view_schedule, ) encryption = await self.get_encrypt_request(json.dumps(param, separators=(",", ":"))) 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 = study_progress_fields( kid, pkg_id, page_size=page_size, study_time=study_time, kind=1, view_schedule=view_schedule, ) encryption = await self.get_encrypt_request(json.dumps(param, separators=(",", ":"))) 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: encrypt_param = study_progress_fields( kid, pkg_id, page_size=-1 if end else 1, study_time=study_time, kind=2, view_schedule=0, end=end, chapter_id=sco_id, for_encrypt=True, ) encryption = await self.get_encrypt_request(json.dumps(encrypt_param, separators=(",", ":"))) param = study_progress_fields( kid, pkg_id, page_size=-1 if end else 1, study_time=study_time, kind=2, view_schedule=0, end=end, chapter_id=sco_id, ) 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": as_uuid(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}/{as_uuid(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": as_uuid(scorm_id), "scormIdOri": as_uuid(scorm_id_ori), "masterId": "", "masterType": "", "packageId": as_uuid(pkg_id) if pkg_id else "", "scocnt": sco_cnt, "data": data, }) async def course_page_params(self, path: str) -> dict: assert self._client is not None resp = await self._http( "GET", f"{EUNIV}{path}", headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"}, ) html = resp.text from euniv.encrypt import note_play_html note_play_html(html, EUNIV) return play_page_params(html) 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 month_hours_text(self) -> str: assert self._client is not None resp = await self._http( "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 month_history_minutes(self, now: datetime | None = None) -> int: from euniv.client import ( HISTORY_PAGE_SIZE, fold_month_minutes, history_items_from_payload, history_search_body, ) from euniv.study_window import CN_TZ current = now or datetime.now(CN_TZ) year, month = current.year, current.month offset = 0 total = 0 first_mark: tuple | None = None for _ in range(50): resp = await self._api( "POST", f"{STUDY_API}/v1/styhis/studyhistory/daily/search", json=history_search_body(True, offset, HISTORY_PAGE_SIZE), ) rows = history_items_from_payload(resp.json()) if rows is None: if offset == 0: raise RuntimeError("学时历史没有获取到") return total if not rows: return total add, done = fold_month_minutes(rows, year, month) total += add if done or len(rows) != HISTORY_PAGE_SIZE: return total mark = ( len(rows), rows[0].get("studied_at"), rows[0].get("title"), rows[-1].get("studied_at"), rows[-1].get("title"), ) if offset == 0: first_mark = mark elif mark == first_mark: return total offset += HISTORY_PAGE_SIZE return total # ── 单门课程的学习协程 ── def _halted(global_stop: asyncio.Event, hours: HoursWatcher) -> bool: return global_stop.is_set() or hours.user_stop.is_set() class CourseCursor: """多协程顺着同一份课程表往下领,每门课只被领取一次。""" def __init__(self, courses: list) -> None: self._courses = list(courses) self._index = 0 self._lock = asyncio.Lock() async def take(self): async with self._lock: if self._index >= len(self._courses): return None item = self._courses[self._index] self._index += 1 return item async def _heartbeat_wait( worker: WorkerView | None, interval: int, stop: asyncio.Event, hours: HoursWatcher, progress: float, ) -> bool: delay = _jitter(interval) _touch(worker, interval=interval, heartbeat_at=time.time() + delay, progress=progress, ok=True) return await wait_stop(delay, stop, hours.user_stop) 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: 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() while not _halted(stop, hours): 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): if started: await hours.refresh() return 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: _touch(worker, ok=False) raise new_schedule = result.get("studySchedule") if new_schedule is not None: schedule = _progress_of({"studySchedule": new_schedule}) _beat(worker, schedule, ok=True) if schedule >= 100: await hours.refresh() return if stall.stuck(schedule, step): raise RuntimeError("进度长时间没有变化") 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, page_size: int, interval: int, stop: asyncio.Event, hours: HoursWatcher, worker: WorkerView | None = None, study_time: int | 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() while not _halted(stop, hours): 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): if started: await hours.refresh() 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) 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: 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, interval: int, stop: asyncio.Event, hours: HoursWatcher, user_id: str, org_id: str, worker: WorkerView | None = None, study_time: int | 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 schedule = _progress_of(progress) _touch(worker, progress=schedule, ok=True) if _completed(progress): return if not user_id or not org_id: while not _halted(stop, hours): try: await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id="", end=False) 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 await _heartbeat_wait(worker, interval, stop, hours, schedule): return return 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": "incomplete", "cmi__core__lesson_location": "1", "cmi__core__lesson_progress": "0.00", "cmi__core__session_time": "00:00:01", "cmi__core__exit": "suspend", "cmi__suspend_data": {}, } total_pages = max(1, int(sco_cnt or 1)) for page_idx in range(total_pages): if _halted(stop, hours): return scorm_data["cmi__core__lesson_location"] = str(page_idx + 1) scorm_data["cmi__core__lesson_progress"] = f"{(page_idx + 1) / total_pages:.2f}" scorm_data["cmi__core__lesson_status"] = "completed" if page_idx + 1 == total_pages else "incomplete" scorm_data["cmi__core__session_time"] = "00:00:01" try: 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, step, sco_id=sco_id, end=True) 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 page_wait = interval if interval <= 0 else min(interval, 5) if await _heartbeat_wait(worker, page_wait, stop, hours, schedule): return while not _halted(stop, hours): 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): await hours.refresh() return try: await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id=sco_id, end=False) 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 await _heartbeat_wait(worker, interval, stop, hours, schedule): return 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) -> None: pkg = await session.sync_package(kid) if _completed(pkg): _touch(worker, progress=_progress_of(pkg), ok=True) return chapters = pkg.get("userKnowledgeList") or [] for ch in chapters: if _halted(stop, hours): return if _completed(ch): continue ch_kid = str(ch.get("knowledgeId") or "").strip() ch_title = ch.get("title") or ch_kid if not compact_id(ch_kid): continue _set_user_status(session._employee_id, course=ch_title) _touch(worker, course=ch_title, progress=_progress_of(ch), ok=True) is_video = "Video" in str(ch.get("knowledgeType") or "") ch_type = "video" if is_video else "document" 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: await _study_video(session, ch_kid, kid, wait, stop, hours, worker, study_time=study_time) else: await _study_document( session, ch_kid, kid, page_size, wait, stop, hours, worker, study_time=study_time, ) # ── 同步准备:用 EunivClient 建立会话,导出 cookies ── def _prepare_session(employee_id: str, password: str, credential: dict, proxy: str | None = None, use_pool: bool = False ) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None]: """同步:恢复会话并导出 cookies。返回 (token, user_id, org_id, cookies, proxy)。""" from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed current = proxy last_exc: BaseException | None = None for _ in range(MAX_SWITCHES + 1): client = EunivClient(employee_id, password, proxy=current) try: client.restore(credential) if not client.credential_alive(): return "", "", "", [], current 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, current except Exception as exc: last_exc = exc log.warning("用户 %s 准备会话失败: %s", employee_id, exc) if use_pool and current and is_proxy_failure(exc): mark_failed(employee_id, current, str(exc)[:200]) current = acquire(employee_id) continue return "", "", "", [], current finally: client.close() if last_exc is not None: log.warning("用户 %s 准备会话失败: %s", employee_id, last_exc) return "", "", "", [], current # ── 启动器 + 按账号 Work ── class AutoStudyWorker: """定时启动器:到点检查各账号,已有 work 则跳过,未达标才拉起。""" 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 self._kick: asyncio.Event | None = None self._tasks: dict[str, asyncio.Task] = {} self._sem: asyncio.Semaphore | 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 wake(self) -> None: if self._loop and self._kick is not None: self._loop.call_soon_threadsafe(self._kick.set) def _run_thread(self) -> None: self._loop = asyncio.new_event_loop() asyncio.set_event_loop(self._loop) self._async_stop = asyncio.Event() self._kick = 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 assert self._kick is not None self._sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS) while not self._async_stop.is_set(): self._kick.clear() try: delay = self._tick() except Exception as exc: log.exception("自动学习调度异常: %s", exc) _set_status(message=f"异常: {exc}") delay = 30.0 if self._async_stop.is_set(): return if self._kick.is_set(): continue await wait_stop(delay, self._async_stop, self._kick) def _alive(self) -> int: dead = [eid for eid, task in self._tasks.items() if task.done()] for eid in dead: self._tasks.pop(eid, None) return len(self._tasks) def _busy(self, employee_id: str) -> bool: task = self._tasks.get(employee_id) if task is not None and not task.done(): return True return is_studying(employee_id) def _tick(self) -> float: from euniv.db import SessionLocal now = as_cn() soonest = next_month_start(now) jobs: list[tuple] = [] course_list: list[tuple[str, str, str]] = [] with SessionLocal() as db: users = db.scalars( select(Account) .where(Account.credential_cipher != "") .where(Account.credential_valid == True) .order_by(Account.employee_id) ).all() expired = False for row in users: if expire_pause(row): expired = True eid = row.employee_id fire = next_fire_at(row, now) if fire is not None and fire < soonest: soonest = fire if hours_met(row): if is_studying(eid) or is_wanted(eid): halt_work(eid) continue if not (study_eligible(row) or is_wanted(eid)): continue if self._busy(eid): continue job = _job_from_account(row) if job is None: drop_work(eid) continue jobs.append(job) if jobs: course_list = snapshot_courses(db.scalars(select(Course)).all()) if expired: db.commit() launched = 0 for job in jobs: if self._launch(job, course_list): launched += 1 alive = self._alive() wait = max(1.0, (soonest - as_cn()).total_seconds()) if alive: _set_status(running=True, message=f"运行中 {alive} 个账号") elif launched: _set_status(running=True, message=f"正在启动 {launched} 个账号") else: label = soonest.strftime("%m-%d %H:%M:%S") _set_status(running=False, message=f"下一次定时 {label}") return wait def _launch(self, job: tuple, course_list: list[tuple[str, str, str]]) -> bool: eid = job[0] if self._busy(eid): return False if not course_list: _set_user_status(eid, state="学习失败", message="没有可用的课程") drop_work(eid) return False want_work(eid) with _halt_lock: generation = _wanted.get(eid, 0) assert self._loop is not None self._tasks[eid] = self._loop.create_task(self._run_account(job, list(course_list), generation)) log.info("启动账号 %s 的学习任务", eid) return True async def _run_account(self, job: tuple, course_list: list[tuple[str, str, str]], generation: int) -> None: emp_id, target, pw, cred, proxy, workers, use_pool = job try: from admin.settings import hours_source_of hours_source = hours_source_of() intervals, auto_mode = _current_intervals() if not course_list: _set_user_status(emp_id, state="学习失败", message="没有可用的课程") return 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, ) except Exception as exc: log.warning("用户 %s 自动学习失败: %s", emp_id, exc) _finish_user(emp_id, exc) else: _finish_user(emp_id) finally: with _halt_lock: current = _wanted.get(emp_id) if current == generation: drop_work(emp_id) elif current is not None and self._kick is not None: self._kick.set() self._tasks.pop(emp_id, None) 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: assert self._async_stop is not None user_stop = asyncio.Event() with _halt_lock: current = _user_halts.get(employee_id) if current is not None and employee_id in _running: return _user_halts[employee_id] = user_stop _running.add(employee_id) try: async with sem: if user_stop.is_set(): _set_user_status(employee_id, state="已停止") return _set_user_status(employee_id, state="准备", course="", workers={}) loop = asyncio.get_event_loop() token, user_id, org_id, cookies, proxy = await loop.run_in_executor( None, _prepare_session, employee_id, password, credential, proxy, use_pool) if not token: _set_user_status(employee_id, state="会话失效", message="无法连接学习平台") 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] _set_user_status(employee_id, state="学习中") hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source) if await hours.refresh(): return ticker = asyncio.create_task(hours.ticker(self._async_stop)) try: await self._study_courses( session, employee_id, course_list, intervals, auto_mode, hours, user_id, org_id, workers) if hours.reached: return if user_stop.is_set() or self._async_stop.is_set(): return _set_user_status(employee_id, state="已学完", course="", workers={}) finally: ticker.cancel() with contextlib.suppress(asyncio.CancelledError): await ticker finally: with _halt_lock: if _user_halts.get(employee_id) is user_stop: _user_halts.pop(employee_id, None) _running.discard(employee_id) if use_pool: from euniv.proxy_pool import release release(employee_id) async def _study_courses(self, session: StudySession, employee_id: str, course_list: list, intervals: dict, auto_mode: bool, hours: HoursWatcher, user_id: str, org_id: str, workers: int) -> None: """N 个协程顺着课程表往下领,已完成的跳过,未完成的发心跳。""" assert self._async_stop is not None cursor = CourseCursor(course_list) count = max(1, min(8, int(workers or 1))) async def worker_loop(index: int) -> None: view = WorkerView(employee_id, index) view.update(course="", progress=0, interval=0, heartbeat_at=0, ok=True) while not _halted(self._async_stop, hours): item = await cursor.take() if item is None: view.update(course="", progress=100, interval=0, heartbeat_at=0, ok=True) return path, title, kind = item await self._study_one_course( session, employee_id, path, title, kind, intervals, auto_mode, hours, user_id, org_id, view) await asyncio.gather(*(worker_loop(index) for index in range(1, count + 1))) 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) -> None: assert self._async_stop is not None if _halted(self._async_stop, hours): return ctype = _course_type(kind, path) if ctype == "unknown": return kid = _knowledge_id_from_path(path) if not kid: return intervals, auto_mode = _current_intervals() _set_user_status(employee_id, course=title) try: params = await _open_play(session, _play_path(kind, path, kid)) if ctype == "package": _touch(worker, course=title, progress=0, ok=True) await _study_package(session, kid, intervals, auto_mode, self._async_stop, hours, user_id, org_id, worker) return progress = await session.update_progress(kid, "") schedule = _progress_of(progress) _touch(worker, course=title, progress=schedule, ok=True) if _completed(progress): return wait, study_time, page_size = _interval_plan(ctype, intervals, auto_mode, params) if ctype == "video": await _study_video( session, kid, "", wait, self._async_stop, hours, worker, study_time=study_time, ) elif ctype == "document": await _study_document( session, kid, "", page_size, wait, self._async_stop, hours, worker, study_time=study_time, ) 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, ) except SessionExpired: hours.user_stop.set() _touch(worker, ok=False) _set_user_status(employee_id, state="会话失效", message="请重新登录") log.info("用户 %s 会话过期", employee_id) except Exception as exc: _touch(worker, ok=False) log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc) # ── 数据库更新 ── 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: stamp_hours(account, hours) db.commit() _set_user_status(employee_id, month_hours=hours) def _release_ignore_window(employee_id: str) -> None: from euniv.db import SessionLocal with SessionLocal() as db: account = db.get(Account, employee_id) if account is None or not account.study_ignore_window: return account.study_ignore_window = False db.commit() # ── 启动入口 ── def start_autostudy() -> AutoStudyWorker: global _worker w = AutoStudyWorker() _worker = w w.start() return w