fix: 学习任务跨月会停,失败的课不再记成已学完

This commit is contained in:
2026-11-16 09:19:30 +08:00
parent 91b06cde25
commit 337d842543
6 changed files with 348 additions and 133 deletions
+2 -2
View File
@@ -409,8 +409,6 @@ def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
raise HTTPException(status_code=401, detail="未登录")
status = autostudy_status()
live = dict((status.get("users") or {}).get(employee_id) or {})
if not live.get("message"):
live["message"] = str(status.get("message") or "")
if settle(account, live):
db.commit()
return assemble(account, live)
@@ -428,6 +426,8 @@ def post_study_control(body: StudyControlBody, request: Request, db: Session = D
raise HTTPException(status_code=401, detail="未登录")
action = (body.action or "").strip().lower()
if action == "start":
if int(account.monthly_target or 0) <= 0:
raise HTTPException(status_code=400, detail="每月目标为 0,不会学习")
if hours_met(account):
from euniv.autostudy import halt_work
+323 -126
View File
@@ -13,7 +13,6 @@
from __future__ import annotations
import asyncio
import contextlib
import json
import logging
import math
@@ -61,7 +60,9 @@ _running: set[str] = set()
_retry_at: dict[str, float] = {}
_retry_count: dict[str, int] = {}
_done_month: dict[str, str] = {}
_targets: dict[str, int] = {}
_RETRY_STEPS = (5 * 60, 15 * 60, 60 * 60)
_HOUR_FAIL_LIMIT = 5
_worker = None
@@ -110,10 +111,13 @@ def _set_status(**kw: object) -> None:
def _set_user_status(employee_id: str, **kw: object) -> None:
from euniv.study_window import month_key
with _lock:
users = _status.setdefault("users", {})
info = users.setdefault(employee_id, {})
info.update(kw)
info["month"] = str(kw["month"]) if "month" in kw else month_key()
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
_notify(employee_id)
@@ -124,16 +128,26 @@ def _clear_user_status(employee_id: str) -> None:
_notify(employee_id)
def _drop_live_hours(employee_id: str) -> None:
with _lock:
info = (_status.get("users") or {}).get(employee_id)
if isinstance(info, dict):
info.pop("month_hours", None)
def _finish_user(employee_id: str, error: BaseException | None = None) -> None:
"""周期结束时保留失败/达标,避免首页只剩「等待执行」。"""
if error is not None:
_set_user_status(employee_id, state="学习失败", message=str(error)[:200], workers={}, course="")
log.warning("用户 %s 学习没有完成: %s", employee_id, error)
_set_user_status(employee_id, state="学习失败", message="学习没有完成", workers={}, course="")
_drop_live_hours(employee_id)
return
with _lock:
info = (_status.get("users") or {}).get(employee_id) or {}
state = str(info.get("state") or "")
if state in _KEEP_LIVE:
_set_user_status(employee_id, workers={}, course="")
_drop_live_hours(employee_id)
return
_clear_user_status(employee_id)
@@ -166,16 +180,24 @@ class WorkerView:
def update(self, **kw: object) -> None:
course = kw.get("course")
if isinstance(course, str) and course != self._course:
self._course = course
marker = kw.get("knowledge_id")
if not isinstance(marker, str) or not marker:
marker = course if isinstance(course, str) else ""
if isinstance(marker, str) and marker and marker != self._course:
self._course = marker
self.sent = 0
self.total = 0
self._origin = 0.0
try:
self._origin = float(kw.get("progress") or 0)
except (TypeError, ValueError):
self._origin = 0.0
kw = dict(kw)
kw.setdefault("sent", 0)
kw.setdefault("total", 0)
kw["interval"] = 0
kw["heartbeat_at"] = 0
kw["heartbeat_in"] = 0
_set_worker_status(self.employee_id, self.worker_id, **kw)
def after_beat(self, progress: float, **kw: object) -> None:
@@ -251,7 +273,7 @@ def _interval_plan(ctype: str, intervals: dict, auto_mode: bool, params: dict) -
wait = int(intervals.get(ctype, 30 if video else 120) or 0)
fallback = int((params or {}).get("submitProTimes" if video else "validtimeSpan") or (30 if video else 120))
if auto_mode:
wait = fallback
wait = max(1, fallback)
page_size = max(1, int((params or {}).get("pageSize") or 1))
return wait, _payload_time(wait, fallback), page_size
@@ -388,6 +410,8 @@ def sync_work(employee_id: str) -> None:
return
if expire_pause(account):
db.commit()
raw_target = getattr(account, "monthly_target", None)
_targets[key] = int(raw_target) if raw_target is not None else 600
met = hours_met(account)
due = study_eligible(account)
if met:
@@ -420,6 +444,14 @@ def snapshot_courses(rows) -> list[tuple[str, str, str]]:
return items
def _release_pool(employee_id: str, pool: bool) -> None:
if not pool or not employee_id:
return
from euniv.proxy_pool import release
release(employee_id)
def _job_from_account(row) -> tuple | None:
"""从账号列表行提取一次凭据。之后 work 只用这份拷贝,不再读账号表。"""
from euniv.crypto import decrypt_secret
@@ -430,28 +462,33 @@ def _job_from_account(row) -> tuple | None:
credential_cipher = str(getattr(row, "credential_cipher", "") or "")
workers = course_workers_of(row)
pool = uses_pool(row)
target = int(target_raw) if target_raw is not None else 600
if target <= 0:
return None
try:
proxy = bind_url(row)
if pool and not proxy and employee_id:
_set_user_status(employee_id, message="正在直连")
except Exception as exc:
log.warning("用户 %s 凭据无法读取: %s", employee_id, exc)
_release_pool(employee_id, pool)
if employee_id:
_set_user_status(employee_id, state="学习失败", message="凭据无法读取")
return None
target = int(target_raw) if target_raw is not None else 600
if target <= 0:
return None
try:
password = decrypt_secret(password_cipher)
credential = json.loads(decrypt_secret(credential_cipher))
except Exception as exc:
log.warning("用户 %s 凭据无法读取: %s", employee_id, exc)
_release_pool(employee_id, pool)
if employee_id:
_set_user_status(employee_id, state="学习失败", message="凭据无法读取")
return None
if not isinstance(credential, dict):
_release_pool(employee_id, pool)
return None
if employee_id:
_targets[employee_id] = target
return (
employee_id,
target,
@@ -486,7 +523,7 @@ def _course_type(kind: str, path: str) -> str:
return "scorm"
if kind == "视频" or "/video/" in path:
return "video"
if kind in ("文档", "") or "/document/" in path:
if kind == "文档" or "/document/" in path:
return "document"
return "unknown"
@@ -514,6 +551,8 @@ async def _open_play(session: "StudySession", path: str) -> dict:
return {}
try:
return await session.course_page_params(path)
except SessionExpired:
raise
except Exception:
log.debug("打开播放页失败 %s", path, exc_info=True)
return {}
@@ -584,11 +623,25 @@ class HoursWatcher:
self.source = source if source in ("api", "history") else "api"
self._lock = asyncio.Lock()
self.reached = False
from euniv.study_window import month_key
self.month = month_key()
self.month_rolled = False
self._misses = 0
def current_target(self) -> int:
return int(_targets.get(self.employee_id, self.target))
async def refresh(self) -> bool:
from euniv.study_window import month_key
async with self._lock:
if self.reached or self.user_stop.is_set():
return True
if month_key() != self.month:
self.month_rolled = True
self.user_stop.set()
return True
try:
if self.source == "history":
current = int(await self.session.month_history_minutes())
@@ -596,16 +649,24 @@ class HoursWatcher:
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 self.target > 0 and current >= self.target:
if not text:
raise RuntimeError("学时没有解析到")
self._misses = 0
await asyncio.to_thread(_update_month_hours, self.employee_id, text)
target = self.current_target()
if target > 0 and current >= target:
self.reached = True
self.user_stop.set()
_set_user_status(self.employee_id, state="已达标")
await asyncio.to_thread(_release_ignore_window, self.employee_id)
return True
except Exception:
self._misses += 1
log.warning("用户 %s 刷新本月学时失败", self.employee_id, exc_info=True)
if self._misses >= _HOUR_FAIL_LIMIT:
self.user_stop.set()
_set_user_status(self.employee_id, state="学习失败", message="学时没有获取到")
return True
return False
async def ticker(self, global_stop: asyncio.Event) -> None:
@@ -756,6 +817,16 @@ class StudySession:
raise PermissionError("当前课程没有权限")
return resp
async def _guard_single(self, kid: str) -> None:
if not getattr(self, "_single_limit", False) or not kid:
return
try:
await self._api("POST", f"{EUNIV}/kng/knowledges/{as_uuid(kid)}/heart")
except (SessionExpired, PermissionError):
raise
except Exception:
log.info("多端检查没有发出")
async def update_progress(self, kid: str, pkg_id: str = "") -> dict:
resp = await self._api("POST", f"{STUDY_API}/v1/study/updateprogress",
json={"knowledgeId": as_uuid(kid),
@@ -805,6 +876,7 @@ class StudySession:
async def submit_video_heartbeat(self, kid: str, pkg_id: str,
study_time: int, view_schedule: int) -> dict:
await self._guard_single(kid)
param = study_progress_fields(
kid, pkg_id, page_size=1, study_time=study_time,
kind=0, view_schedule=view_schedule,
@@ -827,10 +899,11 @@ class StudySession:
async def submit_document_heartbeat(self, kid: str, pkg_id: str,
page_size: int, study_time: int,
view_schedule: int) -> None:
view_schedule: int, end: bool = False) -> None:
await self._guard_single(kid)
param = study_progress_fields(
kid, pkg_id, page_size=page_size, study_time=study_time,
kind=1, view_schedule=view_schedule,
kind=1, view_schedule=view_schedule, end=end,
)
plain = json.dumps(param, ensure_ascii=False, separators=(",", ":"))
encryption = await self.get_encrypt_request(plain)
@@ -848,6 +921,7 @@ class StudySession:
async def submit_scorm_heartbeat(self, kid: str, pkg_id: str,
study_time: int, sco_id: str = "",
end: bool = False) -> None:
await self._guard_single(kid)
encrypt_param = study_progress_fields(
kid, pkg_id, page_size=-1 if end else 1, study_time=study_time,
kind=2, view_schedule=0, end=end, chapter_id=sco_id, for_encrypt=True,
@@ -898,10 +972,24 @@ class StudySession:
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
)
html = resp.text
if _page_is_login(html):
raise SessionExpired("学习平台登录已失效")
from euniv.encrypt import note_play_html
note_play_html(html, EUNIV)
return play_page_params(html)
async def scorm_page_count(self, kid: str) -> int:
"""只数课件页文件,不下载正文。失败时返回 0,调用方改为只发学时心跳。"""
assert self._client is not None
compact = compact_id(kid)
index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/index-scorm.js"
try:
resp = await self._http("GET", index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"})
except Exception:
log.warning("课件页列表没有获取到")
return 0
return len(re.findall(r'["\']([^"\']+\.oss\.js)["\']', resp.text))
async def scorm_extract_answers(self, kid: str) -> list[dict]:
assert self._client is not None
compact = compact_id(kid)
@@ -1015,10 +1103,43 @@ async def _heartbeat_wait(
progress: float,
) -> bool:
delay = _jitter(interval)
_touch(worker, interval=interval, heartbeat_at=time.time() + delay, progress=progress, ok=True)
cap = max(int(interval or 0), 1)
remaining = max(0, min(int(math.ceil(delay)), cap))
_touch(
worker,
interval=interval,
heartbeat_at=time.time() + delay,
heartbeat_in=remaining,
progress=progress,
ok=True,
)
return await wait_stop(delay, stop, hours.user_stop)
def _page_is_login(html: str) -> bool:
text = html or ""
if "submitProTimes" in text or "knowledgeType" in text or "spMonthlyPeriod" in text:
return False
lowered = text.lower()
return "password" in lowered and ("login" in lowered or "登录" in text)
def _whole(value: object, default: int = 0) -> int:
try:
return int(float(value))
except (TypeError, ValueError):
return default
def _uses_new_timer(params: dict | None) -> bool:
data = params or {}
def on(name: str) -> bool:
return str(data.get(name) or "").strip() == "1"
return on("submitIsOpen") or on("learningProgressSubmission")
async def _study_video(session: StudySession, kid: str, pkg_id: str,
interval: int, stop: asyncio.Event, hours: HoursWatcher,
worker: WorkerView | None = None,
@@ -1052,8 +1173,11 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
await hours.refresh()
return
started = True
view = int(progress.get("viewSchedule") or view)
view += step
view = _whole(progress.get("viewSchedule"), view)
view = max(0, view + step + random.randint(-1, 1))
limit = int(getattr(session, "_video_cap", 0) or 0)
if limit > 0:
view = min(view, limit)
page_rhythm = interval > 0 and interval == step
if page_rhythm and await _heartbeat_wait(worker, interval, stop, hours, schedule):
return
@@ -1127,7 +1251,7 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
interval: int, stop: asyncio.Event, hours: HoursWatcher,
user_id: str, org_id: str, worker: WorkerView | None = None,
study_time: int | None = None) -> None:
study_time: int | None = None, scorm_id: str = "") -> None:
import uuid as _uuid
step = int(study_time if study_time is not None else (interval if interval > 0 else 120))
if step <= 0:
@@ -1142,27 +1266,36 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
if _completed(progress):
return
if not user_id or not org_id:
async def hours_only() -> None:
while not _halted(stop, hours):
if _halted(stop, hours):
return
try:
await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id="", end=False)
progress = await session.update_progress(kid, pkg_id)
latest = await session.update_progress(kid, pkg_id)
except Exception:
_touch(worker, ok=False)
raise
schedule = _progress_of(progress)
_beat(worker, schedule, ok=True)
if _completed(progress):
current = _progress_of(latest)
_beat(worker, current, ok=True)
if _completed(latest):
await hours.refresh()
return
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
if await _heartbeat_wait(worker, interval, stop, hours, current):
return
page_count = 0
if user_id and org_id and scorm_id:
counter = getattr(session, "scorm_page_count", None)
if counter is not None:
page_count = int(await counter(kid) or 0)
if page_count <= 0 or not user_id or not org_id or not scorm_id:
await hours_only()
return
sco_cnt = await session.scorm_count(kid)
session_id = str(_uuid.uuid4())
sco_id = kid
sco_id = scorm_id
existing = await session.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):
@@ -1174,15 +1307,15 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
"cmi__core__exit": "suspend",
"cmi__suspend_data": {},
}
total_pages = max(1, int(sco_cnt or 1))
total_pages = max(1, page_count)
prior_done = str(scorm_data.get("cmi__core__lesson_status") or "") == "completed"
for page_idx in range(total_pages):
if _halted(stop, hours):
return
scorm_data["cmi__core__lesson_location"] = str(page_idx + 1)
scorm_data["cmi__core__lesson_progress"] = f"{(page_idx + 1) / total_pages:.2f}"
scorm_data["cmi__core__lesson_status"] = "completed" if page_idx + 1 == total_pages else "incomplete"
scorm_data["cmi__core__lesson_status"] = "completed" if prior_done and page_idx + 1 == total_pages else "incomplete"
scorm_data["cmi__core__session_time"] = "00:00:01"
try:
await session.scorm_save(
@@ -1205,15 +1338,7 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
return
while not _halted(stop, hours):
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 _completed(progress):
await hours.refresh()
if _halted(stop, hours):
return
try:
await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id=sco_id, end=False)
@@ -1232,35 +1357,43 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
async def _study_package(session: StudySession, kid: str, intervals: dict,
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
user_id: str, org_id: str, worker: WorkerView | None = None) -> None:
user_id: str, org_id: str, worker: WorkerView | None = None) -> bool:
pkg = await session.sync_package(kid)
if _completed(pkg):
_touch(worker, progress=_progress_of(pkg), ok=True)
return
return True
chapters = pkg.get("userKnowledgeList") or []
failed = 0
for ch in chapters:
if _halted(stop, hours):
return
return failed == 0
if _completed(ch):
continue
ch_kid = str(ch.get("knowledgeId") or "").strip()
ch_title = ch.get("title") or ch_kid
if not compact_id(ch_kid):
log.info("跳过没有编号的章节 %s", ch_title)
continue
_set_user_status(session._employee_id, course=ch_title)
_touch(worker, course=ch_title, progress=_progress_of(ch), ok=True)
_touch(worker, course=ch_title, knowledge_id=ch_kid, progress=_progress_of(ch), ok=True)
is_video = "Video" in str(ch.get("knowledgeType") or "")
ch_type = "video" if is_video else "document"
params = await _open_play(session, _package_chapter_path(kid, ch_kid, ch_type))
wait, study_time, page_size = _interval_plan(ch_type, intervals, auto_mode, params)
if is_video:
await _study_video(session, ch_kid, kid, wait, stop, hours, worker, study_time=study_time)
else:
await _study_document(
session, ch_kid, kid, page_size, wait, stop, hours, worker, study_time=study_time,
)
try:
params = await _open_play(session, _package_chapter_path(kid, ch_kid, ch_type))
wait, study_time, page_size = _interval_plan(ch_type, intervals, auto_mode, params)
if is_video:
await _study_video(session, ch_kid, kid, wait, stop, hours, worker, study_time=study_time)
else:
await _study_document(
session, ch_kid, kid, page_size, wait, stop, hours, worker, study_time=study_time,
)
except SessionExpired:
raise
except Exception:
failed += 1
log.warning("章节 %s 没有学完", ch_title, exc_info=True)
continue
return failed == 0
# ── 同步准备:用 EunivClient 建立会话,导出 cookies ──
@@ -1268,18 +1401,18 @@ async def _study_package(session: StudySession, kid: str, intervals: dict,
def _prepare_session(employee_id: str, password: str,
credential: dict, proxy: str | None = None,
use_pool: bool = False
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None]:
"""同步:恢复会话并导出 cookies。返回 (token, user_id, org_id, cookies, proxy)。"""
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
"""同步:恢复会话并导出 cookies。最后一项是 expired 或 network。"""
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
current = proxy
last_exc: BaseException | None = None
last_reason = "network"
for _ in range(MAX_SWITCHES + 1):
client = EunivClient(employee_id, password, proxy=current)
try:
client.restore(credential)
if not client.credential_alive():
return "", "", "", [], current
return "", "", "", [], current, "expired"
client._ensure_site()
token = client.session_token()
user_id = str(client._profile.get("userId") or "")
@@ -1287,20 +1420,21 @@ def _prepare_session(employee_id: str, password: str,
cookies: list[tuple[str, str, str, str]] = []
for cookie in client.client.cookies.jar:
cookies.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/"))
return token, user_id, org_id, cookies, current
return token, user_id, org_id, cookies, current, ""
except SessionExpired:
return "", "", "", [], current, "expired"
except Exception as exc:
last_exc = exc
log.warning("用户 %s 准备会话失败: %s", employee_id, exc)
if use_pool and current and is_proxy_failure(exc):
mark_failed(employee_id, current, str(exc)[:200])
current = acquire(employee_id)
last_reason = "network"
continue
return "", "", "", [], current
last_reason = "expired" if isinstance(exc, SessionExpired) else "network"
return "", "", "", [], current, last_reason
finally:
client.close()
if last_exc is not None:
log.warning("用户 %s 准备会话失败: %s", employee_id, last_exc)
return "", "", "", [], current
return "", "", "", [], current, last_reason
# ── 启动器 + 按账号 Work ──
@@ -1325,6 +1459,9 @@ class AutoStudyWorker:
self._stop_flag.set()
if self._loop and self._async_stop:
self._loop.call_soon_threadsafe(self._async_stop.set)
thread = self._thread
if thread is not None and thread is not threading.current_thread():
thread.join(timeout=15)
def wake(self) -> None:
if self._loop and self._kick is not None:
@@ -1347,16 +1484,30 @@ class AutoStudyWorker:
while not self._async_stop.is_set():
self._kick.clear()
try:
delay = self._tick()
jobs, course_list, delay, idle = await asyncio.to_thread(self._collect)
except Exception as exc:
log.exception("自动学习调度异常: %s", exc)
_set_status(message=f"异常: {exc}")
delay = 30.0
_set_status(message="调度出现异常")
jobs, course_list, delay, idle = [], [], 30.0, ""
if self._async_stop.is_set():
return
break
for job in jobs:
self._launch(job, course_list)
alive = self._alive()
if alive:
_set_status(running=True, message=f"运行中 {alive} 个账号")
elif idle:
_set_status(running=False, message=idle)
if self._kick.is_set():
continue
await wait_stop(delay, self._async_stop, self._kick)
pending = [task for task in self._tasks.values() if not task.done()]
if pending:
_done, leftover = await asyncio.wait(pending, timeout=10)
for task in leftover:
task.cancel()
if leftover:
await asyncio.gather(*leftover, return_exceptions=True)
def _alive(self) -> int:
dead = [eid for eid, task in self._tasks.items() if task.done()]
@@ -1370,7 +1521,7 @@ class AutoStudyWorker:
return True
return is_studying(employee_id)
def _tick(self) -> float:
def _collect(self) -> tuple[list, list, float, str]:
from euniv.db import SessionLocal
from euniv.study_window import CN_TZ, month_key
@@ -1387,54 +1538,57 @@ class AutoStudyWorker:
).all()
expired = False
for row in users:
if expire_pause(row):
expired = True
eid = row.employee_id
fire = next_fire_at(row, now)
if fire is not None and fire < soonest:
soonest = fire
if hours_met(row):
if is_studying(eid) or is_wanted(eid):
halt_work(eid)
continue
retry_hold = _retry_at.get(eid)
if retry_hold and time.time() < retry_hold and not is_wanted(eid):
retry_at = datetime.fromtimestamp(retry_hold, CN_TZ)
if retry_at < soonest:
soonest = retry_at
continue
if retry_hold and time.time() >= retry_hold:
want_work(eid)
_retry_at.pop(eid, None)
if _done_month.get(eid) == month_key(now) and not is_wanted(eid):
continue
if not (study_eligible(row) or is_wanted(eid)):
continue
if self._busy(eid):
continue
job = _job_from_account(row)
if job is None:
drop_work(eid)
continue
jobs.append(job)
try:
if expire_pause(row):
expired = True
eid = row.employee_id
fire = next_fire_at(row, now)
if fire is not None and fire < soonest:
soonest = fire
if hours_met(row):
if is_studying(eid) or is_wanted(eid):
halt_work(eid)
continue
retry_hold = _retry_at.get(eid)
if retry_hold and time.time() < retry_hold and not is_wanted(eid):
retry_at = datetime.fromtimestamp(retry_hold, CN_TZ)
if retry_at < soonest:
soonest = retry_at
continue
if retry_hold and time.time() >= retry_hold:
want_work(eid)
_retry_at.pop(eid, None)
if _done_month.get(eid) == month_key(now) and not is_wanted(eid):
continue
if not (study_eligible(row) or is_wanted(eid)):
continue
if self._busy(eid):
continue
job = _job_from_account(row)
if job is None:
drop_work(eid)
continue
jobs.append(job)
except Exception:
log.exception("调度账号 %s 失败", getattr(row, "employee_id", ""))
if jobs:
course_list = snapshot_courses(db.scalars(select(Course)).all())
if expired:
db.commit()
launched = 0
wait = max(1.0, min(3600.0, (soonest - as_cn()).total_seconds()))
label = soonest.strftime("%m-%d %H:%M:%S")
return jobs, course_list, wait, f"下一次定时 {label}"
def _tick(self) -> float:
jobs, course_list, delay, idle = self._collect()
for job in jobs:
if self._launch(job, course_list):
launched += 1
self._launch(job, course_list)
alive = self._alive()
wait = max(1.0, (soonest - as_cn()).total_seconds())
if alive:
_set_status(running=True, message=f"运行中 {alive} 个账号")
elif launched:
_set_status(running=True, message=f"正在启动 {launched} 个账号")
else:
label = soonest.strftime("%m-%d %H:%M:%S")
_set_status(running=False, message=f"下一次定时 {label}")
return min(wait, 3600.0)
_set_status(running=False, message=idle)
return delay
def _launch(self, job: tuple, course_list: list[tuple[str, str, str]]) -> bool:
eid = job[0]
@@ -1458,8 +1612,8 @@ class AutoStudyWorker:
try:
from admin.settings import hours_source_of
hours_source = hours_source_of()
intervals, auto_mode = _current_intervals()
hours_source = await asyncio.to_thread(hours_source_of)
intervals, auto_mode = await asyncio.to_thread(_current_intervals)
if not course_list:
_set_user_status(emp_id, state="学习失败", message="没有可用的课程")
return
@@ -1482,6 +1636,8 @@ class AutoStudyWorker:
self._kick.set()
note_attempt_end(emp_id)
self._tasks.pop(emp_id, None)
if self._kick is not None:
self._kick.set()
async def _study_user(self, employee_id: str, target: int,
password: str, credential: dict, proxy: str | None,
@@ -1500,11 +1656,15 @@ class AutoStudyWorker:
_set_user_status(employee_id, state="已停止")
return
_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(
loop = asyncio.get_running_loop()
token, user_id, org_id, cookies, proxy, reason = await loop.run_in_executor(
None, _prepare_session, employee_id, password, credential, proxy, use_pool)
if user_stop.is_set():
_set_user_status(employee_id, state="已停止")
return
if not token:
_set_user_status(employee_id, state="会话失效", message="无法连接学习平台")
message = "请重新登录" if reason == "expired" else "无法连接学习平台"
_set_user_status(employee_id, state="会话失效", message=message)
return
async with StudySession(
@@ -1512,24 +1672,33 @@ class AutoStudyWorker:
) as session:
session._employee_id = employee_id # type: ignore[attr-defined]
session._request_limit = sem
if user_stop.is_set():
_set_user_status(employee_id, state="已停止")
return
_set_user_status(employee_id, state="学习中")
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))
try:
await self._study_courses(
failed = await self._study_courses(
session, employee_id, course_list, intervals,
auto_mode, hours, user_id, org_id, workers)
if hours.reached:
if hours.reached or user_stop.is_set() or self._async_stop.is_set():
return
if user_stop.is_set() or self._async_stop.is_set():
if failed:
_set_user_status(
employee_id,
state="学习失败",
message=f"{failed} 门课程没有学完",
course="",
workers={},
)
return
_set_user_status(employee_id, state="已学完", course="", workers={})
finally:
ticker.cancel()
with contextlib.suppress(asyncio.CancelledError):
await ticker
await asyncio.gather(ticker, return_exceptions=True)
finally:
with _halt_lock:
if _user_halts.get(employee_id) is user_stop:
@@ -1538,18 +1707,19 @@ class AutoStudyWorker:
if use_pool:
from euniv.proxy_pool import release
release(employee_id)
await asyncio.to_thread(release, employee_id)
async def _study_courses(self, session: StudySession, employee_id: str,
course_list: list, intervals: dict,
auto_mode: bool, hours: HoursWatcher,
user_id: str, org_id: str, workers: int) -> None:
user_id: str, org_id: str, workers: int) -> int:
"""N 个协程顺着课程表往下领,已完成的跳过,未完成的发心跳。"""
assert self._async_stop is not None
cursor = CourseCursor(course_list)
count = max(1, min(8, int(workers or 1)))
finished = await asyncio.to_thread(_load_finished, employee_id)
streak = {"n": 0, "wait": 60}
failed = {"n": 0}
streak_lock = asyncio.Lock()
async def worker_loop(index: int) -> None:
@@ -1568,6 +1738,7 @@ class AutoStudyWorker:
pause = 0
async with streak_lock:
if result == "fail":
failed["n"] += 1
streak["n"] += 1
if streak["n"] % 3 == 0:
pause = streak["wait"]
@@ -1582,7 +1753,13 @@ class AutoStudyWorker:
if pause and await wait_stop(pause, self._async_stop, hours.user_stop):
return
await asyncio.gather(*(worker_loop(index) for index in range(1, count + 1)))
try:
async with asyncio.TaskGroup() as group:
for index in range(1, count + 1):
group.create_task(worker_loop(index))
except ExceptionGroup:
log.warning("用户 %s 有学习协程没有跑完", employee_id)
return failed["n"]
async def _study_one_course(self, session: StudySession, employee_id: str,
path: str, title: str, kind: str,
@@ -1594,6 +1771,7 @@ class AutoStudyWorker:
return "stop"
ctype = _course_type(kind, path)
if ctype == "unknown":
log.info("跳过未知类型课程 %s", title or path)
return "skip"
kid = _knowledge_id_from_path(path)
if not kid:
@@ -1601,14 +1779,14 @@ class AutoStudyWorker:
known = finished if finished is not None else set()
if kid in known:
return "skip"
intervals, auto_mode = _current_intervals()
intervals, auto_mode = await asyncio.to_thread(_current_intervals)
_set_user_status(employee_id, course=title)
try:
progress = await session.update_progress(kid, "")
schedule = _progress_of(progress)
_touch(worker, course=title, progress=schedule, ok=True)
_touch(worker, course=title, knowledge_id=kid, progress=schedule, ok=True)
if _completed(progress):
known.add(kid)
await asyncio.to_thread(_remember_finished, employee_id, kid)
@@ -1621,16 +1799,35 @@ class AutoStudyWorker:
session._play_logged = False
params = await _open_play(session, play_path)
if ctype == "package":
_touch(worker, course=title, progress=0, ok=True)
await _study_package(session, kid, intervals, auto_mode,
self._async_stop, hours, user_id, org_id, worker)
_touch(worker, course=title, knowledge_id=kid, progress=0, ok=True)
ok = await _study_package(session, kid, intervals, auto_mode,
self._async_stop, hours, user_id, org_id, worker)
if _halted(self._async_stop, hours):
return "stop"
if not ok:
return "fail"
known.add(kid)
await asyncio.to_thread(_remember_finished, employee_id, kid)
return "studied"
wait, study_time, page_size = _interval_plan(ctype, intervals, auto_mode, params)
session._single_limit = str(params.get("isSingle") or "") == "1"
if ctype == "video":
session._video_cap = _whole(params.get("standardStudyHours"), 0)
if ctype == "document" and _uses_new_timer(params) and auto_mode:
wait = max(1, _whole(params.get("submitProTimes"), 30))
study_time = wait
if ctype == "document" and not _uses_new_timer(params):
standard = _whole(params.get("standardStudyHours"), 0)
span = _whole(params.get("validtimeSpan"), 120)
if 0 < standard < span:
beat = study_time if study_time > 0 else max(1, span)
if _halted(self._async_stop, hours):
return "stop"
await session.submit_document_heartbeat(kid, "", page_size, beat, 1, end=True)
known.add(kid)
await asyncio.to_thread(_remember_finished, employee_id, kid)
return "studied"
if ctype == "video":
await _study_video(
session, kid, "", wait, self._async_stop, hours, worker, study_time=study_time,
@@ -1644,7 +1841,7 @@ class AutoStudyWorker:
await _study_scorm(
session, kid, "", wait, self._async_stop, hours,
str(params.get("userID") or ""), str(params.get("orgID") or ""),
worker, study_time=study_time,
worker, study_time=study_time, scorm_id=str(params.get("scormId") or ""),
)
if _halted(self._async_stop, hours):
return "stop"
@@ -1655,7 +1852,7 @@ class AutoStudyWorker:
hours.user_stop.set()
_touch(worker, ok=False)
_set_user_status(employee_id, state="会话失效", message="请重新登录")
log.info("用户 %s 会话过期", employee_id)
log.info("用户 %s 会话失效", employee_id)
return "stop"
except Exception as exc:
_touch(worker, ok=False)
+4
View File
@@ -433,6 +433,10 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
account = db.get(Account, employee_id)
if account is None or account.refresh_paused or not account.credential_cipher:
return
from euniv.autostudy import is_studying
if is_studying(employee_id):
return
if account.credential_valid is False:
return
client = None
+4 -3
View File
@@ -116,7 +116,10 @@ def view_of(account, now: datetime | None = None) -> dict:
def assemble(account, live: dict | None = None, now: datetime | None = None) -> dict:
payload = view_of(account, now)
info = live if isinstance(live, dict) else {}
info = dict(live) if isinstance(live, dict) else {}
recorded = str(info.get("month") or "")
if recorded and recorded != month_key(now):
info = {}
payload["state"] = str(info.get("state") or "")
payload["course"] = str(info.get("course") or "")
payload["message"] = str(info.get("message") or "")
@@ -174,8 +177,6 @@ def payload_for(employee_id: str) -> dict:
return empty
status = autostudy_status()
live = dict((status.get("users") or {}).get(key) or {})
if not live.get("message"):
live["message"] = str(status.get("message") or "")
if settle(account, live):
db.commit()
return assemble(account, live)
+1
View File
@@ -50,6 +50,7 @@ def fresh_database():
autostudy_mod._retry_at.clear()
autostudy_mod._retry_count.clear()
autostudy_mod._done_month.clear()
autostudy_mod._targets.clear()
autostudy_mod._user_halts.clear()
users = autostudy_mod._status.get("users")
if isinstance(users, dict):
+14 -2
View File
@@ -523,6 +523,14 @@ def test_assemble_prefers_live_month_hours() -> None:
account.hours_month = "2026-10"
account.month_hours = "88"
assert assemble(account, {}, datetime(2026, 11, 2, tzinfo=CN_TZ))["month_hours"] == ""
stale = assemble(
account,
{"state": "已达标", "month": "2026-10", "month_hours": "600", "message": "本月目标已达到"},
datetime(2026, 11, 2, tzinfo=CN_TZ),
)
assert stale["state"] == ""
assert stale["month_hours"] == ""
assert stale["message"] == ""
def test_schedule_disabled_skips_window_until_started() -> None:
@@ -607,7 +615,9 @@ def test_finish_user_keeps_failure_and_clears_idle() -> None:
_finish_user("u1")
assert "u1" not in autostudy_status()["users"]
_finish_user("u2", RuntimeError("boom"))
assert autostudy_status()["users"]["u2"]["state"] == "学习失败"
failed = autostudy_status()["users"]["u2"]
assert failed["state"] == "学习失败"
assert failed["message"] == "学习没有完成"
_clear_user_status("u2")
@@ -842,7 +852,9 @@ def test_video_interval_zero_still_sends_study_time(monkeypatch) -> None:
user_stop = asyncio.Event()
watcher = HoursWatcher(session, "u1", 600, user_stop)
await _study_video(session, "kid", "", 0, global_stop, watcher, study_time=30)
assert session.heartbeats == [(30, 30)]
assert len(session.heartbeats) == 1
assert session.heartbeats[0][0] == 30
assert abs(session.heartbeats[0][1] - 30) <= 1
asyncio.run(main())