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
+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()