feat: 每门课用独立会话学习,间隔改动即时生效,间隔为 0 时不显示倒计时
This commit is contained in:
@@ -338,6 +338,7 @@ def set_study_settings(
|
|||||||
if monthly_target is not None:
|
if monthly_target is not None:
|
||||||
if not isinstance(monthly_target, int) or isinstance(monthly_target, bool) or not 0 <= monthly_target <= 9999:
|
if not isinstance(monthly_target, int) or isinstance(monthly_target, bool) or not 0 <= monthly_target <= 9999:
|
||||||
raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数")
|
raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数")
|
||||||
|
workers_before = {account.employee_id: account.course_workers for account in accounts}
|
||||||
try:
|
try:
|
||||||
for account in accounts:
|
for account in accounts:
|
||||||
if monthly_target is not None:
|
if monthly_target is not None:
|
||||||
@@ -357,10 +358,9 @@ def set_study_settings(
|
|||||||
from euniv.autostudy import restart_work, sync_work
|
from euniv.autostudy import restart_work, sync_work
|
||||||
|
|
||||||
for account in accounts:
|
for account in accounts:
|
||||||
if scheme is not None:
|
if scheme is not None or account.course_workers != workers_before[account.employee_id]:
|
||||||
restart_work(account.employee_id)
|
restart_work(account.employee_id)
|
||||||
else:
|
sync_work(account.employee_id)
|
||||||
sync_work(account.employee_id)
|
|
||||||
return {"ok": True, "count": len(accounts)}
|
return {"ok": True, "count": len(accounts)}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -463,14 +463,17 @@ def put_study_bundle(body: StudyBundleBody, request: Request, db: Session = Depe
|
|||||||
account = db.get(Account, _signed_in(request, db))
|
account = db.get(Account, _signed_in(request, db))
|
||||||
if account is None:
|
if account is None:
|
||||||
raise HTTPException(status_code=401, detail="未登录")
|
raise HTTPException(status_code=401, detail="未登录")
|
||||||
|
workers_before = account.course_workers
|
||||||
try:
|
try:
|
||||||
_apply_study_bundle(account, body)
|
_apply_study_bundle(account, body)
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
db.rollback()
|
db.rollback()
|
||||||
raise
|
raise
|
||||||
db.commit()
|
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)
|
sync_work(account.employee_id)
|
||||||
payload = view_of(account)
|
payload = view_of(account)
|
||||||
payload["monthly_target"] = account.monthly_target
|
payload["monthly_target"] = account.monthly_target
|
||||||
|
|||||||
+142
-49
@@ -5,8 +5,8 @@
|
|||||||
- 每个用户一个协程,asyncio.gather 并行
|
- 每个用户一个协程,asyncio.gather 并行
|
||||||
- 全局 Semaphore 控制总并发,避免压爆上游
|
- 全局 Semaphore 控制总并发,避免压爆上游
|
||||||
- 每个用户一个 StudySession(httpx.AsyncClient),代理仅 HTTP/HTTPS/SOCKS4/SOCKS5
|
- 每个用户一个 StudySession(httpx.AsyncClient),代理仅 HTTP/HTTPS/SOCKS4/SOCKS5
|
||||||
- 每个用户可配置同时学几门课(当前默认 1,结构已预留)
|
- 每个用户可同时学 1 到 8 门课。每门课一个协程和一份 CourseSession,各自计时、发心跳、读进度
|
||||||
- 心跳间隔用 asyncio.sleep,不占线程
|
- 心跳间隔用 asyncio.sleep,不占线程。间隔记在内存里,保存配置后正在学的课下一拍就按新值走
|
||||||
- 本月学时:看完一门课后刷新,学习过程中每 1 分钟刷新;达到阈值即停止该账号
|
- 本月学时:看完一门课后刷新,学习过程中每 1 分钟刷新;达到阈值即停止该账号
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -20,6 +20,7 @@ import random
|
|||||||
import re
|
import re
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
from collections.abc import Callable
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
@@ -63,6 +64,7 @@ _retry_at: dict[str, float] = {}
|
|||||||
_retry_count: dict[str, int] = {}
|
_retry_count: dict[str, int] = {}
|
||||||
_done_month: dict[str, str] = {}
|
_done_month: dict[str, str] = {}
|
||||||
_targets: dict[str, int] = {}
|
_targets: dict[str, int] = {}
|
||||||
|
_paces: dict[str, tuple[dict, bool]] = {}
|
||||||
_RETRY_STEPS = (5 * 60, 15 * 60, 60 * 60)
|
_RETRY_STEPS = (5 * 60, 15 * 60, 60 * 60)
|
||||||
_HOUR_FAIL_LIMIT = 5
|
_HOUR_FAIL_LIMIT = 5
|
||||||
_worker = None
|
_worker = None
|
||||||
@@ -362,12 +364,6 @@ def _beat_landed(
|
|||||||
return echoed > before + 0.01
|
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(
|
def _pace_after(
|
||||||
stall: _Stall,
|
stall: _Stall,
|
||||||
before: float,
|
before: float,
|
||||||
@@ -381,12 +377,13 @@ def _pace_after(
|
|||||||
interval: int,
|
interval: int,
|
||||||
now: float | None = None,
|
now: float | None = None,
|
||||||
) -> tuple[bool, bool, int]:
|
) -> tuple[bool, bool, int]:
|
||||||
"""返回 (是否入账, 是否放弃, 下一次等待秒)。"""
|
"""返回 (是否入账, 是否放弃, 下一次等待秒)。等待秒就是账号上设的间隔,平台没入账也不改。"""
|
||||||
|
pause = max(0, int(interval))
|
||||||
landed = _beat_landed(before, after, before_earned, after_earned, result, video=video)
|
landed = _beat_landed(before, after, before_earned, after_earned, result, video=video)
|
||||||
if landed:
|
if landed:
|
||||||
stall.note_landed()
|
stall.note_landed()
|
||||||
return True, stall.stuck(after, step, after_earned), _pace_wait(interval, step, True)
|
return True, stall.stuck(after, step, after_earned), pause
|
||||||
return False, stall.quiet(now), _pace_wait(interval, step, False)
|
return False, stall.quiet(now), pause
|
||||||
|
|
||||||
|
|
||||||
def _completed(payload: dict) -> bool:
|
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
|
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]:
|
def _current_intervals(employee_id: str) -> tuple[dict, bool]:
|
||||||
from euniv.db import SessionLocal
|
from euniv.db import SessionLocal
|
||||||
from euniv.heartbeat import intervals_of
|
|
||||||
from euniv.models import Account
|
from euniv.models import Account
|
||||||
|
|
||||||
with SessionLocal() as db:
|
with SessionLocal() as db:
|
||||||
account = db.get(Account, (employee_id or "").strip())
|
account = db.get(Account, (employee_id or "").strip())
|
||||||
if account is None:
|
if account is None:
|
||||||
return {"video": 30, "document": 120, "scorm": 120}, True
|
return _DEFAULT_PACE
|
||||||
return intervals_of(account)
|
return _remember_pace(account)
|
||||||
|
|
||||||
|
|
||||||
def _signal_stop(event: asyncio.Event | None) -> None:
|
def _signal_stop(event: asyncio.Event | None) -> None:
|
||||||
@@ -556,6 +579,7 @@ def sync_work(employee_id: str) -> None:
|
|||||||
db.commit()
|
db.commit()
|
||||||
raw_target = getattr(account, "monthly_target", None)
|
raw_target = getattr(account, "monthly_target", None)
|
||||||
_targets[key] = int(raw_target) if raw_target is not None else 600
|
_targets[key] = int(raw_target) if raw_target is not None else 600
|
||||||
|
_remember_pace(account)
|
||||||
met = hours_met(account)
|
met = hours_met(account)
|
||||||
due = study_eligible(account)
|
due = study_eligible(account)
|
||||||
if met:
|
if met:
|
||||||
@@ -654,6 +678,7 @@ def _job_from_account(row) -> tuple | None:
|
|||||||
return None
|
return None
|
||||||
if employee_id:
|
if employee_id:
|
||||||
_targets[employee_id] = target
|
_targets[employee_id] = target
|
||||||
|
_remember_pace(row)
|
||||||
return (
|
return (
|
||||||
employee_id,
|
employee_id,
|
||||||
target,
|
target,
|
||||||
@@ -1239,6 +1264,46 @@ class StudySession:
|
|||||||
offset += HISTORY_PAGE_SIZE
|
offset += HISTORY_PAGE_SIZE
|
||||||
return total
|
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,
|
hours: HoursWatcher,
|
||||||
progress: float,
|
progress: float,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
delay = _jitter(interval)
|
"""等到下一拍。间隔为 0 时只隔 1 秒就发,页面上不显示倒计时。"""
|
||||||
cap = max(int(interval or 0), 1)
|
gap = max(0, int(interval or 0))
|
||||||
remaining = max(0, min(int(math.ceil(delay)), cap))
|
delay = _jitter(gap)
|
||||||
_touch(
|
if gap <= 0:
|
||||||
worker,
|
_touch(worker, interval=0, heartbeat_at=0, heartbeat_in=0, progress=progress, ok=True)
|
||||||
interval=interval,
|
else:
|
||||||
heartbeat_at=time.time() + delay,
|
_touch(
|
||||||
heartbeat_in=remaining,
|
worker,
|
||||||
progress=progress,
|
interval=gap,
|
||||||
ok=True,
|
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)
|
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,
|
worker: WorkerView | None = None,
|
||||||
study_time: int | None = None,
|
study_time: int | None = None,
|
||||||
snapshot: dict | 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))
|
step = int(study_time if study_time is not None else (interval if interval > 0 else 30))
|
||||||
if step <= 0:
|
if step <= 0:
|
||||||
step = 30
|
step = 30
|
||||||
@@ -1340,6 +1410,8 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
|||||||
"context": "开始播放",
|
"context": "开始播放",
|
||||||
})
|
})
|
||||||
while not _halted(stop, hours):
|
while not _halted(stop, hours):
|
||||||
|
if pace is not None:
|
||||||
|
interval = pace()
|
||||||
try:
|
try:
|
||||||
if pending is not None:
|
if pending is not None:
|
||||||
progress = pending
|
progress = pending
|
||||||
@@ -1384,6 +1456,7 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
|||||||
return
|
return
|
||||||
if give_up:
|
if give_up:
|
||||||
raise RuntimeError("进度长时间没有变化")
|
raise RuntimeError("进度长时间没有变化")
|
||||||
|
pending = fresh
|
||||||
if not page_rhythm:
|
if not page_rhythm:
|
||||||
if await _heartbeat_wait(worker, pause, stop, hours, schedule):
|
if await _heartbeat_wait(worker, pause, stop, hours, schedule):
|
||||||
return
|
return
|
||||||
@@ -1393,7 +1466,8 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
|
|||||||
page_size: int, interval: int, stop: asyncio.Event,
|
page_size: int, interval: int, stop: asyncio.Event,
|
||||||
hours: HoursWatcher, worker: WorkerView | None = None,
|
hours: HoursWatcher, worker: WorkerView | None = None,
|
||||||
study_time: int | 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))
|
step = int(study_time if study_time is not None else (interval if interval > 0 else 120))
|
||||||
if step <= 0:
|
if step <= 0:
|
||||||
step = 120
|
step = 120
|
||||||
@@ -1401,6 +1475,8 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
|
|||||||
stall = _Stall()
|
stall = _Stall()
|
||||||
pending = snapshot
|
pending = snapshot
|
||||||
while not _halted(stop, hours):
|
while not _halted(stop, hours):
|
||||||
|
if pace is not None:
|
||||||
|
interval = pace()
|
||||||
try:
|
try:
|
||||||
if pending is not None:
|
if pending is not None:
|
||||||
progress = pending
|
progress = pending
|
||||||
@@ -1442,6 +1518,7 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
|
|||||||
return
|
return
|
||||||
if give_up:
|
if give_up:
|
||||||
raise RuntimeError("进度长时间没有变化")
|
raise RuntimeError("进度长时间没有变化")
|
||||||
|
pending = fresh
|
||||||
if not page_rhythm:
|
if not page_rhythm:
|
||||||
if await _heartbeat_wait(worker, pause, stop, hours, schedule):
|
if await _heartbeat_wait(worker, pause, stop, hours, schedule):
|
||||||
return
|
return
|
||||||
@@ -1451,11 +1528,16 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
|
|||||||
interval: int, stop: asyncio.Event, hours: HoursWatcher,
|
interval: int, stop: asyncio.Event, hours: HoursWatcher,
|
||||||
user_id: str, org_id: str, worker: WorkerView | None = None,
|
user_id: str, org_id: str, worker: WorkerView | None = None,
|
||||||
study_time: int | None = None, scorm_id: str = "",
|
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
|
import uuid as _uuid
|
||||||
step = int(study_time if study_time is not None else (interval if interval > 0 else 120))
|
step = int(study_time if study_time is not None else (interval if interval > 0 else 120))
|
||||||
if step <= 0:
|
if step <= 0:
|
||||||
step = 120
|
step = 120
|
||||||
|
|
||||||
|
def gap() -> int:
|
||||||
|
return pace() if pace is not None else interval
|
||||||
|
|
||||||
if snapshot is not None:
|
if snapshot is not None:
|
||||||
progress = snapshot
|
progress = snapshot
|
||||||
else:
|
else:
|
||||||
@@ -1484,7 +1566,7 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
|
|||||||
if _completed(latest):
|
if _completed(latest):
|
||||||
await hours.refresh()
|
await hours.refresh()
|
||||||
return
|
return
|
||||||
if await _heartbeat_wait(worker, interval, stop, hours, current):
|
if await _heartbeat_wait(worker, gap(), stop, hours, current):
|
||||||
return
|
return
|
||||||
|
|
||||||
page_count = 0
|
page_count = 0
|
||||||
@@ -1538,8 +1620,7 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
|
|||||||
if _completed(progress):
|
if _completed(progress):
|
||||||
await hours.refresh()
|
await hours.refresh()
|
||||||
return
|
return
|
||||||
page_wait = interval if interval <= 0 else min(interval, 5)
|
if await _heartbeat_wait(worker, min(gap(), 5), stop, hours, schedule):
|
||||||
if await _heartbeat_wait(worker, page_wait, stop, hours, schedule):
|
|
||||||
return
|
return
|
||||||
|
|
||||||
while not _halted(stop, hours):
|
while not _halted(stop, hours):
|
||||||
@@ -1556,14 +1637,16 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
|
|||||||
if _completed(progress):
|
if _completed(progress):
|
||||||
await hours.refresh()
|
await hours.refresh()
|
||||||
return
|
return
|
||||||
if await _heartbeat_wait(worker, interval, stop, hours, schedule):
|
if await _heartbeat_wait(worker, gap(), stop, hours, schedule):
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
async def _study_package(session: StudySession, kid: str, intervals: dict,
|
async def _study_package(session: StudySession, kid: str,
|
||||||
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
|
pace_of: Callable[[], tuple[dict, bool]],
|
||||||
|
stop: asyncio.Event, hours: HoursWatcher,
|
||||||
user_id: str, org_id: str, worker: WorkerView | None = None,
|
user_id: str, org_id: str, worker: WorkerView | None = None,
|
||||||
skipped: dict | None = None) -> bool:
|
skipped: dict | None = None) -> bool:
|
||||||
|
"""按顺序学完包里的章节。pace_of 返回账号当前的间隔,每一拍取一次。"""
|
||||||
pkg = await session.sync_package(kid)
|
pkg = await session.sync_package(kid)
|
||||||
if _completed(pkg):
|
if _completed(pkg):
|
||||||
_touch(worker, progress=_progress_of(pkg), ok=True)
|
_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)
|
_set_user_status(session._employee_id, course=ch_title)
|
||||||
_show_progress(worker, ch, course=ch_title, knowledge_id=ch_kid, ok=True)
|
_show_progress(worker, ch, course=ch_title, knowledge_id=ch_kid, ok=True)
|
||||||
try:
|
try:
|
||||||
params = await _open_play(session, _package_chapter_path(kid, ch_kid, ch_type))
|
chapter_path = _package_chapter_path(kid, ch_kid, ch_type)
|
||||||
wait, study_time, page_size = _interval_plan(ch_type, intervals, auto_mode, params)
|
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":
|
if ch_type == "video":
|
||||||
cap = _whole(params.get("standardStudyHours"), 0)
|
cap = _whole(params.get("standardStudyHours"), 0)
|
||||||
session._video_cap = cap
|
session._video_cap = cap
|
||||||
await _study_video(
|
await _study_video(
|
||||||
session, ch_kid, kid, wait, stop, hours, worker,
|
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:
|
else:
|
||||||
session._video_cap = 0
|
session._video_cap = 0
|
||||||
await _study_document(
|
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:
|
except SessionExpired:
|
||||||
raise
|
raise
|
||||||
@@ -1971,7 +2063,7 @@ class AutoStudyWorker:
|
|||||||
return
|
return
|
||||||
path, title, kind = item
|
path, title, kind = item
|
||||||
result = await self._study_one_course(
|
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,
|
hours, user_id, org_id, view, finished, skipped,
|
||||||
)
|
)
|
||||||
pause = 0
|
pause = 0
|
||||||
@@ -2041,7 +2133,9 @@ class AutoStudyWorker:
|
|||||||
if await wait_stop(random.uniform(2.0, 5.0), self._async_stop, hours.user_stop):
|
if await wait_stop(random.uniform(2.0, 5.0), self._async_stop, hours.user_stop):
|
||||||
return "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:
|
try:
|
||||||
play_path = _play_path(kind, path, kid)
|
play_path = _play_path(kind, path, kid)
|
||||||
session._referer = f"{EUNIV}{play_path}"
|
session._referer = f"{EUNIV}{play_path}"
|
||||||
@@ -2050,7 +2144,7 @@ class AutoStudyWorker:
|
|||||||
if ctype == "package":
|
if ctype == "package":
|
||||||
_touch(worker, course=title, knowledge_id=kid, ok=True)
|
_touch(worker, course=title, knowledge_id=kid, ok=True)
|
||||||
ok = await _study_package(
|
ok = await _study_package(
|
||||||
session, kid, intervals, auto_mode,
|
session, kid, pace_of,
|
||||||
self._async_stop, hours, user_id, org_id, worker, skipped,
|
self._async_stop, hours, user_id, org_id, worker, skipped,
|
||||||
)
|
)
|
||||||
if _halted(self._async_stop, hours):
|
if _halted(self._async_stop, hours):
|
||||||
@@ -2061,7 +2155,10 @@ class AutoStudyWorker:
|
|||||||
await asyncio.to_thread(_remember_finished, employee_id, kid)
|
await asyncio.to_thread(_remember_finished, employee_id, kid)
|
||||||
return "studied"
|
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"
|
session._single_limit = str(params.get("isSingle") or "") == "1"
|
||||||
if ctype == "video":
|
if ctype == "video":
|
||||||
video_cap = _whole(params.get("standardStudyHours"), 0)
|
video_cap = _whole(params.get("standardStudyHours"), 0)
|
||||||
@@ -2069,10 +2166,6 @@ class AutoStudyWorker:
|
|||||||
else:
|
else:
|
||||||
video_cap = 0
|
video_cap = 0
|
||||||
session._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):
|
if ctype == "document" and not _uses_new_timer(params):
|
||||||
standard = _whole(params.get("standardStudyHours"), 0)
|
standard = _whole(params.get("standardStudyHours"), 0)
|
||||||
span = _whole(params.get("validtimeSpan"), 120)
|
span = _whole(params.get("validtimeSpan"), 120)
|
||||||
@@ -2087,19 +2180,19 @@ class AutoStudyWorker:
|
|||||||
if ctype == "video":
|
if ctype == "video":
|
||||||
await _study_video(
|
await _study_video(
|
||||||
session, kid, "", wait, self._async_stop, hours, worker,
|
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":
|
elif ctype == "document":
|
||||||
await _study_document(
|
await _study_document(
|
||||||
session, kid, "", page_size, wait, self._async_stop, hours, worker,
|
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":
|
elif ctype == "scorm":
|
||||||
await _study_scorm(
|
await _study_scorm(
|
||||||
session, kid, "", wait, self._async_stop, hours,
|
session, kid, "", wait, self._async_stop, hours,
|
||||||
str(params.get("userID") or ""), str(params.get("orgID") or ""),
|
str(params.get("userID") or ""), str(params.get("orgID") or ""),
|
||||||
worker, study_time=study_time, scorm_id=str(params.get("scormId") 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):
|
if _halted(self._async_stop, hours):
|
||||||
return "stop"
|
return "stop"
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ def fresh_database():
|
|||||||
autostudy_mod._retry_count.clear()
|
autostudy_mod._retry_count.clear()
|
||||||
autostudy_mod._done_month.clear()
|
autostudy_mod._done_month.clear()
|
||||||
autostudy_mod._targets.clear()
|
autostudy_mod._targets.clear()
|
||||||
|
autostudy_mod._paces.clear()
|
||||||
autostudy_mod._user_halts.clear()
|
autostudy_mod._user_halts.clear()
|
||||||
users = autostudy_mod._status.get("users")
|
users = autostudy_mod._status.get("users")
|
||||||
if isinstance(users, dict):
|
if isinstance(users, dict):
|
||||||
|
|||||||
@@ -694,6 +694,9 @@ def test_heartbeat_interval_belongs_to_the_user(monkeypatch) -> None:
|
|||||||
assert omitted.json()["heartbeat_video_seconds"] == 1
|
assert omitted.json()["heartbeat_video_seconds"] == 1
|
||||||
current = client.get("/api/settings/heartbeat")
|
current = client.get("/api/settings/heartbeat")
|
||||||
assert current.json()["heartbeat_mode"] == "manual"
|
assert current.json()["heartbeat_mode"] == "manual"
|
||||||
|
from euniv.autostudy import _pace_of
|
||||||
|
|
||||||
|
assert _pace_of("6650000146") == ({"video": 1, "document": 2, "scorm": 3}, False)
|
||||||
intervals, auto = _current_intervals("6650000146")
|
intervals, auto = _current_intervals("6650000146")
|
||||||
assert auto is False
|
assert auto is False
|
||||||
assert intervals == {"video": 1, "document": 2, "scorm": 3}
|
assert intervals == {"video": 1, "document": 2, "scorm": 3}
|
||||||
@@ -882,6 +885,38 @@ def test_start_saves_the_settings_sent_with_it(monkeypatch) -> None:
|
|||||||
assert work_running("6650000146") is False
|
assert work_running("6650000146") is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_changing_the_course_count_restarts_a_running_study(monkeypatch) -> None:
|
||||||
|
import euniv.api as api_module
|
||||||
|
import euniv.autostudy as autostudy_module
|
||||||
|
import euniv.service as service_module
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
api_module,
|
||||||
|
"login_and_store",
|
||||||
|
lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
|
||||||
|
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
|
||||||
|
),
|
||||||
|
)
|
||||||
|
restarted: list[str] = []
|
||||||
|
original = autostudy_module.restart_work
|
||||||
|
|
||||||
|
def record(employee_id: str) -> None:
|
||||||
|
restarted.append(employee_id)
|
||||||
|
original(employee_id)
|
||||||
|
|
||||||
|
monkeypatch.setattr(autostudy_module, "restart_work", record)
|
||||||
|
client = TestClient(api_module.app)
|
||||||
|
_freeze_beijing(monkeypatch, 2026, 11, 15)
|
||||||
|
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
|
||||||
|
started = client.post("/api/settings/study-control", json={"action": "start", "settings": _study_body(workers=2)})
|
||||||
|
assert started.status_code == 200
|
||||||
|
assert client.put("/api/settings/study", json=_study_body(workers=2, monthly_target=700)).status_code == 200
|
||||||
|
assert restarted == []
|
||||||
|
assert client.put("/api/settings/study", json=_study_body(workers=3, monthly_target=700)).status_code == 200
|
||||||
|
assert restarted == ["6650000146"]
|
||||||
|
assert autostudy_module.work_running("6650000146") is True
|
||||||
|
|
||||||
|
|
||||||
def test_study_control_stays_stopped_when_month_hours_met(monkeypatch) -> None:
|
def test_study_control_stays_stopped_when_month_hours_met(monkeypatch) -> None:
|
||||||
import euniv.api as api_module
|
import euniv.api as api_module
|
||||||
import euniv.service as service_module
|
import euniv.service as service_module
|
||||||
|
|||||||
@@ -1177,3 +1177,242 @@ def test_completed_course_skips_the_play_page(monkeypatch) -> None:
|
|||||||
assert opened == []
|
assert opened == []
|
||||||
|
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
||||||
|
|
||||||
|
def test_each_course_has_its_own_play_page_state() -> None:
|
||||||
|
async def main() -> None:
|
||||||
|
base = StudySession("token-1", [])
|
||||||
|
seen: list[tuple[str, str]] = []
|
||||||
|
|
||||||
|
async def fake_http(_method: str, url: str, **kw: object):
|
||||||
|
seen.append((url, str(dict(kw.get("headers") or {}).get("Referer") or "")))
|
||||||
|
return None
|
||||||
|
|
||||||
|
base._client = object()
|
||||||
|
base._http = fake_http
|
||||||
|
first = base.for_course()
|
||||||
|
second = base.for_course()
|
||||||
|
first._referer = "https://euniv.zte.com.cn/kng/view/video/aaa.html"
|
||||||
|
first._video_cap = 60
|
||||||
|
first._single_limit = True
|
||||||
|
first._play_logged = True
|
||||||
|
first._submit_logs = 9
|
||||||
|
assert second._referer == "https://euniv.zte.com.cn/"
|
||||||
|
assert (second._video_cap, second._single_limit, second._play_logged, second._submit_logs) == (0, False, False, 0)
|
||||||
|
assert base._referer == "https://euniv.zte.com.cn/"
|
||||||
|
assert first._token == "token-1"
|
||||||
|
base._token = "token-2"
|
||||||
|
assert second._token == "token-2"
|
||||||
|
await first.post_site_log("CreateSubmitLog", {})
|
||||||
|
await second.post_site_log("CreateSubmitLog", {})
|
||||||
|
assert [referer for _url, referer in seen] == [
|
||||||
|
"https://euniv.zte.com.cn/kng/view/video/aaa.html",
|
||||||
|
"https://euniv.zte.com.cn/",
|
||||||
|
]
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
|
||||||
|
def test_courses_studied_together_do_not_disturb_each_other(monkeypatch) -> None:
|
||||||
|
from euniv.autostudy import AutoStudyWorker
|
||||||
|
|
||||||
|
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
|
||||||
|
monkeypatch.setattr("euniv.autostudy._load_finished", lambda _eid: set())
|
||||||
|
monkeypatch.setattr("euniv.autostudy._remember_finished", lambda *_args, **_kwargs: None)
|
||||||
|
|
||||||
|
async def no_wait(*_args, **_kwargs) -> bool:
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
return False
|
||||||
|
|
||||||
|
monkeypatch.setattr("euniv.autostudy.wait_stop", no_wait)
|
||||||
|
short, long, later = "a" * 32, "b" * 32, "c" * 32
|
||||||
|
need = {short: 1, long: 12, later: 1}
|
||||||
|
length = {short: 60, long: 600, later: 90}
|
||||||
|
sent = {kid: 0 for kid in need}
|
||||||
|
order: list[str] = []
|
||||||
|
gate: dict[str, asyncio.Event] = {}
|
||||||
|
|
||||||
|
async def open_play(_session, path: str) -> dict:
|
||||||
|
kid = path.rsplit("/", 1)[-1].split(".")[0]
|
||||||
|
return {"submitProTimes": 30, "standardStudyHours": length[kid], "pageSize": 1}
|
||||||
|
|
||||||
|
monkeypatch.setattr("euniv.autostudy._open_play", open_play)
|
||||||
|
|
||||||
|
class Course:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._employee_id = "u-split"
|
||||||
|
self.kids: set[str] = set()
|
||||||
|
self.views: list[int] = []
|
||||||
|
|
||||||
|
async def update_progress(self, kid: str, _pkg: str) -> dict:
|
||||||
|
self.kids.add(kid)
|
||||||
|
done = sent[kid] >= need[kid]
|
||||||
|
return {
|
||||||
|
"studyschedule": 100 if done else sent[kid] * 5,
|
||||||
|
"status": "Completed" if done else "Studying",
|
||||||
|
"viewSchedule": sent[kid] * 30,
|
||||||
|
"actualstudyhours": sent[kid],
|
||||||
|
"standardstudyhours": need[kid],
|
||||||
|
}
|
||||||
|
|
||||||
|
async def submit_video_heartbeat(self, kid: str, _pkg: str, _study_time: int, view: int) -> dict:
|
||||||
|
if kid == long and sent[kid] == 2:
|
||||||
|
await asyncio.wait_for(gate["later"].wait(), timeout=5)
|
||||||
|
self.kids.add(kid)
|
||||||
|
self.views.append(view)
|
||||||
|
sent[kid] += 1
|
||||||
|
order.append(kid)
|
||||||
|
if kid == later:
|
||||||
|
gate["later"].set()
|
||||||
|
return {"studySchedule": 100 if sent[kid] >= need[kid] else sent[kid] * 5}
|
||||||
|
|
||||||
|
async def post_site_log(self, *_args, **_kwargs) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
class Login:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.made: list[Course] = []
|
||||||
|
|
||||||
|
def for_course(self) -> Course:
|
||||||
|
course = Course()
|
||||||
|
self.made.append(course)
|
||||||
|
return course
|
||||||
|
|
||||||
|
async def month_hours_text(self) -> str:
|
||||||
|
return "10"
|
||||||
|
|
||||||
|
async def main() -> None:
|
||||||
|
gate["later"] = asyncio.Event()
|
||||||
|
login = Login()
|
||||||
|
host = AutoStudyWorker()
|
||||||
|
host._async_stop = asyncio.Event()
|
||||||
|
hours = HoursWatcher(login, "u-split", 600, asyncio.Event())
|
||||||
|
courses = [
|
||||||
|
(f"/kng/view/video/{short}.html", "短课", "视频"),
|
||||||
|
(f"/kng/view/video/{long}.html", "长课", "视频"),
|
||||||
|
(f"/kng/view/video/{later}.html", "后一门", "视频"),
|
||||||
|
]
|
||||||
|
failed = await host._study_courses(login, "u-split", courses, hours, "", "", 2)
|
||||||
|
assert failed == 0
|
||||||
|
assert sent == need
|
||||||
|
assert len(login.made) == 3
|
||||||
|
assert all(len(course.kids) == 1 for course in login.made)
|
||||||
|
by_kid = {next(iter(course.kids)): course for course in login.made}
|
||||||
|
steady = by_kid[long]
|
||||||
|
assert steady._referer.endswith(f"/kng/view/video/{long}.html")
|
||||||
|
assert steady._video_cap == 600
|
||||||
|
assert len(steady.views) == 12
|
||||||
|
assert 90 < max(steady.views) <= 600
|
||||||
|
assert by_kid[short]._video_cap == 60
|
||||||
|
assert by_kid[later]._video_cap == 90
|
||||||
|
assert sorted(order[:3]) == [short, long, long]
|
||||||
|
assert order[3] == later
|
||||||
|
assert order[4:] == [long] * 10
|
||||||
|
_clear_user_status("u-split")
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
|
||||||
|
def test_zero_interval_waits_a_second_and_hides_the_countdown(monkeypatch) -> None:
|
||||||
|
import time
|
||||||
|
|
||||||
|
from euniv.autostudy import WorkerView, _heartbeat_wait
|
||||||
|
|
||||||
|
delays: list[float] = []
|
||||||
|
|
||||||
|
async def capture(delay: float, *_events) -> bool:
|
||||||
|
delays.append(delay)
|
||||||
|
return False
|
||||||
|
|
||||||
|
monkeypatch.setattr("euniv.autostudy.wait_stop", capture)
|
||||||
|
|
||||||
|
async def main() -> None:
|
||||||
|
_clear_user_status("u-zero")
|
||||||
|
view = WorkerView("u-zero", 1)
|
||||||
|
view.update(course="甲", knowledge_id="k-zero", progress=1)
|
||||||
|
hours = HoursWatcher(object(), "u-zero", 600, asyncio.Event())
|
||||||
|
await _heartbeat_wait(view, 0, asyncio.Event(), hours, 1.0)
|
||||||
|
row = autostudy_status()["users"]["u-zero"]["workers"][0]
|
||||||
|
assert (row["interval"], row["heartbeat_at"], row["heartbeat_in"]) == (0, 0, 0)
|
||||||
|
assert delays == [1.0]
|
||||||
|
await _heartbeat_wait(view, 5, asyncio.Event(), hours, 1.0)
|
||||||
|
row = autostudy_status()["users"]["u-zero"]["workers"][0]
|
||||||
|
assert row["interval"] == 5
|
||||||
|
assert 1 <= row["heartbeat_in"] <= 5
|
||||||
|
assert row["heartbeat_at"] > time.time()
|
||||||
|
assert 5.3 <= delays[1] <= 5.5
|
||||||
|
_clear_user_status("u-zero")
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
|
||||||
|
def test_interval_change_applies_on_the_next_beat(monkeypatch) -> None:
|
||||||
|
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
|
||||||
|
waits: list[int] = []
|
||||||
|
|
||||||
|
async def capture_wait(_worker, interval, _stop, _hours, _progress) -> bool:
|
||||||
|
waits.append(interval)
|
||||||
|
return False
|
||||||
|
|
||||||
|
monkeypatch.setattr("euniv.autostudy._heartbeat_wait", capture_wait)
|
||||||
|
current = {"gap": 1}
|
||||||
|
|
||||||
|
class Session:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.submits = 0
|
||||||
|
self.reads = 0
|
||||||
|
|
||||||
|
async def update_progress(self, _kid: str, _pkg: str) -> dict:
|
||||||
|
self.reads += 1
|
||||||
|
done = self.submits >= 4
|
||||||
|
return {
|
||||||
|
"studyschedule": 100 if done else self.submits * 20,
|
||||||
|
"status": "Completed" if done else "Studying",
|
||||||
|
"actualstudyhours": self.submits,
|
||||||
|
"viewSchedule": self.submits * 30,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def submit_video_heartbeat(self, _kid: str, _pkg: str, _study_time: int, _view: int) -> dict:
|
||||||
|
self.submits += 1
|
||||||
|
if self.submits == 2:
|
||||||
|
current["gap"] = 7
|
||||||
|
return {"studySchedule": self.submits * 20}
|
||||||
|
|
||||||
|
async def month_hours_text(self) -> str:
|
||||||
|
return "10"
|
||||||
|
|
||||||
|
async def main() -> None:
|
||||||
|
session = Session()
|
||||||
|
watcher = HoursWatcher(session, "u-live", 600, asyncio.Event())
|
||||||
|
await _study_video(
|
||||||
|
session, "kid", "", 1, asyncio.Event(), watcher,
|
||||||
|
study_time=30,
|
||||||
|
snapshot={"studyschedule": 0, "status": "Studying", "actualstudyhours": 0, "viewSchedule": 0},
|
||||||
|
video_cap=600,
|
||||||
|
pace=lambda: current["gap"],
|
||||||
|
)
|
||||||
|
assert waits == [1, 1, 7]
|
||||||
|
assert session.submits == 4
|
||||||
|
assert session.reads == 4
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
|
||||||
|
def test_saved_interval_is_kept_in_memory_for_running_courses() -> None:
|
||||||
|
from euniv.autostudy import _course_plan, _pace_of, _remember_pace
|
||||||
|
|
||||||
|
class Row:
|
||||||
|
employee_id = "u-pace"
|
||||||
|
heartbeat_mode = "manual"
|
||||||
|
heartbeat_video_seconds = 0
|
||||||
|
heartbeat_document_seconds = 4
|
||||||
|
heartbeat_scorm_seconds = 6
|
||||||
|
|
||||||
|
assert _pace_of("u-pace-unknown") == ({"video": 30, "document": 120, "scorm": 120}, True)
|
||||||
|
_remember_pace(Row())
|
||||||
|
intervals, auto = _pace_of("u-pace")
|
||||||
|
assert auto is False
|
||||||
|
assert intervals == {"video": 0, "document": 4, "scorm": 6}
|
||||||
|
assert _course_plan("video", intervals, auto, {"submitProTimes": 30})[:2] == (0, 30)
|
||||||
|
assert _course_plan("document", intervals, auto, {"validtimeSpan": 120, "submitIsOpen": "1"})[:2] == (4, 120)
|
||||||
|
assert _course_plan("document", intervals, True, {"submitProTimes": 30, "submitIsOpen": "1"})[:2] == (30, 30)
|
||||||
|
|||||||
Reference in New Issue
Block a user