feat: 每门课用独立会话学习,间隔改动即时生效,间隔为 0 时不显示倒计时

This commit is contained in:
2026-11-17 17:06:19 +08:00
parent e98cc13061
commit 42b29fb4d6
6 changed files with 424 additions and 53 deletions
+4 -1
View File
@@ -463,14 +463,17 @@ def put_study_bundle(body: StudyBundleBody, request: Request, db: Session = Depe
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
workers_before = account.course_workers
try:
_apply_study_bundle(account, body)
except HTTPException:
db.rollback()
raise
db.commit()
from euniv.autostudy import sync_work
from euniv.autostudy import restart_work, sync_work
if account.course_workers != workers_before:
restart_work(account.employee_id)
sync_work(account.employee_id)
payload = view_of(account)
payload["monthly_target"] = account.monthly_target
+142 -49
View File
@@ -5,8 +5,8 @@
- 每个用户一个协程,asyncio.gather 并行
- 全局 Semaphore 控制总并发,避免压爆上游
- 每个用户一个 StudySession(httpx.AsyncClient),代理仅 HTTP/HTTPS/SOCKS4/SOCKS5
- 每个用户可配置同时学几门课(当前默认 1,结构已预留)
- 心跳间隔用 asyncio.sleep,不占线程
- 每个用户可同时学 1 到 8 门课。每门课一个协程和一份 CourseSession,各自计时、发心跳、读进度
- 心跳间隔用 asyncio.sleep,不占线程。间隔记在内存里,保存配置后正在学的课下一拍就按新值走
- 本月学时:看完一门课后刷新,学习过程中每 1 分钟刷新;达到阈值即停止该账号
"""
@@ -20,6 +20,7 @@ import random
import re
import threading
import time
from collections.abc import Callable
from datetime import datetime, timezone
import httpx
@@ -63,6 +64,7 @@ _retry_at: dict[str, float] = {}
_retry_count: dict[str, int] = {}
_done_month: dict[str, str] = {}
_targets: dict[str, int] = {}
_paces: dict[str, tuple[dict, bool]] = {}
_RETRY_STEPS = (5 * 60, 15 * 60, 60 * 60)
_HOUR_FAIL_LIMIT = 5
_worker = None
@@ -362,12 +364,6 @@ def _beat_landed(
return echoed > before + 0.01
def _pace_wait(interval: int, step: int, landed: bool) -> int:
"""倒计时用账号上设的间隔。平台没入账也不改成播放页的 30 或 120 秒。"""
del step, landed
return 1 if interval <= 0 else int(interval)
def _pace_after(
stall: _Stall,
before: float,
@@ -381,12 +377,13 @@ def _pace_after(
interval: int,
now: float | None = None,
) -> tuple[bool, bool, int]:
"""返回 (是否入账, 是否放弃, 下一次等待秒)。"""
"""返回 (是否入账, 是否放弃, 下一次等待秒)。等待秒就是账号上设的间隔,平台没入账也不改。"""
pause = max(0, int(interval))
landed = _beat_landed(before, after, before_earned, after_earned, result, video=video)
if landed:
stall.note_landed()
return True, stall.stuck(after, step, after_earned), _pace_wait(interval, step, True)
return False, stall.quiet(now), _pace_wait(interval, step, False)
return True, stall.stuck(after, step, after_earned), pause
return False, stall.quiet(now), pause
def _completed(payload: dict) -> bool:
@@ -421,16 +418,42 @@ def _interval_plan(ctype: str, intervals: dict, auto_mode: bool, params: dict) -
return wait, declared, page_size
def _course_plan(ctype: str, intervals: dict, auto_mode: bool, params: dict) -> tuple[int, int, int]:
"""一门课实际用的 (等待秒, 心跳 studyTime, pageSize)。新计时器的文档在自动获取时按页面的短间隔走。"""
wait, study_time, page_size = _interval_plan(ctype, intervals, auto_mode, params)
if ctype == "document" and auto_mode and _uses_new_timer(params):
wait = max(1, _whole((params or {}).get("submitProTimes"), 30))
study_time = wait
return wait, study_time, page_size
_DEFAULT_PACE: tuple[dict, bool] = ({"video": 30, "document": 120, "scorm": 120}, True)
def _remember_pace(account) -> tuple[dict, bool]:
"""把账号的心跳间隔记到内存。正在学的课每一拍都从这里取,保存配置后下一拍就生效。"""
from euniv.heartbeat import intervals_of
pace = intervals_of(account)
key = str(getattr(account, "employee_id", "") or "").strip()
if key:
_paces[key] = pace
return pace
def _pace_of(employee_id: str) -> tuple[dict, bool]:
return _paces.get((employee_id or "").strip()) or _DEFAULT_PACE
def _current_intervals(employee_id: str) -> tuple[dict, bool]:
from euniv.db import SessionLocal
from euniv.heartbeat import intervals_of
from euniv.models import Account
with SessionLocal() as db:
account = db.get(Account, (employee_id or "").strip())
if account is None:
return {"video": 30, "document": 120, "scorm": 120}, True
return intervals_of(account)
return _DEFAULT_PACE
return _remember_pace(account)
def _signal_stop(event: asyncio.Event | None) -> None:
@@ -556,6 +579,7 @@ def sync_work(employee_id: str) -> None:
db.commit()
raw_target = getattr(account, "monthly_target", None)
_targets[key] = int(raw_target) if raw_target is not None else 600
_remember_pace(account)
met = hours_met(account)
due = study_eligible(account)
if met:
@@ -654,6 +678,7 @@ def _job_from_account(row) -> tuple | None:
return None
if employee_id:
_targets[employee_id] = target
_remember_pace(row)
return (
employee_id,
target,
@@ -1239,6 +1264,46 @@ class StudySession:
offset += HISTORY_PAGE_SIZE
return total
def for_course(self) -> "CourseSession":
return CourseSession(self)
class CourseSession(StudySession):
"""一门课自己的会话。
登录态、连接和代理用账号那一份。播放页地址、片长、多端检查和日志次数只属于这门课,
同时在学的其它课读不到也改不到,所以一门课换课或学完不会影响别的课。
"""
def __init__(self, base: StudySession) -> None:
self._base = base
self._employee_id = base._employee_id
self._referer = EUNIV + "/"
self._submit_logs = 0
self._single_limit = False
self._video_cap = 0
self._play_logged = False
def __getattr__(self, name: str):
if name == "_base":
raise AttributeError(name)
return getattr(self._base, name)
async def _http(self, method: str, url: str, **kw: object) -> httpx.Response:
return await self._base._http(method, url, **kw)
async def _api(self, method: str, url: str, **kw: object) -> httpx.Response:
return await self._base._api(method, url, **kw)
async def get_encrypt_request(self, body_json: str) -> str:
return await self._base.get_encrypt_request(body_json)
def _for_course(session):
"""给一门课单独的会话。测试里的替身没有这个方法,直接用它自己。"""
maker = getattr(session, "for_course", None)
return maker() if callable(maker) else session
# ── 单门课程的学习协程 ──
@@ -1270,17 +1335,20 @@ async def _heartbeat_wait(
hours: HoursWatcher,
progress: float,
) -> bool:
delay = _jitter(interval)
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,
)
"""等到下一拍。间隔为 0 时只隔 1 秒就发,页面上不显示倒计时。"""
gap = max(0, int(interval or 0))
delay = _jitter(gap)
if gap <= 0:
_touch(worker, interval=0, heartbeat_at=0, heartbeat_in=0, progress=progress, ok=True)
else:
_touch(
worker,
interval=gap,
heartbeat_at=time.time() + delay,
heartbeat_in=min(int(math.ceil(delay)), gap),
progress=progress,
ok=True,
)
return await wait_stop(delay, stop, hours.user_stop)
@@ -1313,7 +1381,9 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
worker: WorkerView | None = None,
study_time: int | None = None,
snapshot: dict | None = None,
video_cap: int | None = None) -> None:
video_cap: int | None = None,
pace: Callable[[], int] | None = None) -> None:
"""pace 每一拍取一次当前间隔,账号改了间隔后正在学的这门课下一拍就按新值走。"""
step = int(study_time if study_time is not None else (interval if interval > 0 else 30))
if step <= 0:
step = 30
@@ -1340,6 +1410,8 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
"context": "开始播放",
})
while not _halted(stop, hours):
if pace is not None:
interval = pace()
try:
if pending is not None:
progress = pending
@@ -1384,6 +1456,7 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
return
if give_up:
raise RuntimeError("进度长时间没有变化")
pending = fresh
if not page_rhythm:
if await _heartbeat_wait(worker, pause, stop, hours, schedule):
return
@@ -1393,7 +1466,8 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
page_size: int, interval: int, stop: asyncio.Event,
hours: HoursWatcher, worker: WorkerView | None = None,
study_time: int | None = None,
snapshot: dict | None = None) -> None:
snapshot: dict | None = None,
pace: Callable[[], int] | None = None) -> None:
step = int(study_time if study_time is not None else (interval if interval > 0 else 120))
if step <= 0:
step = 120
@@ -1401,6 +1475,8 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
stall = _Stall()
pending = snapshot
while not _halted(stop, hours):
if pace is not None:
interval = pace()
try:
if pending is not None:
progress = pending
@@ -1442,6 +1518,7 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
return
if give_up:
raise RuntimeError("进度长时间没有变化")
pending = fresh
if not page_rhythm:
if await _heartbeat_wait(worker, pause, stop, hours, schedule):
return
@@ -1451,11 +1528,16 @@ 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, scorm_id: str = "",
snapshot: dict | None = None) -> None:
snapshot: dict | None = None,
pace: Callable[[], int] | None = None) -> 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:
step = 120
def gap() -> int:
return pace() if pace is not None else interval
if snapshot is not None:
progress = snapshot
else:
@@ -1484,7 +1566,7 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
if _completed(latest):
await hours.refresh()
return
if await _heartbeat_wait(worker, interval, stop, hours, current):
if await _heartbeat_wait(worker, gap(), stop, hours, current):
return
page_count = 0
@@ -1538,8 +1620,7 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
if _completed(progress):
await hours.refresh()
return
page_wait = interval if interval <= 0 else min(interval, 5)
if await _heartbeat_wait(worker, page_wait, stop, hours, schedule):
if await _heartbeat_wait(worker, min(gap(), 5), stop, hours, schedule):
return
while not _halted(stop, hours):
@@ -1556,14 +1637,16 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
if _completed(progress):
await hours.refresh()
return
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
if await _heartbeat_wait(worker, gap(), stop, hours, schedule):
return
async def _study_package(session: StudySession, kid: str, intervals: dict,
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
async def _study_package(session: StudySession, kid: str,
pace_of: Callable[[], tuple[dict, bool]],
stop: asyncio.Event, hours: HoursWatcher,
user_id: str, org_id: str, worker: WorkerView | None = None,
skipped: dict | None = None) -> bool:
"""按顺序学完包里的章节。pace_of 返回账号当前的间隔,每一拍取一次。"""
pkg = await session.sync_package(kid)
if _completed(pkg):
_touch(worker, progress=_progress_of(pkg), ok=True)
@@ -1587,19 +1670,28 @@ async def _study_package(session: StudySession, kid: str, intervals: dict,
_set_user_status(session._employee_id, course=ch_title)
_show_progress(worker, ch, course=ch_title, knowledge_id=ch_kid, ok=True)
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)
chapter_path = _package_chapter_path(kid, ch_kid, ch_type)
session._referer = f"{EUNIV}{chapter_path}"
session._play_logged = False
params = await _open_play(session, chapter_path)
session._single_limit = str(params.get("isSingle") or "") == "1"
def chapter_pace(kind: str = ch_type, page: dict = params) -> int:
return _course_plan(kind, *pace_of(), page)[0]
wait, study_time, page_size = _course_plan(ch_type, *pace_of(), params)
if ch_type == "video":
cap = _whole(params.get("standardStudyHours"), 0)
session._video_cap = cap
await _study_video(
session, ch_kid, kid, wait, stop, hours, worker,
study_time=study_time, video_cap=cap,
study_time=study_time, video_cap=cap, pace=chapter_pace,
)
else:
session._video_cap = 0
await _study_document(
session, ch_kid, kid, page_size, wait, stop, hours, worker, study_time=study_time,
session, ch_kid, kid, page_size, wait, stop, hours, worker,
study_time=study_time, pace=chapter_pace,
)
except SessionExpired:
raise
@@ -1971,7 +2063,7 @@ class AutoStudyWorker:
return
path, title, kind = item
result = await self._study_one_course(
session, employee_id, path, title, kind,
_for_course(session), employee_id, path, title, kind,
hours, user_id, org_id, view, finished, skipped,
)
pause = 0
@@ -2041,7 +2133,9 @@ class AutoStudyWorker:
if await wait_stop(random.uniform(2.0, 5.0), self._async_stop, hours.user_stop):
return "stop"
intervals, auto_mode = await asyncio.to_thread(_current_intervals, employee_id)
def pace_of() -> tuple[dict, bool]:
return _pace_of(employee_id)
try:
play_path = _play_path(kind, path, kid)
session._referer = f"{EUNIV}{play_path}"
@@ -2050,7 +2144,7 @@ class AutoStudyWorker:
if ctype == "package":
_touch(worker, course=title, knowledge_id=kid, ok=True)
ok = await _study_package(
session, kid, intervals, auto_mode,
session, kid, pace_of,
self._async_stop, hours, user_id, org_id, worker, skipped,
)
if _halted(self._async_stop, hours):
@@ -2061,7 +2155,10 @@ class AutoStudyWorker:
await asyncio.to_thread(_remember_finished, employee_id, kid)
return "studied"
wait, study_time, page_size = _interval_plan(ctype, intervals, auto_mode, params)
def pace() -> int:
return _course_plan(ctype, *pace_of(), params)[0]
wait, study_time, page_size = _course_plan(ctype, *pace_of(), params)
session._single_limit = str(params.get("isSingle") or "") == "1"
if ctype == "video":
video_cap = _whole(params.get("standardStudyHours"), 0)
@@ -2069,10 +2166,6 @@ class AutoStudyWorker:
else:
video_cap = 0
session._video_cap = 0
if ctype == "document" and _uses_new_timer(params) and auto_mode:
page_gap = _whole(params.get("submitProTimes"), 30)
wait = max(1, page_gap)
study_time = wait
if ctype == "document" and not _uses_new_timer(params):
standard = _whole(params.get("standardStudyHours"), 0)
span = _whole(params.get("validtimeSpan"), 120)
@@ -2087,19 +2180,19 @@ class AutoStudyWorker:
if ctype == "video":
await _study_video(
session, kid, "", wait, self._async_stop, hours, worker,
study_time=study_time, snapshot=progress, video_cap=video_cap,
study_time=study_time, snapshot=progress, video_cap=video_cap, pace=pace,
)
elif ctype == "document":
await _study_document(
session, kid, "", page_size, wait, self._async_stop, hours, worker,
study_time=study_time, snapshot=progress,
study_time=study_time, snapshot=progress, pace=pace,
)
elif ctype == "scorm":
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, scorm_id=str(params.get("scormId") or ""),
snapshot=progress,
snapshot=progress, pace=pace,
)
if _halted(self._async_stop, hours):
return "stop"