feat: 学习进度轮询、学时依据与首页代理弹窗

This commit is contained in:
2026-11-15 05:13:48 +08:00
parent f0a2bdd854
commit 5acbea35fb
17 changed files with 921 additions and 221 deletions
+1
View File
@@ -22,3 +22,4 @@ class SystemConfig(Base):
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")
hours_source: Mapped[str] = mapped_column(String(16), nullable=False, default="api", server_default="api")
+1
View File
@@ -49,6 +49,7 @@ class SettingsBody(BaseModel):
heartbeat_video_seconds: int = 30
heartbeat_document_seconds: int = 120
heartbeat_scorm_seconds: int = 120
hours_source: str = "api"
class PauseBody(BaseModel):
+16
View File
@@ -85,6 +85,17 @@ def heartbeat_intervals(db: Session | None = None) -> dict:
}
def hours_source_of(row: SystemConfig | None = None) -> str:
"""api:接口本月学时;history:学时历史本月分钟合计。"""
if row is None:
from euniv.db import SessionLocal
with SessionLocal() as owned:
return hours_source_of(load_config(owned))
value = str(row.hours_source or "api").strip().lower()
return value if value in ("api", "history") else "api"
def settings_view(row: SystemConfig) -> dict:
return {
"refresh_interval_minutes": int(row.refresh_interval_minutes),
@@ -96,6 +107,7 @@ def settings_view(row: SystemConfig) -> dict:
"heartbeat_video_seconds": int(row.heartbeat_video_seconds),
"heartbeat_document_seconds": int(row.heartbeat_document_seconds),
"heartbeat_scorm_seconds": int(row.heartbeat_scorm_seconds),
"hours_source": hours_source_of(row),
}
@@ -150,6 +162,9 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
raise SettingsError("文档心跳间隔须为 30 到 600 的整数")
if hb_scorm is None or not 30 <= hb_scorm <= 600:
raise SettingsError("Scorm 心跳间隔须为 30 到 600 的整数")
source = str(payload.get("hours_source") or "api").strip().lower()
if source not in ("api", "history"):
raise SettingsError("学时达标依据须为 api 或 history")
row = load_config(db)
previous_interval = int(row.refresh_interval_minutes)
@@ -162,6 +177,7 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
row.heartbeat_video_seconds = hb_video
row.heartbeat_document_seconds = hb_doc
row.heartbeat_scorm_seconds = hb_scorm
row.hours_source = source
if password is not None and password != "":
row.admin_password_cipher = encrypt_secret(str(password))
db.commit()
@@ -0,0 +1,21 @@
"""学时达标判断依据:接口本月学时或学时历史统计。"""
from alembic import op
import sqlalchemy as sa
revision = "0013_hours_source"
down_revision = "0012_study_control"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("system_config") as batch:
batch.add_column(
sa.Column("hours_source", sa.String(length=16), nullable=False, server_default="api")
)
def downgrade() -> None:
with op.batch_alter_table("system_config") as batch:
batch.drop_column("hours_source")
+3
View File
@@ -354,6 +354,9 @@ def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
live = (autostudy_status().get("users") or {}).get(employee_id) or {}
payload["state"] = str(live.get("state") or "")
payload["course"] = str(live.get("course") or "")
payload["message"] = str(live.get("message") or "")
workers = live.get("workers") or []
payload["workers"] = workers if isinstance(workers, list) else []
payload["active"] = bool(live) and payload["state"] not in {"已达标", "已停止", "会话失效", "会话过期"}
if payload["active"]:
payload["started"] = True
+230 -48
View File
@@ -19,6 +19,7 @@ import logging
import random
import re
import threading
import time
from datetime import datetime, timezone
import httpx
@@ -42,9 +43,32 @@ _user_halts: dict[str, asyncio.Event] = {}
_worker = None
def _workers_list(info: dict) -> list[dict]:
workers = info.get("workers") or {}
if isinstance(workers, list):
return [dict(item) for item in workers if isinstance(item, dict)]
if not isinstance(workers, dict):
return []
rows = []
for key in sorted(workers, key=lambda value: int(value) if str(value).isdigit() else 0):
item = workers[key]
if not isinstance(item, dict):
continue
row = dict(item)
row.setdefault("id", int(key) if str(key).isdigit() else key)
rows.append(row)
return rows
def autostudy_status() -> dict:
with _lock:
return dict(_status)
raw = {key: value for key, value in _status.items() if key != "users"}
users_in = dict(_status.get("users") or {})
copied = {eid: dict(info) for eid, info in users_in.items()}
for info in copied.values():
info["workers"] = _workers_list(info)
raw["users"] = copied
return raw
def _set_status(**kw: object) -> None:
@@ -66,6 +90,46 @@ def _clear_user_status(employee_id: str) -> None:
_status.get("users", {}).pop(employee_id, None)
def _set_worker_status(employee_id: str, worker_id: int, **kw: object) -> None:
with _lock:
users = _status.setdefault("users", {})
info = users.setdefault(employee_id, {})
workers = info.setdefault("workers", {})
if not isinstance(workers, dict):
workers = {}
info["workers"] = workers
row = workers.setdefault(str(worker_id), {"id": worker_id})
row.update(kw)
course = kw.get("course")
if isinstance(course, str) and course:
info["course"] = course
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
class WorkerView:
def __init__(self, employee_id: str, worker_id: int) -> None:
self.employee_id = employee_id
self.worker_id = worker_id
def update(self, **kw: object) -> None:
_set_worker_status(self.employee_id, self.worker_id, **kw)
def _touch(worker: WorkerView | None, **kw: object) -> None:
if worker is not None:
worker.update(**kw)
def _progress_of(payload: dict) -> float:
raw = payload.get("studyschedule")
if raw is None:
raw = payload.get("studySchedule")
try:
return max(0.0, min(100.0, float(raw or 0)))
except (TypeError, ValueError):
return 0.0
def request_stop(employee_id: str) -> None:
key = (employee_id or "").strip()
if not key:
@@ -160,12 +224,14 @@ class HoursWatcher:
target: int,
user_stop: asyncio.Event,
interval: float = _HOURS_REFRESH_SECONDS,
source: str = "api",
) -> None:
self.session = session
self.employee_id = employee_id
self.target = target
self.user_stop = user_stop
self.interval = interval
self.source = source if source in ("api", "history") else "api"
self._lock = asyncio.Lock()
self.reached = False
@@ -174,8 +240,12 @@ class HoursWatcher:
if self.reached or self.user_stop.is_set():
return True
try:
text = await self.session.month_hours_text()
current = _parse_minutes(text)
if self.source == "history":
current = int(await self.session.month_history_minutes())
text = str(current)
else:
text = await self.session.month_hours_text()
current = _parse_minutes(text)
if text:
await asyncio.to_thread(_update_month_hours, self.employee_id, text)
if current >= self.target:
@@ -456,6 +526,51 @@ class StudySession:
m = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', resp.text)
return m.group(1) if m else ""
async def month_history_minutes(self, now: datetime | None = None) -> int:
from euniv.client import (
HISTORY_PAGE_SIZE,
fold_month_minutes,
history_items_from_payload,
history_search_body,
)
from euniv.study_window import CN_TZ
current = now or datetime.now(CN_TZ)
year, month = current.year, current.month
offset = 0
total = 0
first_mark: tuple | None = None
for _ in range(50):
resp = await self._api(
"POST",
f"{STUDY_API}/v1/styhis/studyhistory/daily/search",
json=history_search_body(True, offset, HISTORY_PAGE_SIZE),
)
rows = history_items_from_payload(resp.json())
if rows is None:
if offset == 0:
raise RuntimeError("学时历史没有获取到")
return total
if not rows:
return total
add, done = fold_month_minutes(rows, year, month)
total += add
if done or len(rows) != HISTORY_PAGE_SIZE:
return total
mark = (
len(rows),
rows[0].get("studied_at"),
rows[0].get("title"),
rows[-1].get("studied_at"),
rows[-1].get("title"),
)
if offset == 0:
first_mark = mark
elif mark == first_mark:
return total
offset += HISTORY_PAGE_SIZE
return total
# ── 单门课程的学习协程 ──
@@ -480,13 +595,31 @@ class CourseCursor:
return item
async def _heartbeat_wait(
worker: WorkerView | None,
interval: int,
stop: asyncio.Event,
hours: HoursWatcher,
progress: float,
) -> bool:
delay = _jitter(interval)
_touch(worker, interval=interval, heartbeat_at=time.time() + delay, progress=progress, ok=True)
return await wait_stop(delay, stop, hours.user_stop)
async def _study_video(session: StudySession, kid: str, pkg_id: str,
interval: int, stop: asyncio.Event, hours: HoursWatcher) -> None:
interval: int, stop: asyncio.Event, hours: HoursWatcher,
worker: WorkerView | None = None) -> None:
view = 0
started = False
while not _halted(stop, hours):
progress = await session.update_progress(kid, pkg_id)
schedule = float(progress.get("studyschedule", 0))
try:
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_touch(worker, progress=schedule, ok=True)
if schedule >= 100:
if started:
await hours.refresh()
@@ -494,29 +627,48 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
started = True
view = int(progress.get("viewSchedule", view))
view += interval
result = await session.submit_video_heartbeat(kid, pkg_id, interval, view)
try:
result = await session.submit_video_heartbeat(kid, pkg_id, interval, view)
except Exception:
_touch(worker, ok=False)
raise
new_schedule = result.get("studySchedule")
if new_schedule is not None and float(new_schedule) >= 100:
await hours.refresh()
if new_schedule is not None:
schedule = _progress_of({"studySchedule": new_schedule})
_touch(worker, progress=schedule, ok=True)
if schedule >= 100:
await hours.refresh()
return
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
return
await wait_stop(_jitter(interval), stop, hours.user_stop)
async def _study_document(session: StudySession, kid: str, pkg_id: str,
page_size: int, interval: int, stop: asyncio.Event,
hours: HoursWatcher) -> None:
hours: HoursWatcher, worker: WorkerView | None = None) -> None:
view = 1
while not _halted(stop, hours):
progress = await session.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100:
try:
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_touch(worker, progress=schedule, ok=True)
if schedule >= 100:
return
try:
await session.submit_document_heartbeat(kid, pkg_id, page_size, interval, view)
except Exception:
_touch(worker, ok=False)
raise
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
return
await session.submit_document_heartbeat(kid, pkg_id, page_size, interval, view)
await wait_stop(_jitter(interval), stop, hours.user_stop)
async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
interval: int, stop: asyncio.Event, hours: HoursWatcher,
user_id: str, org_id: str) -> None:
user_id: str, org_id: str, worker: WorkerView | None = None) -> None:
import uuid as _uuid
sco_cnt = await session.scorm_count(kid)
session_id = str(_uuid.uuid4())
@@ -545,28 +697,46 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
return
scorm_data["cmi__core__lesson_location"] = str(page_idx + 1)
scorm_data["cmi__core__session_time"] = "00:00:01"
await session.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,
pkg_id=pkg_id, data=scorm_data,
)
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True)
progress = await session.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100:
try:
await session.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,
pkg_id=pkg_id, data=scorm_data,
)
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=True)
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_touch(worker, progress=schedule, ok=True)
if schedule >= 100:
return
if await _heartbeat_wait(worker, min(interval, 5), stop, hours, schedule):
return
await wait_stop(_jitter(min(interval, 5)), stop, hours.user_stop)
while not _halted(stop, hours):
progress = await session.update_progress(kid, pkg_id)
if float(progress.get("studyschedule", 0)) >= 100:
try:
progress = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_touch(worker, progress=schedule, ok=True)
if schedule >= 100:
return
try:
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False)
except Exception:
_touch(worker, ok=False)
raise
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
return
await session.submit_scorm_heartbeat(kid, pkg_id, interval, sco_id=sco_id, end=False)
await wait_stop(_jitter(interval), stop, hours.user_stop)
async def _study_package(session: StudySession, kid: str, intervals: dict,
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
user_id: str, org_id: str) -> None:
user_id: str, org_id: str, worker: WorkerView | None = None) -> None:
pkg = await session.sync_package(kid)
chapters = pkg.get("userKnowledgeList") or []
for ch in chapters:
@@ -579,6 +749,7 @@ async def _study_package(session: StudySession, kid: str, intervals: dict,
if not ch_kid:
continue
_set_user_status(session._employee_id, course=ch_title)
_touch(worker, course=ch_title, progress=_progress_of(ch), ok=True)
is_video = "Video" in str(ch.get("knowledgeType") or "")
ch_type = "video" if is_video else "document"
@@ -595,9 +766,9 @@ async def _study_package(session: StudySession, kid: str, intervals: dict,
pass
if is_video:
await _study_video(session, ch_kid, kid, ch_interval, stop, hours)
await _study_video(session, ch_kid, kid, ch_interval, stop, hours, worker)
else:
await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, hours)
await _study_document(session, ch_kid, kid, page_size, ch_interval, stop, hours, worker)
# ── 同步准备:用 EunivClient 建立会话,导出 cookies ──
@@ -693,11 +864,12 @@ class AutoStudyWorker:
async def _run_cycle(self) -> None:
assert self._async_stop is not None
from admin.settings import heartbeat_intervals
from admin.settings import heartbeat_intervals, hours_source_of
from euniv.crypto import decrypt_secret
from euniv.db import SessionLocal
intervals_cfg = heartbeat_intervals()
hours_source = hours_source_of()
auto_mode = intervals_cfg["mode"] == "auto"
intervals = {
"video": intervals_cfg["video"],
@@ -724,9 +896,10 @@ class AutoStudyWorker:
else:
waiting += 1
continue
target = row.monthly_target or 600
target = int(row.monthly_target) if row.monthly_target is not None else 600
current = _parse_minutes(row.month_hours)
if target > 0 and current < target:
below = hours_source == "history" or (target > 0 and current < target)
if below:
try:
password = decrypt_secret(row.password_cipher)
credential = json.loads(decrypt_secret(row.credential_cipher))
@@ -764,7 +937,7 @@ class AutoStudyWorker:
tasks = [
self._study_user(
emp_id, target, pw, cred, proxy, workers, use_pool,
course_list, intervals, auto_mode, sem,
course_list, intervals, auto_mode, hours_source, sem,
)
for emp_id, target, pw, cred, proxy, workers, use_pool in eligible
]
@@ -779,7 +952,7 @@ class AutoStudyWorker:
async def _study_user(self, employee_id: str, target: int,
password: str, credential: dict, proxy: str | None,
workers: int, use_pool: bool, course_list: list, intervals: dict,
auto_mode: bool, sem: asyncio.Semaphore) -> None:
auto_mode: bool, hours_source: str, sem: asyncio.Semaphore) -> None:
assert self._async_stop is not None
user_stop = asyncio.Event()
with _halt_lock:
@@ -792,7 +965,7 @@ class AutoStudyWorker:
if user_stop.is_set():
_set_user_status(employee_id, state="已停止")
return
_set_user_status(employee_id, state="准备", course="")
_set_user_status(employee_id, state="准备", course="", workers={})
loop = asyncio.get_event_loop()
token, user_id, org_id, cookies, proxy = await loop.run_in_executor(
None, _prepare_session, employee_id, password, credential, proxy, use_pool)
@@ -805,7 +978,7 @@ class AutoStudyWorker:
) as session:
session._employee_id = employee_id # type: ignore[attr-defined]
_set_user_status(employee_id, state="学习中")
hours = HoursWatcher(session, employee_id, target, user_stop)
hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source)
if await hours.refresh():
return
ticker = asyncio.create_task(hours.ticker(self._async_stop))
@@ -835,22 +1008,26 @@ class AutoStudyWorker:
cursor = CourseCursor(course_list)
count = max(1, min(8, int(workers or 1)))
async def worker() -> None:
async def worker_loop(index: int) -> None:
view = WorkerView(employee_id, index)
view.update(course="", progress=0, interval=0, heartbeat_at=0, ok=True)
while not _halted(self._async_stop, hours):
item = await cursor.take()
if item is None:
view.update(course="", progress=100, interval=0, heartbeat_at=0, ok=True)
return
path, title, kind = item
await self._study_one_course(
session, employee_id, path, title, kind,
intervals, auto_mode, hours, user_id, org_id)
intervals, auto_mode, hours, user_id, org_id, view)
await asyncio.gather(*(worker() for _ in range(count)))
await asyncio.gather(*(worker_loop(index) for index in range(1, count + 1)))
async def _study_one_course(self, session: StudySession, employee_id: str,
path: str, title: str, kind: str,
intervals: dict, auto_mode: bool,
hours: HoursWatcher, user_id: str, org_id: str) -> None:
hours: HoursWatcher, user_id: str, org_id: str,
worker: WorkerView | None = None) -> None:
assert self._async_stop is not None
if _halted(self._async_stop, hours):
return
@@ -862,14 +1039,17 @@ class AutoStudyWorker:
return
_set_user_status(employee_id, course=title)
_touch(worker, course=title, progress=0, ok=True)
try:
if ctype == "package":
await _study_package(session, kid, intervals, auto_mode,
self._async_stop, hours, user_id, org_id)
self._async_stop, hours, user_id, org_id, worker)
else:
progress = await session.update_progress(kid, "")
if float(progress.get("studyschedule", 0)) >= 100:
schedule = _progress_of(progress)
_touch(worker, progress=schedule, ok=True)
if schedule >= 100:
return
interval = intervals.get(ctype, 120)
@@ -886,17 +1066,19 @@ class AutoStudyWorker:
pass
if ctype == "video":
await _study_video(session, kid, "", interval, self._async_stop, hours)
await _study_video(session, kid, "", interval, self._async_stop, hours, worker)
elif ctype == "document":
await _study_document(session, kid, "", page_size, interval, self._async_stop, hours)
await _study_document(session, kid, "", page_size, interval, self._async_stop, hours, worker)
elif ctype == "scorm":
await _study_scorm(session, kid, "", interval, self._async_stop, hours,
user_id, org_id)
user_id, org_id, worker)
except SessionExpired:
hours.user_stop.set()
_touch(worker, ok=False)
_set_user_status(employee_id, state="会话过期")
log.info("用户 %s 会话过期", employee_id)
except Exception as exc:
_touch(worker, ok=False)
log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
+134 -17
View File
@@ -155,6 +155,117 @@ def _history_api_item(row: object) -> dict | None:
}
HISTORY_PAGE_SIZE = 100
def history_search_body(pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE) -> dict:
body: dict = {"pageable": pageable}
if pageable:
page = offset // limit + 1 if limit else 1
body.update(
{
"offset": offset,
"limit": limit,
"page": page,
"pageSize": limit,
"start": offset,
"length": limit,
}
)
return body
def history_items_from_payload(payload: object) -> list[dict] | None:
if not isinstance(payload, dict):
return None
rows = payload.get("datas")
if rows is None:
rows = payload.get("data")
if isinstance(rows, dict):
rows = rows.get("datas") or rows.get("list") or rows.get("records") or rows.get("items")
if not isinstance(rows, list):
return None
items = []
for row in rows:
item = _history_api_item(row)
if item is not None:
items.append(item)
return items
def history_stamp(studied_at: str) -> datetime | None:
text = (studied_at or "").strip().replace("T", " ")
if not text:
return None
text = text[:19]
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
try:
return datetime.strptime(text, fmt)
except ValueError:
continue
return None
def history_month_side(studied_at: str, year: int, month: int) -> str:
stamp = history_stamp(studied_at)
if stamp is None:
return "unknown"
if (stamp.year, stamp.month) == (year, month):
return "in"
if (stamp.year, stamp.month) < (year, month):
return "before"
return "after"
def fold_month_minutes(items: list[dict], year: int, month: int) -> tuple[int, bool]:
total = 0
reached_before = False
for item in items:
side = history_month_side(str(item.get("studied_at") or ""), year, month)
if side == "in":
minutes = item.get("minutes")
if isinstance(minutes, int):
total += minutes
elif side == "before":
reached_before = True
break
return total, reached_before
def accumulate_month_minutes(fetch_page, year: int, month: int, page_size: int = HISTORY_PAGE_SIZE) -> int:
"""倒序分页累加本月分钟,遇到上个月即停。"""
offset = 0
total = 0
first_mark: tuple | None = None
for _ in range(50):
rows = fetch_page(offset, page_size)
if rows is None:
if offset == 0:
raise RuntimeError("学时历史没有获取到")
return total
if not rows:
return total
add, done = fold_month_minutes(rows, year, month)
total += add
if done:
return total
if len(rows) != page_size:
return total
mark = (
len(rows),
rows[0].get("studied_at"),
rows[0].get("title"),
rows[-1].get("studied_at"),
rows[-1].get("title"),
)
if offset == 0:
first_mark = mark
elif mark == first_mark:
return total
offset += page_size
return total
def parse_training_cards(page: str, status: str) -> list[dict]:
items = []
for block in re.findall(r"<li class='el-plan-li-3'[\s\S]*?</li>", page):
@@ -798,33 +909,39 @@ class EunivClient:
def study_history(self) -> list[dict]:
"""读取「我的学时」列表:来源、获得学时(分钟)、日期。"""
try:
items = self._study_history_api()
items = self._study_history_search(pageable=False)
except Exception:
items = None
if items is not None:
return items
return self._study_history_page()
def _study_history_api(self) -> list[dict] | None:
def month_history_minutes(self, now: datetime | None = None) -> int:
"""倒序分页统计本月学时分钟,遇到上个月即停。"""
from euniv.study_window import CN_TZ
current = now or datetime.now(CN_TZ)
year, month = current.year, current.month
def fetch_page(offset: int, limit: int) -> list[dict] | None:
return self._study_history_search(pageable=True, offset=offset, limit=limit)
try:
return accumulate_month_minutes(fetch_page, year, month)
except Exception:
items = self.study_history()
total, _ = fold_month_minutes(items, year, month)
return total
def _study_history_search(
self, *, pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE
) -> list[dict] | None:
response = self._request(
"POST",
f"{STUDY_API}/v1/styhis/studyhistory/daily/search",
json={"pageable": False},
json=history_search_body(pageable, offset, limit),
)
payload = response.json()
if not isinstance(payload, dict):
return None
rows = payload.get("datas")
if rows is None:
rows = payload.get("data")
if not isinstance(rows, list):
return None
items = []
for row in rows:
item = _history_api_item(row)
if item is not None:
items.append(item)
return items
return history_items_from_payload(response.json())
def _study_history_page(self) -> list[dict]:
text = self._study_period_page()
+15
View File
@@ -642,7 +642,9 @@ def test_settings_do_not_expose_process_switches() -> None:
"heartbeat_video_seconds",
"heartbeat_document_seconds",
"heartbeat_scorm_seconds",
"hours_source",
}
assert body["hours_source"] == "api"
assert identity.password_cipher()
assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD
@@ -852,3 +854,16 @@ def test_admin_can_save_study_settings_in_one_request() -> None:
assert one["study_start"] == "每月8日 09:10:11"
assert one["course_workers"] == 2
assert one["proxy"] == "HTTP 10.0.0.8:8080"
def test_admin_can_switch_hours_source() -> None:
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/settings", json=_settings_body(hours_source="history"))
assert saved.status_code == 200
assert saved.json()["hours_source"] == "history"
assert client.get("/api/admin/settings").json()["hours_source"] == "history"
bad = client.put("/api/admin/settings", json=_settings_body(hours_source="other"))
assert bad.status_code == 400
assert bad.json()["detail"] == "学时达标依据须为 api 或 history"
+2
View File
@@ -562,11 +562,13 @@ def test_user_can_start_and_stop_study_immediately() -> None:
client.put("/api/settings/study-start", json={"day": 31, "hour": 23, "minute": 59, "second": 59})
idle = client.get("/api/settings/study-control")
assert idle.status_code == 200
assert idle.json()["workers"] == []
started = client.post("/api/settings/study-control", json={"action": "start"})
assert started.status_code == 200
assert started.json()["started"] is True
assert started.json()["ignore_window"] is True
assert started.json()["paused"] is False
assert started.json()["workers"] == []
stopped = client.post("/api/settings/study-control", json={"action": "stop"})
assert stopped.status_code == 200
assert stopped.json()["started"] is False
+76 -1
View File
@@ -4,7 +4,18 @@ import pytest
from datetime import datetime
from euniv.autostudy import CourseCursor, HoursWatcher, _parse_minutes, _study_video, wait_stop
from euniv.autostudy import (
CourseCursor,
HoursWatcher,
_clear_user_status,
_parse_minutes,
_set_user_status,
_set_worker_status,
_study_video,
autostudy_status,
wait_stop,
)
from euniv.client import accumulate_month_minutes, fold_month_minutes
from euniv.course_workers import CourseWorkersError, of as workers_of, validate as validate_workers
from euniv.proxy import ProxyError, apply as apply_proxy, build_proxy_url, parse_proxy, view_of as proxy_view
from euniv.study_control import eligible as study_eligible, start_now, stop_now
@@ -81,6 +92,70 @@ def test_hours_watcher_stops_when_target_reached(monkeypatch) -> None:
asyncio.run(main())
def test_hours_watcher_history_source_uses_month_history(monkeypatch) -> None:
saved: list[tuple[str, str]] = []
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda eid, hours: saved.append((eid, hours)))
class _HistorySession:
async def month_history_minutes(self) -> int:
return 600
async def month_hours_text(self) -> str:
raise AssertionError("history 模式不应读接口本月学时")
async def main() -> None:
user_stop = asyncio.Event()
watcher = HoursWatcher(_HistorySession(), "u1", 600, user_stop, source="history")
assert await watcher.refresh() is True
assert watcher.reached
assert saved == [("u1", "600")]
asyncio.run(main())
def test_accumulate_month_minutes_stops_at_previous_month() -> None:
pages = [
[
{"title": "a", "minutes": 10, "studied_at": "2026-11-15 09:00:00"},
{"title": "b", "minutes": 20, "studied_at": "2026-11-02 09:00:00"},
],
[
{"title": "c", "minutes": 5, "studied_at": "2026-11-01 09:00:00"},
{"title": "d", "minutes": 99, "studied_at": "2026-10-31 23:00:00"},
{"title": "e", "minutes": 1, "studied_at": "2026-10-01 00:00:00"},
],
[
{"title": "should-not", "minutes": 1000, "studied_at": "2026-09-01 00:00:00"},
],
]
calls: list[tuple[int, int]] = []
def fetch(offset: int, limit: int):
calls.append((offset, limit))
return pages[offset // limit]
assert accumulate_month_minutes(fetch, 2026, 11, page_size=2) == 35
assert calls == [(0, 2), (2, 2)]
dumped = [
{"title": "a", "minutes": 8, "studied_at": "2026-11-14 10:00:00"},
{"title": "b", "minutes": 4, "studied_at": "2026-10-30 10:00:00"},
]
assert fold_month_minutes(dumped, 2026, 11) == (8, True)
assert accumulate_month_minutes(lambda _offset, _limit: dumped, 2026, 11, page_size=100) == 8
def test_autostudy_status_lists_workers_in_id_order() -> None:
_clear_user_status("u1")
_set_user_status("u1", state="学习中")
_set_worker_status("u1", 2, course="乙", progress=80, ok=True)
_set_worker_status("u1", 1, course="甲", progress=10, ok=False)
users = autostudy_status()["users"]["u1"]
assert [row["id"] for row in users["workers"]] == [1, 2]
assert users["workers"][0]["ok"] is False
assert users["course"] == "甲"
_clear_user_status("u1")
def test_hours_watcher_continues_below_target(monkeypatch) -> None:
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)