feat: 自动学习功能,后台定时发送心跳积累学时

This commit is contained in:
2026-11-15 01:01:45 +08:00
parent 2acf310e0c
commit ffa563d97c
13 changed files with 959 additions and 16 deletions
+42 -4
View File
@@ -31,18 +31,29 @@ from euniv.service import (
)
from euniv.session import clear_session, read_employee_id, write_session
from pydantic import BaseModel as _BaseModel
class MonthlyTargetBody(_BaseModel):
monthly_target: int
@asynccontextmanager
async def lifespan(_app: FastAPI):
init_db()
ensure_admin_seed()
load_admin_identity()
stop = None
stop_refresh = None
stop_study = None
if os.environ.get("EUNIV_DISABLE_REFRESH") != "1":
stop = start_credential_refresh()
stop_refresh = start_credential_refresh()
from euniv.autostudy import start_autostudy
stop_study = start_autostudy()
yield
if stop is not None:
stop.set()
if stop_study is not None:
stop_study.stop()
if stop_refresh is not None:
stop_refresh.set()
app = FastAPI(title="EunivTools", lifespan=lifespan)
@@ -186,6 +197,33 @@ def exam_detail(path: str, request: Request, db: Session = Depends(get_db)) -> d
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/settings/monthly-target")
def get_monthly_target(request: Request, db: Session = Depends(get_db)) -> dict:
employee_id = _signed_in(request, db)
account = db.get(Account, employee_id)
return {"monthly_target": account.monthly_target if account else 600}
@app.put("/api/settings/monthly-target")
def put_monthly_target(body: MonthlyTargetBody, request: Request, db: Session = Depends(get_db)) -> dict:
employee_id = _signed_in(request, db)
if not 0 <= body.monthly_target <= 9999:
raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数")
account = db.get(Account, employee_id)
if account is None:
raise HTTPException(status_code=401, detail="未登录")
account.monthly_target = body.monthly_target
db.commit()
return {"monthly_target": account.monthly_target}
@app.get("/api/autostudy/status")
def autostudy_state(request: Request, db: Session = Depends(get_db)) -> dict:
_signed_in(request, db)
from euniv.autostudy import autostudy_status
return autostudy_status()
@app.get("/api/training")
def training_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
try:
+411
View File
@@ -0,0 +1,411 @@
"""自动学习:后台遍历用户和课程,发送心跳积累学时。"""
from __future__ import annotations
import json
import logging
import random
import re
import threading
import time
import uuid
from datetime import datetime, timezone
from sqlalchemy import select
from sqlalchemy.orm import Session
from euniv.client import EunivClient, SessionExpired
from euniv.models import Account, Course
log = logging.getLogger(__name__)
_lock = threading.Lock()
_status: dict = {"running": False, "user": "", "course": "", "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()
# ── 课程路径解析 ──
_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:
"""从 kind 和 path 推断课程类型:video, document, scorm, package, unknown。"""
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, knowledge_id: str) -> str:
"""构造播放页地址。"""
ctype = _course_type(kind, path)
if ctype == "video":
return f"/kng/view/video/{knowledge_id}.html"
if ctype == "document":
return f"/kng/view/document/{knowledge_id}.html"
if ctype == "scorm":
return f"/kng/view/scorm/{knowledge_id}.html"
return path
# ── 单门课程的学习逻辑 ──
def _jitter(seconds: int) -> float:
"""给间隔加 ±3 秒的随机偏移。"""
delta = random.uniform(-3.0, 3.0)
return max(5.0, seconds + delta)
def _study_video(client: EunivClient, kid: str, pkg_id: str,
interval: int, gate: threading.Event,
check_target) -> None:
"""视频课:每 interval 秒提交 submitpro,直到 studySchedule=100 或目标达成。"""
view = 0
while not gate.is_set():
progress = client.update_progress(kid, pkg_id)
schedule = float(progress.get("studyschedule", 0))
if schedule >= 100:
return
view = int(progress.get("viewSchedule", view))
view += interval
result = client.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 check_target():
return
gate.wait(_jitter(interval))
def _study_document(client: EunivClient, kid: str, pkg_id: str,
page_size: int, interval: int, gate: threading.Event,
check_target) -> None:
"""文档课:每 interval 秒提交 study/submit,直到完成或目标达成。"""
view = 1
while not gate.is_set():
progress = client.update_progress(kid, pkg_id)
schedule = float(progress.get("studyschedule", 0))
if schedule >= 100:
return
client.submit_document_heartbeat(kid, pkg_id, page_size, interval, view)
if check_target():
return
gate.wait(_jitter(interval))
def _study_scorm(client: EunivClient, kid: str, pkg_id: str,
interval: int, gate: threading.Event,
check_target) -> None:
"""Scorm 课:提交 scormstudy + study/submit (end=true),直到完成或目标达成。"""
sco_cnt = client.scorm_count(kid)
user_id = client.user_id()
org_id = str(client._profile.get("accountId") or "")
session_id = str(uuid.uuid4())
sco_id = kid
existing = client.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 = client.scorm_extract_answers(kid)
total_pages = max(len(answers), 10)
for page_idx in range(total_pages):
if gate.is_set():
return
scorm_data["cmi__core__lesson_location"] = str(page_idx + 1)
scorm_data["cmi__core__session_time"] = "00:00:01"
client.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,
package_id=pkg_id, master_id="", master_type="",
data=scorm_data,
)
client.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True)
if check_target():
return
progress = client.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100:
return
gate.wait(_jitter(min(interval, 5)))
outer_rounds = 0
while not gate.is_set():
progress = client.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100:
return
client.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False)
outer_rounds += 1
if check_target():
return
gate.wait(_jitter(interval))
def _study_package(client: EunivClient, kid: str, intervals: dict,
auto_mode: bool, gate: threading.Event,
check_target) -> None:
"""课程包:获取各章进度,逐章学习。"""
pkg = client.sync_package(kid)
chapters = pkg.get("userKnowledgeList") or []
for ch in chapters:
if gate.is_set():
return
ch_schedule = float(ch.get("studySchedule", 0))
if ch_schedule >= 100:
continue
ch_kid = str(ch.get("knowledgeId") or "").replace("-", "")
ch_title = ch.get("title") or ch_kid
if not ch_kid:
continue
_set_status(course=ch_title)
ch_type = "document"
ch_path = f"/kng/view/document/{ch_kid}.html"
if "Video" in str(ch.get("knowledgeType") or ""):
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
if auto_mode:
try:
params = client.course_page_params(f"/kng/course/package/{ch_type}/{kid}_{ch_kid}.html")
if ch_type == "video":
ch_interval = params.get("submitProTimes", ch_interval)
else:
ch_interval = params.get("validtimeSpan", ch_interval)
page_size = params.get("pageSize", 1)
except Exception:
pass
if ch_type == "video":
_study_video(client, ch_kid, kid, ch_interval, gate, check_target)
else:
_study_document(client, ch_kid, kid, page_size, ch_interval, gate, check_target)
if check_target():
return
# ── Worker 主循环 ──
class _AutoStudyGate:
def __init__(self) -> None:
self._event = threading.Event()
def stop(self) -> None:
self._event.set()
def is_set(self) -> bool:
return self._event.is_set()
def wait(self, seconds: float) -> None:
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:
_run_cycle(gate)
except Exception as exc:
log.exception("自动学习周期异常: %s", exc)
_set_status(message=f"异常: {exc}")
gate.wait(random.uniform(300, 600))
def _run_cycle(gate: _AutoStudyGate) -> 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_valid, 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
_set_status(running=True, message="")
for row in users:
if gate.is_set():
break
employee_id = row.employee_id
target = row.monthly_target or 600
current = _parse_minutes(row.month_hours)
if target <= 0 or current >= target:
continue
_set_status(user=employee_id)
try:
password = decrypt_secret(row.password_cipher)
credential = json.loads(decrypt_secret(row.credential_cipher))
except Exception:
continue
client = EunivClient(employee_id, password)
try:
client.restore(credential)
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="本轮完成")
def _study_user_courses(client: EunivClient, employee_id: str, target: int,
course_list: list, intervals: dict,
auto_mode: bool, gate: _AutoStudyGate) -> None:
"""对一个用户依次学习课程列表,直到达到目标或全部完成。"""
def check_target() -> bool:
"""检查当前月学时是否达标。"""
try:
minutes = client.month_hours()
current = _parse_minutes(minutes)
if current >= target:
_update_month_hours(employee_id, minutes)
return True
_update_month_hours(employee_id, minutes)
except Exception:
pass
return False
for path, title, kind in course_list:
if gate.is_set():
return
ctype = _course_type(kind, path)
if ctype == "unknown":
continue
kid = _knowledge_id_from_path(path)
if not kid:
continue
_set_status(course=title)
try:
if ctype == "package":
_study_package(client, kid, intervals, auto_mode, gate, check_target)
else:
progress = client.update_progress(kid, "")
if float(progress.get("studyschedule", 0)) >= 100:
continue
interval = intervals.get(ctype, 120)
page_size = 1
play_p = _play_path(kind, path, kid)
if auto_mode:
try:
params = client.course_page_params(play_p)
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":
_study_video(client, kid, "", interval, gate, check_target)
elif ctype == "document":
_study_document(client, kid, "", page_size, interval, gate, check_target)
elif ctype == "scorm":
_study_scorm(client, kid, "", interval, gate, check_target)
except SessionExpired:
raise
except Exception as exc:
log.warning("课程 %s 学习异常: %s", title, exc)
continue
if check_target():
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:
from euniv.db import SessionLocal
with SessionLocal() as db:
account = db.get(Account, employee_id)
if account:
account.month_hours = hours
db.commit()
+226
View File
@@ -3,7 +3,9 @@
from __future__ import annotations
import base64
import hashlib
import io
import json
import random
import re
import threading
@@ -363,6 +365,14 @@ def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
return best_x
_SCORM_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696"
def _scorm_md5(body_json: str) -> str:
"""RteApiSite.js 里的本地 MD5:hex_md5(JSON + 固定 key)。"""
return hashlib.md5((body_json + _SCORM_MD5_KEY).encode("utf-8")).hexdigest()
class SessionExpired(RuntimeError):
"""学习平台凭证失效,需要重新登录。"""
@@ -894,3 +904,219 @@ class EunivClient:
profile = self.login()
self.authorize(profile)
return {"profile": self.user_info(), "summary": self.study_snapshot()}
# ── 自动学习所需方法 ──
def course_page_params(self, path: str) -> dict:
"""打开播放页,解析 JS 变量。返回 knowledgeType, submitProTimes, validtimeSpan, standardStudyHours, pageSize 等。"""
html = self._site_page(path)
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 {
"knowledgeType": _var("knowledgeType"),
"submitIsOpen": _var("submitIsOpen", "0"),
"submitProTimes": int(_var("submitProTimes", "30") or 30),
"validtimeSpan": int(_var("validtimeSpan", "120") or 120),
"standardStudyHours": int(_var("standardStudyHours", "0") or 0),
"pageSize": int(_var("pageSize", "1") or 1),
"fileType": _var("fileType"),
"kngId": _var("kngId"),
"packageID": _var("packageID"),
"orgID": _var("orgID"),
"userID": _var("userID"),
}
def update_progress(self, knowledge_id: str, package_id: str = "",
master_id: str = "", master_type: str = "") -> dict:
"""POST /v1/study/updateprogress。返回 studyschedule, actualstudyhours, standardstudyhours, viewSchedule, status。"""
body = {
"knowledgeId": knowledge_id,
"packageId": package_id,
"masterId": master_id,
"masterType": master_type,
}
resp = self._request("POST", f"{STUDY_API}/v1/study/updateprogress", json=body)
return resp.json()
def sync_package(self, knowledge_id: str) -> dict:
"""GET /v1/uk/syncpackage。返回整包和各章信息。"""
resp = self._request("GET", f"{STUDY_API}/v1/uk/syncpackage",
params={"knowledgeId": knowledge_id, "sourceType": "SingleStudy", "masterId": ""})
return resp.json()
def get_encrypt_request(self, body_json: str) -> str:
"""POST GetEncryptRequest,返回 32 位 MD5 摘要。"""
resp = 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}")
def submit_video_heartbeat(self, knowledge_id: str, package_id: str,
study_time: int, view_schedule: int,
master_id: str = "", master_type: str = "") -> dict:
"""视频心跳 POST /v1/study/submitpro。"""
param = {
"knowledgeId": knowledge_id,
"masterId": master_id,
"masterType": master_type,
"packageId": package_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 = self.get_encrypt_request(encrypt_body)
param["encryption"] = encryption
param["multiple"] = 1
param["realHour"] = study_time
resp = self._request("POST", f"{STUDY_API}/v1/study/submitpro",
content=json.dumps(param, separators=(",", ":")))
text = resp.text.strip()
if not text:
return {}
return resp.json()
def submit_document_heartbeat(self, knowledge_id: str, package_id: str,
page_size: int, study_time: int,
view_schedule: int,
master_id: str = "", master_type: str = "") -> dict:
"""文档心跳 POST /v1/study/submit。"""
param = {
"knowledgeId": knowledge_id,
"masterId": master_id,
"masterType": master_type,
"packageId": package_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 = self.get_encrypt_request(encrypt_body)
param["multiple"] = 1
param["realHour"] = study_time
resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
content=json.dumps(param, separators=(",", ":")))
return {}
def submit_scorm_heartbeat(self, knowledge_id: str, package_id: str,
study_time: int, sco_id: str = "",
end: bool = False,
master_id: str = "", master_type: str = "") -> dict:
"""Scorm 心跳 POST /v1/study/submit,type=2。"""
param = {
"knowledgeId": knowledge_id,
"masterId": master_id,
"masterType": master_type,
"packageId": package_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 = self.get_encrypt_request(encrypt_body)
param["multiple"] = 1
param["realHour"] = study_time
resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
content=json.dumps(param, separators=(",", ":")))
return {}
def scorm_count(self, knowledge_id: str) -> int:
"""GET /v1/kng/scorm/count/。"""
resp = self._request("GET", f"{STUDY_API}/v1/kng/scorm/count/",
params={"knowledgeId": knowledge_id})
data = resp.json()
return int(data.get("scocnt") or 1)
def scorm_get(self, user_id: str, sco_id: str) -> dict:
"""GET /v1/scormstudy/{userId}/{scoId}。"""
resp = self._request("GET", f"https://api-mall.yxt.com/v1/scormstudy/{user_id}/{sco_id}")
text = resp.text.strip()
if not text:
return {}
return resp.json()
def scorm_save(self, session_id: str, org_id: str, user_id: str,
scorm_id: str, scorm_id_ori: str, sco_cnt: int,
package_id: str, master_id: str, master_type: str,
data: dict) -> None:
"""POST /v1/scormstudy。"""
body = {
"sessionId": session_id,
"orgId": org_id,
"userId": user_id,
"scormId": scorm_id,
"scormIdOri": scorm_id_ori,
"masterId": master_id,
"masterType": master_type,
"packageId": package_id,
"scocnt": sco_cnt,
"data": data,
}
self._request("POST", "https://api-mall.yxt.com/v1/scormstudy",
json=body)
def scorm_page_files(self, knowledge_id: str) -> list[str]:
"""下载 Scorm 课件的页索引,返回各页 .oss.js 的 URL 列表。"""
index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{knowledge_id}/h5/js/index-scorm.js"
resp = self.client.get(index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"})
urls = []
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/{knowledge_id}/h5/js/{raw}")
return urls
def scorm_extract_answers(self, knowledge_id: str) -> list[dict]:
"""下载 .oss.js 页,提取题目和正确答案。"""
urls = self.scorm_page_files(knowledge_id)
answers = []
for url in urls:
try:
resp = self.client.get(url, headers={"User-Agent": USER_AGENT})
text = resp.text
for block in re.finditer(r'单选题([\s\S]*?)正确答案[::]\s*([A-D])', text):
answers.append({"page_url": url, "answer": block.group(2)})
except Exception:
continue
return answers
def user_id(self) -> str:
return str(self._profile.get("userId") or "")
+1
View File
@@ -46,3 +46,4 @@ class Account(Base):
last_refresh_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
credential_valid: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
month_hours: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default="")
monthly_target: Mapped[int] = mapped_column(nullable=False, default=600, server_default="600")