From ffa563d97c3bab5a2ddc75c1765ae9e97402de36 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 15 Nov 2026 01:01:45 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=87=AA=E5=8A=A8=E5=AD=A6=E4=B9=A0?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=8C=E5=90=8E=E5=8F=B0=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E5=8F=91=E9=80=81=E5=BF=83=E8=B7=B3=E7=A7=AF=E7=B4=AF=E5=AD=A6?= =?UTF-8?q?=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/admin/models.py | 4 + backend/admin/routes.py | 4 + backend/admin/settings.py | 37 ++ backend/alembic/versions/0007_autostudy.py | 29 ++ backend/euniv/api.py | 46 ++- backend/euniv/autostudy.py | 411 +++++++++++++++++++++ backend/euniv/client.py | 226 +++++++++++ backend/euniv/models.py | 1 + backend/tests/test_admin.py | 4 + backend/tests/test_api.py | 1 + web/src/features/admin/SettingsView.vue | 70 +++- web/src/features/home/HomeView.vue | 69 +++- web/src/styles.css | 73 ++++ 13 files changed, 959 insertions(+), 16 deletions(-) create mode 100644 backend/alembic/versions/0007_autostudy.py create mode 100644 backend/euniv/autostudy.py diff --git a/backend/admin/models.py b/backend/admin/models.py index f135a6b..2bd25e9 100644 --- a/backend/admin/models.py +++ b/backend/admin/models.py @@ -18,3 +18,7 @@ class SystemConfig(Base): auto_jigsaw_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=3, server_default="3") admin_username: Mapped[str] = mapped_column(String(64), nullable=False) admin_password_cipher: Mapped[str] = mapped_column(Text, nullable=False) + heartbeat_interval_mode: Mapped[str] = mapped_column(String(16), nullable=False, default="manual", server_default="manual") + heartbeat_video_seconds: Mapped[int] = mapped_column(Integer, nullable=False, default=30, server_default="30") + heartbeat_document_seconds: Mapped[int] = mapped_column(Integer, nullable=False, default=120, server_default="120") + heartbeat_scorm_seconds: Mapped[int] = mapped_column(Integer, nullable=False, default=120, server_default="120") diff --git a/backend/admin/routes.py b/backend/admin/routes.py index 9701179..b5cb841 100644 --- a/backend/admin/routes.py +++ b/backend/admin/routes.py @@ -24,6 +24,10 @@ class SettingsBody(BaseModel): auto_jigsaw_attempts: int admin_username: str admin_password: str | None = None + heartbeat_interval_mode: str = "manual" + heartbeat_video_seconds: int = 30 + heartbeat_document_seconds: int = 120 + heartbeat_scorm_seconds: int = 120 class PauseBody(BaseModel): diff --git a/backend/admin/settings.py b/backend/admin/settings.py index 7c8240f..de5986d 100644 --- a/backend/admin/settings.py +++ b/backend/admin/settings.py @@ -69,6 +69,22 @@ def auto_attempt_count(db: Session) -> int: return int(load_config(db).auto_jigsaw_attempts) +def heartbeat_intervals(db: Session | None = None) -> dict: + """返回 {mode, video, document, scorm}。mode 为 'auto' 时三个值仅作备用。""" + if db is None: + from euniv.db import SessionLocal + with SessionLocal() as owned: + row = load_config(owned) + else: + row = load_config(db) + return { + "mode": row.heartbeat_interval_mode or "manual", + "video": int(row.heartbeat_video_seconds), + "document": int(row.heartbeat_document_seconds), + "scorm": int(row.heartbeat_scorm_seconds), + } + + def settings_view(row: SystemConfig) -> dict: return { "refresh_interval_minutes": int(row.refresh_interval_minutes), @@ -76,6 +92,10 @@ def settings_view(row: SystemConfig) -> dict: "manual_preference": bool(row.manual_preference), "auto_jigsaw_attempts": int(row.auto_jigsaw_attempts), "admin_username": row.admin_username, + "heartbeat_interval_mode": row.heartbeat_interval_mode or "manual", + "heartbeat_video_seconds": int(row.heartbeat_video_seconds), + "heartbeat_document_seconds": int(row.heartbeat_document_seconds), + "heartbeat_scorm_seconds": int(row.heartbeat_scorm_seconds), } @@ -118,6 +138,19 @@ def save_settings(db: Session, payload: dict) -> SystemConfig: if password is not None and password != "" and len(str(password)) > 128: raise SettingsError("管理员密码过长") + hb_mode = str(payload.get("heartbeat_interval_mode") or "manual") + if hb_mode not in ("auto", "manual"): + raise SettingsError("心跳间隔模式须为 auto 或 manual") + hb_video = _as_int(payload.get("heartbeat_video_seconds")) + hb_doc = _as_int(payload.get("heartbeat_document_seconds")) + hb_scorm = _as_int(payload.get("heartbeat_scorm_seconds")) + if hb_video is None or not 10 <= hb_video <= 300: + raise SettingsError("视频心跳间隔须为 10 到 300 的整数") + if hb_doc is None or not 30 <= hb_doc <= 600: + raise SettingsError("文档心跳间隔须为 30 到 600 的整数") + if hb_scorm is None or not 30 <= hb_scorm <= 600: + raise SettingsError("Scorm 心跳间隔须为 30 到 600 的整数") + row = load_config(db) previous_interval = int(row.refresh_interval_minutes) row.refresh_interval_minutes = interval @@ -125,6 +158,10 @@ def save_settings(db: Session, payload: dict) -> SystemConfig: row.manual_preference = bool(payload.get("manual_preference")) row.auto_jigsaw_attempts = attempts row.admin_username = username + row.heartbeat_interval_mode = hb_mode + row.heartbeat_video_seconds = hb_video + row.heartbeat_document_seconds = hb_doc + row.heartbeat_scorm_seconds = hb_scorm if password is not None and password != "": row.admin_password_cipher = encrypt_secret(str(password)) db.commit() diff --git a/backend/alembic/versions/0007_autostudy.py b/backend/alembic/versions/0007_autostudy.py new file mode 100644 index 0000000..c192c88 --- /dev/null +++ b/backend/alembic/versions/0007_autostudy.py @@ -0,0 +1,29 @@ +"""自动学习:用户每月目标、心跳间隔配置。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0007_autostudy" +down_revision = "0006_month_hours" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.add_column(sa.Column("monthly_target", sa.Integer(), nullable=False, server_default="600")) + with op.batch_alter_table("system_config") as batch: + batch.add_column(sa.Column("heartbeat_interval_mode", sa.String(length=16), nullable=False, server_default="manual")) + batch.add_column(sa.Column("heartbeat_video_seconds", sa.Integer(), nullable=False, server_default="30")) + batch.add_column(sa.Column("heartbeat_document_seconds", sa.Integer(), nullable=False, server_default="120")) + batch.add_column(sa.Column("heartbeat_scorm_seconds", sa.Integer(), nullable=False, server_default="120")) + + +def downgrade() -> None: + with op.batch_alter_table("system_config") as batch: + batch.drop_column("heartbeat_scorm_seconds") + batch.drop_column("heartbeat_document_seconds") + batch.drop_column("heartbeat_video_seconds") + batch.drop_column("heartbeat_interval_mode") + with op.batch_alter_table("accounts") as batch: + batch.drop_column("monthly_target") diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 330db51..8f09c00 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -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: diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py new file mode 100644 index 0000000..0b6345b --- /dev/null +++ b/backend/euniv/autostudy.py @@ -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() diff --git a/backend/euniv/client.py b/backend/euniv/client.py index aecfacf..a50dbec 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -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 "") diff --git a/backend/euniv/models.py b/backend/euniv/models.py index a19cfcb..de9f303 100644 --- a/backend/euniv/models.py +++ b/backend/euniv/models.py @@ -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") diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index cce9a58..c7f27af 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -625,6 +625,10 @@ def test_settings_do_not_expose_process_switches() -> None: "manual_preference", "auto_jigsaw_attempts", "admin_username", + "heartbeat_interval_mode", + "heartbeat_video_seconds", + "heartbeat_document_seconds", + "heartbeat_scorm_seconds", } assert identity.password_cipher() assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 0a71da9..98b0d69 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -110,6 +110,7 @@ def test_login_stores_password_and_credential_only() -> None: "last_refresh_at", "credential_valid", "month_hours", + "monthly_target", } home = client.get("/api/home") diff --git a/web/src/features/admin/SettingsView.vue b/web/src/features/admin/SettingsView.vue index 0bcc67c..21a11d7 100644 --- a/web/src/features/admin/SettingsView.vue +++ b/web/src/features/admin/SettingsView.vue @@ -1,6 +1,6 @@ diff --git a/web/src/styles.css b/web/src/styles.css index 1faa7e3..4fd9fea 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -405,6 +405,64 @@ select { color: var(--muted); } +.home-target { + display: flex; + align-items: center; + gap: 12px; + padding-top: 16px; + border-top: 1px solid var(--line); +} + +.home-target label { + flex: none; + font-size: 13px; + color: var(--muted); +} + +.target-control { + display: flex; + align-items: center; + gap: 6px; +} + +.target-control .n-input-number { + width: 120px; +} + +.target-unit { + color: var(--muted); + font-size: 13px; +} + +.home-study-status { + display: flex; + align-items: center; + gap: 8px; + padding-top: 12px; + border-top: 1px solid var(--line); +} + +.study-indicator { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--muted); + flex: none; +} + +.study-indicator.active { + background: #3fb950; + box-shadow: 0 0 6px rgba(63, 185, 80, 0.5); +} + +.study-text { + font-size: 13px; +} + +.study-text.muted { + color: var(--muted); +} + .profile { display: flex; align-items: center; @@ -959,6 +1017,21 @@ select { color: var(--muted); } +.form-section { + margin: 20px 0 8px; + font-size: 13px; + font-weight: 600; + color: var(--muted); + letter-spacing: 0.04em; +} + +.form-hint { + margin: 0; + padding: 2px 0 0 160px; + font-size: 12px; + color: var(--muted); +} + .admin-table { width: 100%; min-width: 820px;