feat: 自动学习功能,后台定时发送心跳积累学时
This commit is contained in:
@@ -18,3 +18,7 @@ class SystemConfig(Base):
|
|||||||
auto_jigsaw_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=3, server_default="3")
|
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_username: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
admin_password_cipher: Mapped[str] = mapped_column(Text, 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")
|
||||||
|
|||||||
@@ -24,6 +24,10 @@ class SettingsBody(BaseModel):
|
|||||||
auto_jigsaw_attempts: int
|
auto_jigsaw_attempts: int
|
||||||
admin_username: str
|
admin_username: str
|
||||||
admin_password: str | None = None
|
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):
|
class PauseBody(BaseModel):
|
||||||
|
|||||||
@@ -69,6 +69,22 @@ def auto_attempt_count(db: Session) -> int:
|
|||||||
return int(load_config(db).auto_jigsaw_attempts)
|
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:
|
def settings_view(row: SystemConfig) -> dict:
|
||||||
return {
|
return {
|
||||||
"refresh_interval_minutes": int(row.refresh_interval_minutes),
|
"refresh_interval_minutes": int(row.refresh_interval_minutes),
|
||||||
@@ -76,6 +92,10 @@ def settings_view(row: SystemConfig) -> dict:
|
|||||||
"manual_preference": bool(row.manual_preference),
|
"manual_preference": bool(row.manual_preference),
|
||||||
"auto_jigsaw_attempts": int(row.auto_jigsaw_attempts),
|
"auto_jigsaw_attempts": int(row.auto_jigsaw_attempts),
|
||||||
"admin_username": row.admin_username,
|
"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:
|
if password is not None and password != "" and len(str(password)) > 128:
|
||||||
raise SettingsError("管理员密码过长")
|
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)
|
row = load_config(db)
|
||||||
previous_interval = int(row.refresh_interval_minutes)
|
previous_interval = int(row.refresh_interval_minutes)
|
||||||
row.refresh_interval_minutes = interval
|
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.manual_preference = bool(payload.get("manual_preference"))
|
||||||
row.auto_jigsaw_attempts = attempts
|
row.auto_jigsaw_attempts = attempts
|
||||||
row.admin_username = username
|
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 != "":
|
if password is not None and password != "":
|
||||||
row.admin_password_cipher = encrypt_secret(str(password))
|
row.admin_password_cipher = encrypt_secret(str(password))
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|||||||
@@ -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")
|
||||||
+42
-4
@@ -31,18 +31,29 @@ from euniv.service import (
|
|||||||
)
|
)
|
||||||
from euniv.session import clear_session, read_employee_id, write_session
|
from euniv.session import clear_session, read_employee_id, write_session
|
||||||
|
|
||||||
|
from pydantic import BaseModel as _BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class MonthlyTargetBody(_BaseModel):
|
||||||
|
monthly_target: int
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(_app: FastAPI):
|
async def lifespan(_app: FastAPI):
|
||||||
init_db()
|
init_db()
|
||||||
ensure_admin_seed()
|
ensure_admin_seed()
|
||||||
load_admin_identity()
|
load_admin_identity()
|
||||||
stop = None
|
stop_refresh = None
|
||||||
|
stop_study = None
|
||||||
if os.environ.get("EUNIV_DISABLE_REFRESH") != "1":
|
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
|
yield
|
||||||
if stop is not None:
|
if stop_study is not None:
|
||||||
stop.set()
|
stop_study.stop()
|
||||||
|
if stop_refresh is not None:
|
||||||
|
stop_refresh.set()
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(title="EunivTools", lifespan=lifespan)
|
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
|
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")
|
@app.get("/api/training")
|
||||||
def training_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
|
def training_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -3,7 +3,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
|
import hashlib
|
||||||
import io
|
import io
|
||||||
|
import json
|
||||||
import random
|
import random
|
||||||
import re
|
import re
|
||||||
import threading
|
import threading
|
||||||
@@ -363,6 +365,14 @@ def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
|
|||||||
return best_x
|
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):
|
class SessionExpired(RuntimeError):
|
||||||
"""学习平台凭证失效,需要重新登录。"""
|
"""学习平台凭证失效,需要重新登录。"""
|
||||||
|
|
||||||
@@ -894,3 +904,219 @@ class EunivClient:
|
|||||||
profile = self.login()
|
profile = self.login()
|
||||||
self.authorize(profile)
|
self.authorize(profile)
|
||||||
return {"profile": self.user_info(), "summary": self.study_snapshot()}
|
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 "")
|
||||||
|
|||||||
@@ -46,3 +46,4 @@ class Account(Base):
|
|||||||
last_refresh_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
last_refresh_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
credential_valid: Mapped[bool | None] = mapped_column(Boolean, 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="")
|
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")
|
||||||
|
|||||||
@@ -625,6 +625,10 @@ def test_settings_do_not_expose_process_switches() -> None:
|
|||||||
"manual_preference",
|
"manual_preference",
|
||||||
"auto_jigsaw_attempts",
|
"auto_jigsaw_attempts",
|
||||||
"admin_username",
|
"admin_username",
|
||||||
|
"heartbeat_interval_mode",
|
||||||
|
"heartbeat_video_seconds",
|
||||||
|
"heartbeat_document_seconds",
|
||||||
|
"heartbeat_scorm_seconds",
|
||||||
}
|
}
|
||||||
assert identity.password_cipher()
|
assert identity.password_cipher()
|
||||||
assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD
|
assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD
|
||||||
|
|||||||
@@ -110,6 +110,7 @@ def test_login_stores_password_and_credential_only() -> None:
|
|||||||
"last_refresh_at",
|
"last_refresh_at",
|
||||||
"credential_valid",
|
"credential_valid",
|
||||||
"month_hours",
|
"month_hours",
|
||||||
|
"monthly_target",
|
||||||
}
|
}
|
||||||
|
|
||||||
home = client.get("/api/home")
|
home = client.get("/api/home")
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from "vue";
|
import { computed, onMounted, ref } from "vue";
|
||||||
import { NAlert, NButton, NInput, NInputNumber, NSwitch } from "naive-ui";
|
import { NAlert, NButton, NInput, NInputNumber, NRadioButton, NRadioGroup, NSwitch } from "naive-ui";
|
||||||
|
|
||||||
const emit = defineEmits<{ saved: [] }>();
|
const emit = defineEmits<{ saved: [] }>();
|
||||||
|
|
||||||
@@ -16,6 +16,10 @@ const attempts = ref<number | null>(null);
|
|||||||
const username = ref("");
|
const username = ref("");
|
||||||
const password = ref("");
|
const password = ref("");
|
||||||
const confirmPassword = ref("");
|
const confirmPassword = ref("");
|
||||||
|
const hbMode = ref("manual");
|
||||||
|
const hbVideo = ref<number | null>(30);
|
||||||
|
const hbDocument = ref<number | null>(120);
|
||||||
|
const hbScorm = ref<number | null>(120);
|
||||||
|
|
||||||
const preferenceLabel = computed(() =>
|
const preferenceLabel = computed(() =>
|
||||||
showManualJigsaw.value ? "默认勾选手动滑动验证码" : "先尝试自动滑动验证码",
|
showManualJigsaw.value ? "默认勾选手动滑动验证码" : "先尝试自动滑动验证码",
|
||||||
@@ -58,6 +62,10 @@ onMounted(async () => {
|
|||||||
showManualJigsaw.value = body.show_manual_jigsaw === true;
|
showManualJigsaw.value = body.show_manual_jigsaw === true;
|
||||||
manualPreference.value = body.manual_preference === true;
|
manualPreference.value = body.manual_preference === true;
|
||||||
username.value = body.admin_username;
|
username.value = body.admin_username;
|
||||||
|
hbMode.value = typeof body.heartbeat_interval_mode === "string" ? body.heartbeat_interval_mode : "manual";
|
||||||
|
hbVideo.value = readNumber(body.heartbeat_video_seconds) ?? 30;
|
||||||
|
hbDocument.value = readNumber(body.heartbeat_document_seconds) ?? 120;
|
||||||
|
hbScorm.value = readNumber(body.heartbeat_scorm_seconds) ?? 120;
|
||||||
loaded.value = true;
|
loaded.value = true;
|
||||||
} catch {
|
} catch {
|
||||||
errorText.value = "系统配置没有获取到。";
|
errorText.value = "系统配置没有获取到。";
|
||||||
@@ -82,24 +90,35 @@ async function save() {
|
|||||||
errorText.value = "自动滑动次数须为 1 到 10 的整数";
|
errorText.value = "自动滑动次数须为 1 到 10 的整数";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (hbMode.value === "manual") {
|
||||||
|
if (invalidInteger(hbVideo.value, 10, 300)) {
|
||||||
|
errorText.value = "视频心跳间隔须为 10 到 300 的整数";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (invalidInteger(hbDocument.value, 30, 600)) {
|
||||||
|
errorText.value = "文档心跳间隔须为 30 到 600 的整数";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (invalidInteger(hbScorm.value, 30, 600)) {
|
||||||
|
errorText.value = "Scorm 心跳间隔须为 30 到 600 的整数";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
const adminUsername = username.value.trim();
|
const adminUsername = username.value.trim();
|
||||||
if (!adminUsername) {
|
if (!adminUsername) {
|
||||||
errorText.value = "请填写管理员用户名";
|
errorText.value = "请填写管理员用户名";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const body: {
|
const body: Record<string, unknown> = {
|
||||||
refresh_interval_minutes: number;
|
|
||||||
show_manual_jigsaw: boolean;
|
|
||||||
manual_preference: boolean;
|
|
||||||
auto_jigsaw_attempts: number;
|
|
||||||
admin_username: string;
|
|
||||||
admin_password?: string;
|
|
||||||
} = {
|
|
||||||
refresh_interval_minutes: refreshInterval.value as number,
|
refresh_interval_minutes: refreshInterval.value as number,
|
||||||
show_manual_jigsaw: showManualJigsaw.value,
|
show_manual_jigsaw: showManualJigsaw.value,
|
||||||
manual_preference: manualPreference.value,
|
manual_preference: manualPreference.value,
|
||||||
auto_jigsaw_attempts: attempts.value as number,
|
auto_jigsaw_attempts: attempts.value as number,
|
||||||
admin_username: adminUsername,
|
admin_username: adminUsername,
|
||||||
|
heartbeat_interval_mode: hbMode.value,
|
||||||
|
heartbeat_video_seconds: hbVideo.value as number,
|
||||||
|
heartbeat_document_seconds: hbDocument.value as number,
|
||||||
|
heartbeat_scorm_seconds: hbScorm.value as number,
|
||||||
};
|
};
|
||||||
if (password.value !== "" || confirmPassword.value !== "") {
|
if (password.value !== "" || confirmPassword.value !== "") {
|
||||||
if (password.value !== confirmPassword.value) {
|
if (password.value !== confirmPassword.value) {
|
||||||
@@ -166,6 +185,39 @@ async function save() {
|
|||||||
<span class="setting-unit">次</span>
|
<span class="setting-unit">次</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<h3 class="form-section">自动学习心跳间隔</h3>
|
||||||
|
<div class="form-row">
|
||||||
|
<label>间隔来源</label>
|
||||||
|
<n-radio-group v-model:value="hbMode" size="small">
|
||||||
|
<n-radio-button value="auto">自动获取</n-radio-button>
|
||||||
|
<n-radio-button value="manual">手动设定</n-radio-button>
|
||||||
|
</n-radio-group>
|
||||||
|
</div>
|
||||||
|
<template v-if="hbMode === 'manual'">
|
||||||
|
<div class="form-row">
|
||||||
|
<label for="hb-video">视频</label>
|
||||||
|
<div class="setting-control">
|
||||||
|
<n-input-number id="hb-video" v-model:value="hbVideo" button-placement="both" :min="10" :max="300" :precision="0" />
|
||||||
|
<span class="setting-unit">秒</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<label for="hb-document">文档</label>
|
||||||
|
<div class="setting-control">
|
||||||
|
<n-input-number id="hb-document" v-model:value="hbDocument" button-placement="both" :min="30" :max="600" :precision="0" />
|
||||||
|
<span class="setting-unit">秒</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<label for="hb-scorm">Scorm</label>
|
||||||
|
<div class="setting-control">
|
||||||
|
<n-input-number id="hb-scorm" v-model:value="hbScorm" button-placement="both" :min="30" :max="600" :precision="0" />
|
||||||
|
<span class="setting-unit">秒</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<p v-else class="form-hint">自动获取:每次自动学习时从课程播放页在线读取间隔</p>
|
||||||
|
<h3 class="form-section">管理员</h3>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<label for="admin-username">管理员用户名</label>
|
<label for="admin-username">管理员用户名</label>
|
||||||
<n-input id="admin-username" v-model:value="username" autocomplete="username" />
|
<n-input id="admin-username" v-model:value="username" autocomplete="username" />
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from "vue";
|
import { computed, onMounted, ref, watch } from "vue";
|
||||||
import { NAlert, NButton, NIcon, NTooltip } from "naive-ui";
|
import { NAlert, NButton, NIcon, NInputNumber, NTooltip } from "naive-ui";
|
||||||
import { RefreshOutline } from "@vicons/ionicons5";
|
import { RefreshOutline } from "@vicons/ionicons5";
|
||||||
|
|
||||||
interface HomeSummary {
|
interface HomeSummary {
|
||||||
@@ -26,6 +26,12 @@ const refreshing = ref(false);
|
|||||||
let refreshRunning = false;
|
let refreshRunning = false;
|
||||||
let busy = false;
|
let busy = false;
|
||||||
|
|
||||||
|
const monthlyTarget = ref<number | null>(null);
|
||||||
|
const targetLoaded = ref(false);
|
||||||
|
let targetSaveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
||||||
|
const studyStatus = ref<{ running: boolean; user: string; course: string; message: string } | null>(null);
|
||||||
|
|
||||||
function amount(value: string | number | null | undefined) {
|
function amount(value: string | number | null | undefined) {
|
||||||
if (value === null || value === undefined || value === "") return "—";
|
if (value === null || value === undefined || value === "") return "—";
|
||||||
const numeric = Number(value);
|
const numeric = Number(value);
|
||||||
@@ -88,7 +94,41 @@ function refresh() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(refresh);
|
async function loadTarget() {
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/settings/monthly-target");
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
monthlyTarget.value = data.monthly_target ?? 600;
|
||||||
|
targetLoaded.value = true;
|
||||||
|
}
|
||||||
|
} catch { /* 静默 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveTarget(value: number | null) {
|
||||||
|
if (value == null || !Number.isInteger(value) || value < 0 || value > 9999) return;
|
||||||
|
clearTimeout(targetSaveTimer);
|
||||||
|
targetSaveTimer = setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await fetch("/api/settings/monthly-target", {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ monthly_target: value }),
|
||||||
|
});
|
||||||
|
} catch { /* 静默 */ }
|
||||||
|
}, 600);
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(monthlyTarget, (v) => { if (targetLoaded.value) saveTarget(v); });
|
||||||
|
|
||||||
|
async function loadStudyStatus() {
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/autostudy/status");
|
||||||
|
if (res.ok) studyStatus.value = await res.json();
|
||||||
|
} catch { /* 静默 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => { refresh(); loadTarget(); loadStudyStatus(); });
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -144,6 +184,29 @@ onMounted(refresh);
|
|||||||
</div>
|
</div>
|
||||||
</dl>
|
</dl>
|
||||||
</div>
|
</div>
|
||||||
|
<div v-if="targetLoaded" class="home-target">
|
||||||
|
<label for="monthly-target">每月自动学习目标</label>
|
||||||
|
<div class="target-control">
|
||||||
|
<n-input-number
|
||||||
|
id="monthly-target"
|
||||||
|
v-model:value="monthlyTarget"
|
||||||
|
button-placement="both"
|
||||||
|
:min="0"
|
||||||
|
:max="9999"
|
||||||
|
:precision="0"
|
||||||
|
size="small"
|
||||||
|
/>
|
||||||
|
<span class="target-unit">分钟</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="studyStatus" class="home-study-status">
|
||||||
|
<span class="study-indicator" :class="{ active: studyStatus.running }"></span>
|
||||||
|
<span v-if="studyStatus.running" class="study-text">
|
||||||
|
正在学习:{{ studyStatus.course || "准备中" }}
|
||||||
|
</span>
|
||||||
|
<span v-else-if="studyStatus.message" class="study-text muted">{{ studyStatus.message }}</span>
|
||||||
|
<span v-else class="study-text muted">自动学习未运行</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -405,6 +405,64 @@ select {
|
|||||||
color: var(--muted);
|
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 {
|
.profile {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -959,6 +1017,21 @@ select {
|
|||||||
color: var(--muted);
|
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 {
|
.admin-table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-width: 820px;
|
min-width: 820px;
|
||||||
|
|||||||
Reference in New Issue
Block a user