feat: 每月定时开始学习并改为本地计算心跳摘要

This commit is contained in:
2026-11-15 01:30:24 +08:00
parent e9a1e9b315
commit caa79d79b7
14 changed files with 510 additions and 35 deletions
+22
View File
@@ -17,8 +17,10 @@ from admin.users import (
list_users,
read_credentials,
read_proxy,
read_study_start,
set_paused,
set_proxy,
set_study_start,
)
from euniv.courses import course_page, request_course_sync_now
from euniv.db import get_db
@@ -57,6 +59,14 @@ class AdminProxyClearBody(BaseModel):
employee_ids: list[str]
class AdminStudyStartBody(BaseModel):
employee_ids: list[str]
day: int
hour: int
minute: int
second: int
def require_admin(request: Request) -> str:
if not admin_session_active(request.cookies):
raise HTTPException(status_code=401, detail="未登录")
@@ -164,6 +174,18 @@ def get_user_proxy(employee_id: str, db: Session = Depends(get_db), _: str = Dep
return read_proxy(db, employee_id)
@admin_router.put("/users/study-start")
def put_users_study_start(
body: AdminStudyStartBody, db: Session = Depends(get_db), _: str = Depends(require_admin)
) -> dict:
return set_study_start(db, body.employee_ids, body.day, body.hour, body.minute, body.second)
@admin_router.get("/users/{employee_id}/study-start")
def get_user_study_start(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
return read_study_start(db, employee_id)
@admin_router.get("/users/{employee_id}/credentials")
def get_credentials(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
return read_credentials(db, employee_id)
+32
View File
@@ -12,6 +12,10 @@ from sqlalchemy.orm import Session
from euniv.crypto import decrypt_secret
from euniv.models import Account
from euniv.proxy import ProxyError, apply, clear, summary_of, url_of, view_of
from euniv.study_window import StudyWindowError
from euniv.study_window import apply as apply_start
from euniv.study_window import label_of as start_label
from euniv.study_window import view_of as start_view
_TOKEN_KEYS = (
"ucs_token",
@@ -67,6 +71,11 @@ def list_users(db: Session) -> list[dict]:
"month_hours": account.month_hours or "",
"has_proxy": bool(account.proxy_scheme and account.proxy_host and account.proxy_port),
"proxy": summary_of(account),
"study_start": start_label(account),
"study_start_day": int(account.study_start_day or 1),
"study_start_hour": int(account.study_start_hour or 0),
"study_start_minute": int(account.study_start_minute or 0),
"study_start_second": int(account.study_start_second or 0),
}
for account in accounts
]
@@ -217,6 +226,29 @@ def clear_proxy(db: Session, employee_ids: list[str]) -> dict:
return {"ok": True, "count": len(accounts)}
def read_study_start(db: Session, employee_id: str) -> dict:
return start_view(_require(db, employee_id))
def set_study_start(
db: Session,
employee_ids: list[str],
day: int,
hour: int,
minute: int,
second: int,
) -> dict:
accounts = _accounts_by_ids(db, employee_ids)
try:
for account in accounts:
apply_start(account, day, hour, minute, second)
except StudyWindowError as exc:
db.rollback()
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return {"ok": True, "count": len(accounts)}
def delete_user(db: Session, employee_id: str) -> dict:
account = _require(db, employee_id)
db.delete(account)
@@ -0,0 +1,25 @@
"""账号每月自动学习开始时刻。"""
from alembic import op
import sqlalchemy as sa
revision = "0009_study_start"
down_revision = "0008_proxy"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.add_column(sa.Column("study_start_day", sa.Integer(), nullable=False, server_default="1"))
batch.add_column(sa.Column("study_start_hour", sa.Integer(), nullable=False, server_default="0"))
batch.add_column(sa.Column("study_start_minute", sa.Integer(), nullable=False, server_default="0"))
batch.add_column(sa.Column("study_start_second", sa.Integer(), nullable=False, server_default="0"))
def downgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.drop_column("study_start_second")
batch.drop_column("study_start_minute")
batch.drop_column("study_start_hour")
batch.drop_column("study_start_day")
+32
View File
@@ -46,6 +46,13 @@ class ProxyBody(_BaseModel):
password: str | None = None
class StudyStartBody(_BaseModel):
day: int
hour: int
minute: int
second: int
@asynccontextmanager
async def lifespan(_app: FastAPI):
init_db()
@@ -225,6 +232,31 @@ def put_monthly_target(body: MonthlyTargetBody, request: Request, db: Session =
return {"monthly_target": account.monthly_target}
@app.get("/api/settings/study-start")
def get_study_start(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.study_window import view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
return view_of(account)
@app.put("/api/settings/study-start")
def put_study_start(body: StudyStartBody, request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.study_window import StudyWindowError, apply, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
try:
apply(account, body.day, body.hour, body.minute, body.second)
except StudyWindowError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return view_of(account)
@app.get("/api/settings/proxy")
def get_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.proxy import view_of
+12 -17
View File
@@ -14,7 +14,6 @@ from __future__ import annotations
import asyncio
import contextlib
import hashlib
import json
import logging
import random
@@ -25,12 +24,12 @@ from datetime import datetime, timezone
import httpx
from sqlalchemy import select
from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired
from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired, study_encryption
from euniv.models import Account, Course
from euniv.study_window import window_open
log = logging.getLogger(__name__)
_SCORM_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696"
_MAX_CONCURRENT_USERS = 8
_MAX_COURSE_PER_USER = 1
_HOURS_REFRESH_SECONDS = 300.0
@@ -102,7 +101,7 @@ def _jitter(seconds: int) -> float:
def _scorm_md5(body_json: str) -> str:
return hashlib.md5((body_json + _SCORM_MD5_KEY).encode("utf-8")).hexdigest()
return study_encryption(body_json)
def _parse_minutes(value: str) -> int:
@@ -247,18 +246,7 @@ class StudySession:
return resp.json()
async def get_encrypt_request(self, body_json: str) -> str:
assert self._client is not None
resp = await self._client.post(
f"{EUNIV}/kng/services/KngComService.svc/GetEncryptRequest",
json={"body": body_json},
headers={"Content-Type": "text/json", "User-Agent": USER_AGENT},
)
data = resp.json()
if isinstance(data, str):
data = json.loads(data)
if data.get("Status") == "OK":
return str(data["Data"])
raise RuntimeError(f"GetEncryptRequest 失败: {data}")
return study_encryption(body_json)
async def submit_video_heartbeat(self, kid: str, pkg_id: str,
study_time: int, view_schedule: int) -> dict:
@@ -611,7 +599,11 @@ class AutoStudyWorker:
courses = db.scalars(select(Course).order_by(Course.title)).all()
course_list = [(c.path, c.title, c.kind) for c in courses]
eligible = []
waiting = 0
for row in users:
if not window_open(row):
waiting += 1
continue
target = row.monthly_target or 600
current = _parse_minutes(row.month_hours)
if target > 0 and current < target:
@@ -628,7 +620,10 @@ class AutoStudyWorker:
return
if not eligible:
_set_status(running=False, message="所有用户已达标或无有效凭据")
if waiting:
_set_status(running=False, message="未到开始时间或已达标")
else:
_set_status(running=False, message="所有用户已达标或无有效凭据")
return
_set_status(running=True, message=f"本轮 {len(eligible)} 个用户")
+6 -17
View File
@@ -365,12 +365,12 @@ def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
return best_x
_SCORM_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696"
STUDY_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()
def study_encryption(body_json: str) -> str:
"""播放页 RteApiSite.js 的摘要:MD5(进度 JSON + 固定 key),与 GetEncryptRequest 相同。"""
return hashlib.md5((body_json + STUDY_MD5_KEY).encode("utf-8")).hexdigest()
class SessionExpired(RuntimeError):
@@ -954,18 +954,7 @@ class EunivClient:
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}")
return study_encryption(body_json)
def submit_video_heartbeat(self, knowledge_id: str, package_id: str,
study_time: int, view_schedule: int,
@@ -1050,7 +1039,7 @@ class EunivClient:
"viewSchedule": 0,
}
if end:
encryption = _scorm_md5(json.dumps(param, separators=(",", ":")))
encryption = study_encryption(json.dumps(param, separators=(",", ":")))
else:
encrypt_body = json.dumps(param, separators=(",", ":"))
encryption = self.get_encrypt_request(encrypt_body)
+4
View File
@@ -52,3 +52,7 @@ class Account(Base):
proxy_port: Mapped[int | None] = mapped_column(nullable=True)
proxy_username: Mapped[str] = mapped_column(String(128), nullable=False, default="", server_default="")
proxy_password_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="", server_default="")
study_start_day: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1")
study_start_hour: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
study_start_minute: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
study_start_second: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
+80
View File
@@ -0,0 +1,80 @@
"""每月自动学习开始时刻。精确到秒,按北京时间判断当月是否已到点。"""
from __future__ import annotations
import calendar
from datetime import datetime, timedelta, timezone
CN_TZ = timezone(timedelta(hours=8))
class StudyWindowError(ValueError):
"""开始时刻不符合要求。"""
def validate_start(day: object, hour: object, minute: object, second: object) -> tuple[int, int, int, int]:
for name, value, low, high in (
("日", day, 1, 31),
("时", hour, 0, 23),
("分", minute, 0, 59),
("秒", second, 0, 59),
):
if not isinstance(value, int) or isinstance(value, bool) or not low <= value <= high:
raise StudyWindowError(f"每月开始{name}须为 {low} 到 {high} 的整数")
return int(day), int(hour), int(minute), int(second)
def apply(account, day: object, hour: object, minute: object, second: object) -> None:
d, h, m, s = validate_start(day, hour, minute, second)
account.study_start_day = d
account.study_start_hour = h
account.study_start_minute = m
account.study_start_second = s
def label_of(account) -> str:
day = int(getattr(account, "study_start_day", 1) or 1)
hour = int(getattr(account, "study_start_hour", 0) or 0)
minute = int(getattr(account, "study_start_minute", 0) or 0)
second = int(getattr(account, "study_start_second", 0) or 0)
return f"每月{day}日 {hour:02d}:{minute:02d}:{second:02d}"
def view_of(account) -> dict:
day = int(getattr(account, "study_start_day", 1) or 1)
hour = int(getattr(account, "study_start_hour", 0) or 0)
minute = int(getattr(account, "study_start_minute", 0) or 0)
second = int(getattr(account, "study_start_second", 0) or 0)
return {
"day": day,
"hour": hour,
"minute": minute,
"second": second,
"label": label_of(account),
}
def window_open(account, now: datetime | None = None) -> bool:
"""当前是否已过该账号本月开始时刻。2 月 31 日等按当月最后一天。"""
current = now or datetime.now(CN_TZ)
if current.tzinfo is None:
current = current.replace(tzinfo=CN_TZ)
else:
current = current.astimezone(CN_TZ)
day, hour, minute, second = validate_start(
int(getattr(account, "study_start_day", 1) or 1),
int(getattr(account, "study_start_hour", 0) or 0),
int(getattr(account, "study_start_minute", 0) or 0),
int(getattr(account, "study_start_second", 0) or 0),
)
last = calendar.monthrange(current.year, current.month)[1]
start = datetime(
current.year,
current.month,
min(day, last),
hour,
minute,
second,
tzinfo=CN_TZ,
)
return current >= start
+36
View File
@@ -447,6 +447,11 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
"month_hours",
"has_proxy",
"proxy",
"study_start",
"study_start_day",
"study_start_hour",
"study_start_minute",
"study_start_second",
}
assert saved["has_credential"] is True
assert saved["refresh_paused"] is False
@@ -690,3 +695,34 @@ def test_admin_can_set_and_clear_proxy_for_selected_users() -> None:
detail = client.get("/api/admin/users/p1-user/proxy")
assert detail.json()["has_password"] is False
assert detail.json()["username"] == ""
def test_admin_can_set_study_start_for_selected_users() -> None:
_add_account("s1-user")
_add_account("s2-user")
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
saved = client.put(
"/api/admin/users/study-start",
json={"employee_ids": ["s1-user", "s2-user"], "day": 5, "hour": 16, "minute": 8, "second": 9},
)
assert saved.status_code == 200
assert saved.json()["count"] == 2
listed = client.get("/api/admin/users").json()
one = next(item for item in listed if item["employee_id"] == "s1-user")
two = next(item for item in listed if item["employee_id"] == "s2-user")
assert one["study_start"] == "每月5日 16:08:09"
assert two["study_start"] == "每月5日 16:08:09"
one_only = client.put(
"/api/admin/users/study-start",
json={"employee_ids": ["s1-user"], "day": 20, "hour": 0, "minute": 0, "second": 0},
)
assert one_only.status_code == 200
listed = client.get("/api/admin/users").json()
one = next(item for item in listed if item["employee_id"] == "s1-user")
two = next(item for item in listed if item["employee_id"] == "s2-user")
assert one["study_start"] == "每月20日 00:00:00"
assert two["study_start"] == "每月5日 16:08:09"
detail = client.get("/api/admin/users/s1-user/study-start")
assert detail.json()["day"] == 20
+23
View File
@@ -117,6 +117,10 @@ def test_login_stores_password_and_credential_only() -> None:
"proxy_port",
"proxy_username",
"proxy_password_cipher",
"study_start_day",
"study_start_hour",
"study_start_minute",
"study_start_second",
}
home = client.get("/api/home")
@@ -488,6 +492,25 @@ def test_user_can_set_proxy_with_or_without_password() -> None:
assert cleared.json()["enabled"] is False
def test_user_can_set_monthly_study_start() -> None:
import euniv.api as api_module
import euniv.service as service_module
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
)
client = TestClient(api_module.app)
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
empty = client.get("/api/settings/study-start")
assert empty.status_code == 200
assert empty.json() == {"day": 1, "hour": 0, "minute": 0, "second": 0, "label": "每月1日 00:00:00"}
saved = client.put("/api/settings/study-start", json={"day": 5, "hour": 16, "minute": 0, "second": 7})
assert saved.status_code == 200
assert saved.json()["label"] == "每月5日 16:00:07"
bad = client.put("/api/settings/study-start", json={"day": 32, "hour": 16, "minute": 0, "second": 0})
assert bad.status_code == 400
def test_exam_list_rejects_unrecognized_page() -> None:
from euniv.client import EunivClient
+58
View File
@@ -2,8 +2,12 @@ import asyncio
import pytest
from datetime import datetime
from euniv.autostudy import HoursWatcher, _parse_minutes, _study_video, wait_stop
from euniv.client import study_encryption
from euniv.proxy import ProxyError, build_proxy_url, parse_proxy
from euniv.study_window import CN_TZ, StudyWindowError, validate_start, window_open
def test_parse_proxy_accepts_http_and_socks() -> None:
@@ -160,3 +164,57 @@ def test_video_skip_already_complete_does_not_refresh() -> None:
assert not watcher.reached
asyncio.run(main())
def test_study_encryption_matches_get_encrypt_request() -> None:
import json
body = json.dumps(
{
"knowledgeId": "6d16a38ebdfe455fbb1e86ec0c0c35d7",
"masterId": "",
"masterType": "",
"packageId": "",
"pageSize": 1,
"studySize": 1,
"studyTime": 120,
"type": 1,
"offLine": False,
"end": False,
"care": True,
"deviceId": "",
"studyChapterIds": "",
"viewSchedule": 1,
},
separators=(",", ":"),
)
assert study_encryption(body) == "ba119ee448648d9f8f046d11c426afa4"
class _Start:
def __init__(self, day: int, hour: int = 16, minute: int = 0, second: int = 0) -> None:
self.study_start_day = day
self.study_start_hour = hour
self.study_start_minute = minute
self.study_start_second = second
def test_study_window_opens_after_configured_time() -> None:
account = _Start(5, 16, 0, 0)
assert window_open(account, datetime(2026, 11, 5, 15, 59, 59, tzinfo=CN_TZ)) is False
assert window_open(account, datetime(2026, 11, 5, 16, 0, 0, tzinfo=CN_TZ)) is True
assert window_open(account, datetime(2026, 11, 15, 1, 24, 0, tzinfo=CN_TZ)) is True
assert window_open(account, datetime(2026, 12, 5, 15, 0, 0, tzinfo=CN_TZ)) is False
def test_study_window_clamps_missing_day() -> None:
account = _Start(31, 16, 0, 0)
assert window_open(account, datetime(2026, 2, 28, 15, 59, 59, tzinfo=CN_TZ)) is False
assert window_open(account, datetime(2026, 2, 28, 16, 0, 0, tzinfo=CN_TZ)) is True
def test_study_window_rejects_invalid_parts() -> None:
with pytest.raises(StudyWindowError):
validate_start(32, 0, 0, 0)
with pytest.raises(StudyWindowError):
validate_start(1, 24, 0, 0)