feat: 每月定时开始学习并改为本地计算心跳摘要
This commit is contained in:
@@ -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
@@ -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
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user