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
+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()