refactor: 自动学习改为 asyncio 并发架构,支持多用户并行和 proxy 预留

This commit is contained in:
2026-11-15 01:05:52 +08:00
parent ffa563d97c
commit 9e85a4184c
2 changed files with 551 additions and 227 deletions
+4 -4
View File
@@ -44,14 +44,14 @@ async def lifespan(_app: FastAPI):
ensure_admin_seed() ensure_admin_seed()
load_admin_identity() load_admin_identity()
stop_refresh = None stop_refresh = None
stop_study = None study_worker = None
if os.environ.get("EUNIV_DISABLE_REFRESH") != "1": if os.environ.get("EUNIV_DISABLE_REFRESH") != "1":
stop_refresh = start_credential_refresh() stop_refresh = start_credential_refresh()
from euniv.autostudy import start_autostudy from euniv.autostudy import start_autostudy
stop_study = start_autostudy() study_worker = start_autostudy()
yield yield
if stop_study is not None: if study_worker is not None:
stop_study.stop() study_worker.stop()
if stop_refresh is not None: if stop_refresh is not None:
stop_refresh.set() stop_refresh.set()
+499 -175
View File
@@ -1,26 +1,40 @@
"""自动学习:后台遍历用户和课程,发送心跳积累学时。""" """自动学习:asyncio 并发遍历用户和课程,发送心跳积累学时。
架构:
- 一个后台线程运行独立的 asyncio 事件循环
- 每个用户一个协程,asyncio.gather 并行
- 全局 Semaphore 控制总并发,避免压爆上游
- 每个用户一个 StudySession(httpx.AsyncClient),支持独立 proxy
- 每个用户可配置同时学几门课(当前默认 1,结构已预留)
- 心跳间隔用 asyncio.sleep,不占线程
"""
from __future__ import annotations from __future__ import annotations
import asyncio
import hashlib
import json import json
import logging import logging
import random import random
import re import re
import threading import threading
import time import time
import uuid
from datetime import datetime, timezone from datetime import datetime, timezone
import httpx
from sqlalchemy import select from sqlalchemy import select
from sqlalchemy.orm import Session
from euniv.client import EunivClient, SessionExpired from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired
from euniv.models import Account, Course from euniv.models import Account, Course
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
_SCORM_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696"
_MAX_CONCURRENT_USERS = 8
_MAX_COURSE_PER_USER = 1
_lock = threading.Lock() _lock = threading.Lock()
_status: dict = {"running": False, "user": "", "course": "", "message": "", "updated_at": ""} _status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""}
def autostudy_status() -> dict: def autostudy_status() -> dict:
@@ -34,6 +48,19 @@ def _set_status(**kw: object) -> None:
_status["updated_at"] = datetime.now(timezone.utc).isoformat() _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})") _ID_RE = re.compile(r"([0-9a-fA-F]{32})")
@@ -45,7 +72,6 @@ def _knowledge_id_from_path(path: str) -> str:
def _course_type(kind: str, path: str) -> str: def _course_type(kind: str, path: str) -> str:
"""从 kind 和 path 推断课程类型:video, document, scorm, package, unknown。"""
if kind == "课程包" or "/package/" in path: if kind == "课程包" or "/package/" in path:
return "package" return "package"
if kind == "课程" or "/scorm/" in path: if kind == "课程" or "/scorm/" in path:
@@ -57,74 +83,297 @@ def _course_type(kind: str, path: str) -> str:
return "unknown" return "unknown"
def _play_path(kind: str, path: str, knowledge_id: str) -> str: def _play_path(kind: str, path: str, kid: str) -> str:
"""构造播放页地址。"""
ctype = _course_type(kind, path) ctype = _course_type(kind, path)
if ctype == "video": if ctype == "video":
return f"/kng/view/video/{knowledge_id}.html" return f"/kng/view/video/{kid}.html"
if ctype == "document": if ctype == "document":
return f"/kng/view/document/{knowledge_id}.html" return f"/kng/view/document/{kid}.html"
if ctype == "scorm": if ctype == "scorm":
return f"/kng/view/scorm/{knowledge_id}.html" return f"/kng/view/scorm/{kid}.html"
return path return path
# ── 单门课程的学习逻辑 ──
def _jitter(seconds: int) -> float: def _jitter(seconds: int) -> float:
"""给间隔加 ±3 秒的随机偏移。"""
delta = random.uniform(-3.0, 3.0) delta = random.uniform(-3.0, 3.0)
return max(5.0, seconds + delta) return max(5.0, seconds + delta)
def _study_video(client: EunivClient, kid: str, pkg_id: str, def _scorm_md5(body_json: str) -> str:
interval: int, gate: threading.Event, 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: check_target) -> None:
"""视频课:每 interval 秒提交 submitpro,直到 studySchedule=100 或目标达成。"""
view = 0 view = 0
while not gate.is_set(): while not stop.is_set():
progress = client.update_progress(kid, pkg_id) progress = await session.update_progress(kid, pkg_id)
schedule = float(progress.get("studyschedule", 0)) schedule = float(progress.get("studyschedule", 0))
if schedule >= 100: if schedule >= 100:
return return
view = int(progress.get("viewSchedule", view)) view = int(progress.get("viewSchedule", view))
view += interval view += interval
result = client.submit_video_heartbeat(kid, pkg_id, interval, view) result = await session.submit_video_heartbeat(kid, pkg_id, interval, view)
new_schedule = result.get("studySchedule") new_schedule = result.get("studySchedule")
if new_schedule is not None and float(new_schedule) >= 100: if new_schedule is not None and float(new_schedule) >= 100:
return return
if check_target(): if await check_target():
return return
gate.wait(_jitter(interval)) await asyncio.sleep(_jitter(interval))
def _study_document(client: EunivClient, kid: str, pkg_id: str, async def _study_document(session: StudySession, kid: str, pkg_id: str,
page_size: int, interval: int, gate: threading.Event, page_size: int, interval: int, stop: asyncio.Event,
check_target) -> None: check_target) -> None:
"""文档课:每 interval 秒提交 study/submit,直到完成或目标达成。"""
view = 1 view = 1
while not gate.is_set(): while not stop.is_set():
progress = client.update_progress(kid, pkg_id) progress = await session.update_progress(kid, pkg_id)
schedule = float(progress.get("studyschedule", 0)) if float(progress.get("studyschedule", 0)) >= 100:
if schedule >= 100:
return return
client.submit_document_heartbeat(kid, pkg_id, page_size, interval, view) await session.submit_document_heartbeat(kid, pkg_id, page_size, interval, view)
if check_target(): if await check_target():
return return
gate.wait(_jitter(interval)) await asyncio.sleep(_jitter(interval))
def _study_scorm(client: EunivClient, kid: str, pkg_id: str, async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
interval: int, gate: threading.Event, interval: int, stop: asyncio.Event,
check_target) -> None: check_target, user_id: str, org_id: str) -> None:
"""Scorm 课:提交 scormstudy + study/submit (end=true),直到完成或目标达成。""" import uuid as _uuid
sco_cnt = client.scorm_count(kid) sco_cnt = await session.scorm_count(kid)
user_id = client.user_id() session_id = str(_uuid.uuid4())
org_id = str(client._profile.get("accountId") or "")
session_id = str(uuid.uuid4())
sco_id = kid sco_id = kid
existing = client.scorm_get(user_id, sco_id)
existing = await session.scorm_get(user_id, sco_id)
scorm_data = existing.get("data") if existing else None scorm_data = existing.get("data") if existing else None
if not scorm_data or not isinstance(scorm_data, dict): if not scorm_data or not isinstance(scorm_data, dict):
scorm_data = { scorm_data = {
@@ -139,129 +388,143 @@ def _study_scorm(client: EunivClient, kid: str, pkg_id: str,
scorm_data["cmi__core__lesson_status"] = "completed" scorm_data["cmi__core__lesson_status"] = "completed"
scorm_data["cmi__core__lesson_progress"] = "1.00" scorm_data["cmi__core__lesson_progress"] = "1.00"
answers = client.scorm_extract_answers(kid) answers = await session.scorm_extract_answers(kid)
total_pages = max(len(answers), 10) total_pages = max(len(answers), 10)
for page_idx in range(total_pages): for page_idx in range(total_pages):
if gate.is_set(): if stop.is_set():
return return
scorm_data["cmi__core__lesson_location"] = str(page_idx + 1) scorm_data["cmi__core__lesson_location"] = str(page_idx + 1)
scorm_data["cmi__core__session_time"] = "00:00:01" scorm_data["cmi__core__session_time"] = "00:00:01"
await session.scorm_save(
client.scorm_save(
session_id=session_id, org_id=org_id, user_id=user_id, session_id=session_id, org_id=org_id, user_id=user_id,
scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt, scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt,
package_id=pkg_id, master_id="", master_type="", pkg_id=pkg_id, data=scorm_data,
data=scorm_data,
) )
client.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True) await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True)
if await check_target():
if check_target():
return return
progress = await session.update_progress(kid, pkg_id)
progress = client.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100: if float(progress.get("studyschedule", 0)) >= 100:
return return
await asyncio.sleep(_jitter(min(interval, 5)))
gate.wait(_jitter(min(interval, 5))) while not stop.is_set():
progress = await session.update_progress(kid, pkg_id)
outer_rounds = 0
while not gate.is_set():
progress = client.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100: if float(progress.get("studyschedule", 0)) >= 100:
return return
client.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False) await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False)
outer_rounds += 1 if await check_target():
if check_target():
return return
gate.wait(_jitter(interval)) await asyncio.sleep(_jitter(interval))
def _study_package(client: EunivClient, kid: str, intervals: dict, async def _study_package(session: StudySession, kid: str, intervals: dict,
auto_mode: bool, gate: threading.Event, auto_mode: bool, stop: asyncio.Event,
check_target) -> None: check_target, user_id: str, org_id: str) -> None:
"""课程包:获取各章进度,逐章学习。""" pkg = await session.sync_package(kid)
pkg = client.sync_package(kid)
chapters = pkg.get("userKnowledgeList") or [] chapters = pkg.get("userKnowledgeList") or []
for ch in chapters: for ch in chapters:
if gate.is_set(): if stop.is_set():
return return
ch_schedule = float(ch.get("studySchedule", 0)) if float(ch.get("studySchedule", 0)) >= 100:
if ch_schedule >= 100:
continue continue
ch_kid = str(ch.get("knowledgeId") or "").replace("-", "") ch_kid = str(ch.get("knowledgeId") or "").replace("-", "")
ch_title = ch.get("title") or ch_kid ch_title = ch.get("title") or ch_kid
if not ch_kid: if not ch_kid:
continue continue
_set_status(course=ch_title) _set_user_status(session._employee_id, course=ch_title)
ch_type = "document" is_video = "Video" in str(ch.get("knowledgeType") or "")
ch_path = f"/kng/view/document/{ch_kid}.html" ch_type = "video" if is_video else "document"
if "Video" in str(ch.get("knowledgeType") or ""): ch_interval = intervals.get(ch_type, 30 if is_video else 120)
ch_type = "video"
ch_path = f"/kng/view/video/{ch_kid}.html"
ch_interval = intervals.get(ch_type, 30 if ch_type == "video" else 120)
page_size = 1 page_size = 1
if auto_mode: if auto_mode:
try: try:
params = client.course_page_params(f"/kng/course/package/{ch_type}/{kid}_{ch_kid}.html") params = await session.course_page_params(
if ch_type == "video": f"/kng/course/package/{ch_type}/{kid}_{ch_kid}.html")
ch_interval = params.get("submitProTimes", ch_interval) ch_interval = params.get("submitProTimes" if is_video else "validtimeSpan", ch_interval)
else:
ch_interval = params.get("validtimeSpan", ch_interval)
page_size = params.get("pageSize", 1) page_size = params.get("pageSize", 1)
except Exception: except Exception:
pass pass
if ch_type == "video": if is_video:
_study_video(client, ch_kid, kid, ch_interval, gate, check_target) await _study_video(session, ch_kid, kid, ch_interval, stop, check_target)
else: else:
_study_document(client, ch_kid, kid, page_size, ch_interval, gate, check_target) await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, check_target)
if await check_target():
if check_target():
return 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 主循环 ── # ── Worker 主循环 ──
class _AutoStudyGate: class AutoStudyWorker:
"""后台 asyncio 事件循环,管理所有用户的自动学习。"""
def __init__(self) -> None: def __init__(self) -> None:
self._event = threading.Event() 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: def stop(self) -> None:
self._event.set() self._stop_flag.set()
if self._loop and self._async_stop:
self._loop.call_soon_threadsafe(self._async_stop.set)
def is_set(self) -> bool: def _run_thread(self) -> None:
return self._event.is_set() self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
def wait(self, seconds: float) -> None: self._async_stop = asyncio.Event()
self._event.wait(timeout=max(0.0, seconds))
_gate: _AutoStudyGate | None = None
def start_autostudy() -> _AutoStudyGate:
global _gate
gate = _AutoStudyGate()
_gate = gate
threading.Thread(target=_main_loop, args=(gate,), name="euniv-autostudy", daemon=True).start()
return gate
def _main_loop(gate: _AutoStudyGate) -> None:
gate.wait(10)
while not gate.is_set():
try: try:
_run_cycle(gate) 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: except Exception as exc:
log.exception("自动学习周期异常: %s", exc) log.exception("自动学习周期异常: %s", exc)
_set_status(message=f"异常: {exc}") _set_status(message=f"异常: {exc}")
gate.wait(random.uniform(300, 600)) 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:
def _run_cycle(gate: _AutoStudyGate) -> None: assert self._async_stop is not None
from admin.settings import heartbeat_intervals from admin.settings import heartbeat_intervals
from euniv.crypto import decrypt_secret from euniv.crypto import decrypt_secret
from euniv.db import SessionLocal from euniv.db import SessionLocal
@@ -277,7 +540,7 @@ def _run_cycle(gate: _AutoStudyGate) -> None:
with SessionLocal() as db: with SessionLocal() as db:
users = db.execute( users = db.execute(
select(Account.employee_id, Account.monthly_target, Account.month_hours, select(Account.employee_id, Account.monthly_target, Account.month_hours,
Account.credential_valid, Account.credential_cipher, Account.password_cipher) Account.credential_cipher, Account.password_cipher)
.where(Account.credential_cipher != "") .where(Account.credential_cipher != "")
.where(Account.credential_valid == True) .where(Account.credential_valid == True)
.order_by(Account.employee_id) .order_by(Account.employee_id)
@@ -289,87 +552,140 @@ def _run_cycle(gate: _AutoStudyGate) -> None:
_set_status(running=False, message="没有可用的用户或课程") _set_status(running=False, message="没有可用的用户或课程")
return return
_set_status(running=True, message="") eligible = []
for row in users: for row in users:
if gate.is_set():
break
employee_id = row.employee_id
target = row.monthly_target or 600 target = row.monthly_target or 600
current = _parse_minutes(row.month_hours) current = _parse_minutes(row.month_hours)
if target <= 0 or current >= target: if target > 0 and current < target:
continue
_set_status(user=employee_id)
try: try:
password = decrypt_secret(row.password_cipher) password = decrypt_secret(row.password_cipher)
credential = json.loads(decrypt_secret(row.credential_cipher)) credential = json.loads(decrypt_secret(row.credential_cipher))
except Exception: except Exception:
continue continue
eligible.append((row.employee_id, target, password, credential))
client = EunivClient(employee_id, password) if not eligible:
try: _set_status(running=False, message="所有用户已达标或无有效凭据")
client.restore(credential) return
if not client.credential_alive():
continue
_study_user_courses(client, employee_id, target, course_list,
intervals, auto_mode, gate)
except SessionExpired:
log.info("用户 %s 会话过期", employee_id)
except Exception as exc:
log.exception("用户 %s 自动学习异常: %s", employee_id, exc)
finally:
client.close()
_set_status(running=False, user="", course="", message="本轮完成") _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])
def _study_user_courses(client: EunivClient, employee_id: str, target: int, _set_status(running=False, message="本轮完成")
async def _study_user(self, employee_id: str, target: int,
password: str, credential: dict,
course_list: list, intervals: dict, course_list: list, intervals: dict,
auto_mode: bool, gate: _AutoStudyGate) -> None: auto_mode: bool, sem: asyncio.Semaphore) -> None:
"""对一个用户依次学习课程列表,直到达到目标或全部完成。""" assert self._async_stop is not None
async with sem:
_set_user_status(employee_id, state="准备", course="")
def check_target() -> bool: 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: try:
minutes = client.month_hours() minutes_text = await session.month_hours_text()
current = _parse_minutes(minutes) current = _parse_minutes(minutes_text)
if minutes_text:
_update_month_hours(employee_id, minutes_text)
if current >= target: if current >= target:
_update_month_hours(employee_id, minutes) _set_user_status(employee_id, state="已达标")
return True return True
_update_month_hours(employee_id, minutes)
except Exception: except Exception:
pass pass
return False 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: for path, title, kind in course_list:
if gate.is_set(): if self._async_stop.is_set():
return 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) ctype = _course_type(kind, path)
if ctype == "unknown": if ctype == "unknown":
continue return
kid = _knowledge_id_from_path(path) kid = _knowledge_id_from_path(path)
if not kid: if not kid:
continue return
_set_status(course=title) _set_user_status(employee_id, course=title)
try: try:
if ctype == "package": if ctype == "package":
_study_package(client, kid, intervals, auto_mode, gate, check_target) await _study_package(session, kid, intervals, auto_mode,
self._async_stop, check_target, user_id, org_id)
else: else:
progress = client.update_progress(kid, "") progress = await session.update_progress(kid, "")
if float(progress.get("studyschedule", 0)) >= 100: if float(progress.get("studyschedule", 0)) >= 100:
continue return
interval = intervals.get(ctype, 120) interval = intervals.get(ctype, 120)
page_size = 1 page_size = 1
play_p = _play_path(kind, path, kid)
if auto_mode: if auto_mode:
try: try:
params = client.course_page_params(play_p) params = await session.course_page_params(_play_path(kind, path, kid))
if ctype == "video": if ctype == "video":
interval = params.get("submitProTimes", interval) interval = params.get("submitProTimes", interval)
else: else:
@@ -379,28 +695,23 @@ def _study_user_courses(client: EunivClient, employee_id: str, target: int,
pass pass
if ctype == "video": if ctype == "video":
_study_video(client, kid, "", interval, gate, check_target) await _study_video(session, kid, "", interval, self._async_stop, check_target)
elif ctype == "document": elif ctype == "document":
_study_document(client, kid, "", page_size, interval, gate, check_target) await _study_document(session, kid, "", page_size, interval, self._async_stop, check_target)
elif ctype == "scorm": elif ctype == "scorm":
_study_scorm(client, kid, "", interval, gate, check_target) await _study_scorm(session, kid, "", interval, self._async_stop,
check_target, user_id, org_id)
except SessionExpired: except SessionExpired:
raise _set_user_status(employee_id, state="会话过期")
log.info("用户 %s 会话过期", employee_id)
except Exception as exc: except Exception as exc:
log.warning("课程 %s 学习异常: %s", title, exc) log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
continue
if check_target(): if await check_target():
return return
def _parse_minutes(value: str) -> int: # ── 数据库更新 ──
"""从 month_hours 字符串解析分钟数。"""
if not value:
return 0
m = re.search(r"(\d+)", value)
return int(m.group(1)) if m else 0
def _update_month_hours(employee_id: str, hours: str) -> None: def _update_month_hours(employee_id: str, hours: str) -> None:
from euniv.db import SessionLocal from euniv.db import SessionLocal
@@ -409,3 +720,16 @@ def _update_month_hours(employee_id: str, hours: str) -> None:
if account: if account:
account.month_hours = hours account.month_hours = hours
db.commit() db.commit()
# ── 启动入口 ──
_worker: AutoStudyWorker | None = None
def start_autostudy() -> AutoStudyWorker:
global _worker
w = AutoStudyWorker()
_worker = w
w.start()
return w