fix: 停止后不再多发心跳,换课按知识编号重置
This commit is contained in:
@@ -462,15 +462,14 @@ def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db))
|
|||||||
|
|
||||||
@app.get("/api/settings/study-control")
|
@app.get("/api/settings/study-control")
|
||||||
def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
|
def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||||
from euniv.autostudy import autostudy_status
|
from euniv.autostudy import account_status
|
||||||
from euniv.study_control import assemble, settle, stamp_frame
|
from euniv.study_control import assemble, settle, stamp_frame
|
||||||
|
|
||||||
employee_id = _signed_in(request, db)
|
employee_id = _signed_in(request, db)
|
||||||
account = db.get(Account, employee_id)
|
account = db.get(Account, employee_id)
|
||||||
if account is None:
|
if account is None:
|
||||||
raise HTTPException(status_code=401, detail="未登录")
|
raise HTTPException(status_code=401, detail="未登录")
|
||||||
status = autostudy_status()
|
live = account_status(employee_id)
|
||||||
live = dict((status.get("users") or {}).get(employee_id) or {})
|
|
||||||
if settle(account, live):
|
if settle(account, live):
|
||||||
db.commit()
|
db.commit()
|
||||||
return stamp_frame(employee_id, assemble(account, live))
|
return stamp_frame(employee_id, assemble(account, live))
|
||||||
|
|||||||
+177
-100
@@ -94,6 +94,18 @@ def autostudy_status() -> dict:
|
|||||||
return raw
|
return raw
|
||||||
|
|
||||||
|
|
||||||
|
def account_status(employee_id: str) -> dict:
|
||||||
|
"""只复制一个账号的状态,推送时不必复制全部账号。"""
|
||||||
|
key = (employee_id or "").strip()
|
||||||
|
with _lock:
|
||||||
|
raw = (_status.get("users") or {}).get(key)
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
return {}
|
||||||
|
info = dict(raw)
|
||||||
|
info["workers"] = _workers_list(info)
|
||||||
|
return info
|
||||||
|
|
||||||
|
|
||||||
def _notify(employee_id: str = "", urgent: bool = False) -> None:
|
def _notify(employee_id: str = "", urgent: bool = False) -> None:
|
||||||
try:
|
try:
|
||||||
from euniv.study_push import notify
|
from euniv.study_push import notify
|
||||||
@@ -179,10 +191,7 @@ class WorkerView:
|
|||||||
self._origin = 0.0
|
self._origin = 0.0
|
||||||
|
|
||||||
def update(self, **kw: object) -> None:
|
def update(self, **kw: object) -> None:
|
||||||
course = kw.get("course")
|
|
||||||
marker = kw.get("knowledge_id")
|
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:
|
if isinstance(marker, str) and marker and marker != self._course:
|
||||||
self._course = marker
|
self._course = marker
|
||||||
self.sent = 0
|
self.sent = 0
|
||||||
@@ -460,6 +469,18 @@ def _release_pool(employee_id: str, pool: bool) -> None:
|
|||||||
release(employee_id)
|
release(employee_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _release_pool_later(employee_id: str, pool: bool) -> None:
|
||||||
|
"""在事件循环里把释放交给线程,避免堵住会写库的代理锁。"""
|
||||||
|
if not pool or not employee_id:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
except RuntimeError:
|
||||||
|
_release_pool(employee_id, True)
|
||||||
|
return
|
||||||
|
loop.create_task(asyncio.to_thread(_release_pool, employee_id, True))
|
||||||
|
|
||||||
|
|
||||||
def _job_from_account(row) -> tuple | None:
|
def _job_from_account(row) -> tuple | None:
|
||||||
"""从账号列表行提取一次凭据。之后 work 只用这份拷贝,不再读账号表。"""
|
"""从账号列表行提取一次凭据。之后 work 只用这份拷贝,不再读账号表。"""
|
||||||
from euniv.crypto import decrypt_secret
|
from euniv.crypto import decrypt_secret
|
||||||
@@ -472,16 +493,7 @@ def _job_from_account(row) -> tuple | None:
|
|||||||
pool = uses_pool(row)
|
pool = uses_pool(row)
|
||||||
target = int(target_raw) if target_raw is not None else 600
|
target = int(target_raw) if target_raw is not None else 600
|
||||||
if target <= 0:
|
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)
|
_release_pool(employee_id, pool)
|
||||||
if employee_id:
|
|
||||||
_set_user_status(employee_id, state="学习失败", message="凭据无法读取")
|
|
||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
password = decrypt_secret(password_cipher)
|
password = decrypt_secret(password_cipher)
|
||||||
@@ -495,6 +507,16 @@ def _job_from_account(row) -> tuple | None:
|
|||||||
if not isinstance(credential, dict):
|
if not isinstance(credential, dict):
|
||||||
_release_pool(employee_id, pool)
|
_release_pool(employee_id, pool)
|
||||||
return None
|
return None
|
||||||
|
proxy = None
|
||||||
|
if not pool:
|
||||||
|
try:
|
||||||
|
proxy = bind_url(row)
|
||||||
|
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 employee_id:
|
if employee_id:
|
||||||
_targets[employee_id] = target
|
_targets[employee_id] = target
|
||||||
return (
|
return (
|
||||||
@@ -536,6 +558,24 @@ def _course_type(kind: str, path: str) -> str:
|
|||||||
return "unknown"
|
return "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def _chapter_type(raw: object) -> str:
|
||||||
|
"""空串和无法识别的章节类型都不当成文档。"""
|
||||||
|
text = str(raw or "").strip().lower()
|
||||||
|
if "video" in text:
|
||||||
|
return "video"
|
||||||
|
if "document" in text:
|
||||||
|
return "document"
|
||||||
|
return "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def _note_unknown(skipped: dict | None, label: str) -> None:
|
||||||
|
count = 1
|
||||||
|
if isinstance(skipped, dict):
|
||||||
|
count = int(skipped.get("n") or 0) + 1
|
||||||
|
skipped["n"] = count
|
||||||
|
log.info("跳过未知类型课程 %s,累计 %s 门", label, count)
|
||||||
|
|
||||||
|
|
||||||
def _play_path(kind: str, path: str, kid: str) -> str:
|
def _play_path(kind: str, path: str, kid: str) -> str:
|
||||||
compact = compact_id(kid)
|
compact = compact_id(kid)
|
||||||
ctype = _course_type(kind, path)
|
ctype = _course_type(kind, path)
|
||||||
@@ -603,12 +643,16 @@ async def wait_stop(timeout: float, *events: asyncio.Event) -> bool:
|
|||||||
if timeout <= 0:
|
if timeout <= 0:
|
||||||
return False
|
return False
|
||||||
tasks = [asyncio.create_task(event.wait()) for event in events]
|
tasks = [asyncio.create_task(event.wait()) for event in events]
|
||||||
done, pending = await asyncio.wait(tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)
|
try:
|
||||||
for task in pending:
|
done, _pending = await asyncio.wait(
|
||||||
task.cancel()
|
tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED,
|
||||||
if pending:
|
)
|
||||||
await asyncio.gather(*pending, return_exceptions=True)
|
return bool(done)
|
||||||
return bool(done)
|
finally:
|
||||||
|
for task in tasks:
|
||||||
|
if not task.done():
|
||||||
|
task.cancel()
|
||||||
|
await asyncio.gather(*tasks, return_exceptions=True)
|
||||||
|
|
||||||
|
|
||||||
class HoursWatcher:
|
class HoursWatcher:
|
||||||
@@ -998,31 +1042,9 @@ class StudySession:
|
|||||||
return 0
|
return 0
|
||||||
return len(re.findall(r'["\']([^"\']+\.oss\.js)["\']', resp.text))
|
return len(re.findall(r'["\']([^"\']+\.oss\.js)["\']', resp.text))
|
||||||
|
|
||||||
async def scorm_extract_answers(self, kid: str) -> list[dict]:
|
async def scorm_extract_answers(self, kid: str) -> int:
|
||||||
assert self._client is not None
|
"""只取页文件列表长度,不下载课件。索引失败返回 0,不让整门课失败。"""
|
||||||
compact = compact_id(kid)
|
return await self.scorm_page_count(kid)
|
||||||
index_url = f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/index-scorm.js"
|
|
||||||
resp = await self._http("GET", index_url, headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"})
|
|
||||||
urls: list[str] = []
|
|
||||||
for m in re.finditer(r'["\']([^"\']+\.oss\.js)["\']', resp.text):
|
|
||||||
raw = m.group(1)
|
|
||||||
if raw.startswith("http"):
|
|
||||||
urls.append(raw)
|
|
||||||
elif raw.startswith("//"):
|
|
||||||
urls.append("https:" + raw)
|
|
||||||
elif raw.startswith("/"):
|
|
||||||
urls.append(f"https://cdn-cos-file.yunxuetang.cn{raw}")
|
|
||||||
else:
|
|
||||||
urls.append(f"https://cdn-cos-file.yunxuetang.cn/zt/scorm/{compact}/h5/js/{raw}")
|
|
||||||
answers: list[dict] = []
|
|
||||||
for url in urls:
|
|
||||||
try:
|
|
||||||
r = await self._http("GET", url, headers={"User-Agent": USER_AGENT})
|
|
||||||
for block in re.finditer(r'单选题([\s\S]*?)正确答案[::]\s*([A-D])', r.text):
|
|
||||||
answers.append({"page_url": url, "answer": block.group(2)})
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
return answers
|
|
||||||
|
|
||||||
async def month_hours_text(self) -> str:
|
async def month_hours_text(self) -> str:
|
||||||
assert self._client is not None
|
assert self._client is not None
|
||||||
@@ -1151,13 +1173,15 @@ def _uses_new_timer(params: dict | None) -> bool:
|
|||||||
async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
||||||
interval: int, stop: asyncio.Event, hours: HoursWatcher,
|
interval: int, stop: asyncio.Event, hours: HoursWatcher,
|
||||||
worker: WorkerView | None = None,
|
worker: WorkerView | None = None,
|
||||||
study_time: int | None = None) -> None:
|
study_time: int | None = None,
|
||||||
|
snapshot: dict | None = None) -> None:
|
||||||
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
|
||||||
view = 0
|
view = 0
|
||||||
started = False
|
started = False
|
||||||
stall = _Stall()
|
stall = _Stall()
|
||||||
|
pending = snapshot
|
||||||
if not getattr(session, "_play_logged", False):
|
if not getattr(session, "_play_logged", False):
|
||||||
session._play_logged = True
|
session._play_logged = True
|
||||||
poster = getattr(session, "post_site_log", None)
|
poster = getattr(session, "post_site_log", None)
|
||||||
@@ -1170,7 +1194,11 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
|||||||
})
|
})
|
||||||
while not _halted(stop, hours):
|
while not _halted(stop, hours):
|
||||||
try:
|
try:
|
||||||
progress = await session.update_progress(kid, pkg_id)
|
if pending is not None:
|
||||||
|
progress = pending
|
||||||
|
pending = None
|
||||||
|
else:
|
||||||
|
progress = await session.update_progress(kid, pkg_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
_touch(worker, ok=False)
|
_touch(worker, ok=False)
|
||||||
raise
|
raise
|
||||||
@@ -1213,15 +1241,21 @@ async def _study_video(session: StudySession, kid: str, pkg_id: str,
|
|||||||
async def _study_document(session: StudySession, kid: str, pkg_id: str,
|
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) -> None:
|
study_time: int | None = None,
|
||||||
|
snapshot: dict | 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
|
||||||
started = False
|
started = False
|
||||||
stall = _Stall()
|
stall = _Stall()
|
||||||
|
pending = snapshot
|
||||||
while not _halted(stop, hours):
|
while not _halted(stop, hours):
|
||||||
try:
|
try:
|
||||||
progress = await session.update_progress(kid, pkg_id)
|
if pending is not None:
|
||||||
|
progress = pending
|
||||||
|
pending = None
|
||||||
|
else:
|
||||||
|
progress = await session.update_progress(kid, pkg_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
_touch(worker, ok=False)
|
_touch(worker, ok=False)
|
||||||
raise
|
raise
|
||||||
@@ -1240,15 +1274,10 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
|
|||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
await session.submit_document_heartbeat(kid, pkg_id, page_size, step, view)
|
await session.submit_document_heartbeat(kid, pkg_id, page_size, step, view)
|
||||||
progress = await session.update_progress(kid, pkg_id)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
_touch(worker, ok=False)
|
_touch(worker, ok=False)
|
||||||
raise
|
raise
|
||||||
schedule = _progress_of(progress)
|
|
||||||
_beat(worker, schedule, ok=True)
|
_beat(worker, schedule, ok=True)
|
||||||
if _completed(progress):
|
|
||||||
await hours.refresh()
|
|
||||||
return
|
|
||||||
if stall.stuck(schedule, step):
|
if stall.stuck(schedule, step):
|
||||||
raise RuntimeError("进度长时间没有变化")
|
raise RuntimeError("进度长时间没有变化")
|
||||||
if not page_rhythm:
|
if not page_rhythm:
|
||||||
@@ -1259,16 +1288,20 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
|
|||||||
async def _study_scorm(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,
|
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 = "") -> None:
|
study_time: int | None = None, scorm_id: str = "",
|
||||||
|
snapshot: dict | 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
|
||||||
try:
|
if snapshot is not None:
|
||||||
progress = await session.update_progress(kid, pkg_id)
|
progress = snapshot
|
||||||
except Exception:
|
else:
|
||||||
_touch(worker, ok=False)
|
try:
|
||||||
raise
|
progress = await session.update_progress(kid, pkg_id)
|
||||||
|
except Exception:
|
||||||
|
_touch(worker, ok=False)
|
||||||
|
raise
|
||||||
schedule = _progress_of(progress)
|
schedule = _progress_of(progress)
|
||||||
_touch(worker, progress=schedule, ok=True)
|
_touch(worker, progress=schedule, ok=True)
|
||||||
if _completed(progress):
|
if _completed(progress):
|
||||||
@@ -1331,6 +1364,8 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
|
|||||||
scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt,
|
scorm_id=sco_id, scorm_id_ori=kid, sco_cnt=sco_cnt,
|
||||||
pkg_id=pkg_id, data=scorm_data,
|
pkg_id=pkg_id, data=scorm_data,
|
||||||
)
|
)
|
||||||
|
if _halted(stop, hours):
|
||||||
|
return
|
||||||
await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id=sco_id, end=True)
|
await session.submit_scorm_heartbeat(kid, pkg_id, step, sco_id=sco_id, end=True)
|
||||||
progress = await session.update_progress(kid, pkg_id)
|
progress = await session.update_progress(kid, pkg_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -1365,7 +1400,8 @@ async def _study_scorm(session: StudySession, kid: str, pkg_id: str,
|
|||||||
|
|
||||||
async def _study_package(session: StudySession, kid: str, intervals: dict,
|
async def _study_package(session: StudySession, kid: str, intervals: dict,
|
||||||
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
|
auto_mode: bool, stop: asyncio.Event, hours: HoursWatcher,
|
||||||
user_id: str, org_id: str, worker: WorkerView | None = None) -> bool:
|
user_id: str, org_id: str, worker: WorkerView | None = None,
|
||||||
|
skipped: dict | None = None) -> bool:
|
||||||
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)
|
||||||
@@ -1382,16 +1418,20 @@ async def _study_package(session: StudySession, kid: str, intervals: dict,
|
|||||||
if not compact_id(ch_kid):
|
if not compact_id(ch_kid):
|
||||||
log.info("跳过没有编号的章节 %s", ch_title)
|
log.info("跳过没有编号的章节 %s", ch_title)
|
||||||
continue
|
continue
|
||||||
|
ch_type = _chapter_type(ch.get("knowledgeType"))
|
||||||
|
if ch_type == "unknown":
|
||||||
|
_note_unknown(skipped, str(ch_title))
|
||||||
|
continue
|
||||||
_set_user_status(session._employee_id, course=ch_title)
|
_set_user_status(session._employee_id, course=ch_title)
|
||||||
_touch(worker, course=ch_title, knowledge_id=ch_kid, 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"
|
|
||||||
try:
|
try:
|
||||||
params = await _open_play(session, _package_chapter_path(kid, ch_kid, ch_type))
|
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)
|
wait, study_time, page_size = _interval_plan(ch_type, intervals, auto_mode, params)
|
||||||
if is_video:
|
if ch_type == "video":
|
||||||
|
session._video_cap = _whole(params.get("standardStudyHours"), 0)
|
||||||
await _study_video(session, ch_kid, kid, wait, stop, hours, worker, study_time=study_time)
|
await _study_video(session, ch_kid, kid, wait, stop, hours, worker, study_time=study_time)
|
||||||
else:
|
else:
|
||||||
|
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,
|
||||||
)
|
)
|
||||||
@@ -1605,6 +1645,7 @@ class AutoStudyWorker:
|
|||||||
if not course_list:
|
if not course_list:
|
||||||
_set_user_status(eid, state="学习失败", message="没有可用的课程")
|
_set_user_status(eid, state="学习失败", message="没有可用的课程")
|
||||||
drop_work(eid)
|
drop_work(eid)
|
||||||
|
_release_pool_later(eid, bool(job[6]))
|
||||||
return False
|
return False
|
||||||
_set_user_status(eid, state="排队中", course="")
|
_set_user_status(eid, state="排队中", course="")
|
||||||
want_work(eid)
|
want_work(eid)
|
||||||
@@ -1620,15 +1661,20 @@ class AutoStudyWorker:
|
|||||||
try:
|
try:
|
||||||
from admin.settings import hours_source_of
|
from admin.settings import hours_source_of
|
||||||
|
|
||||||
hours_source = await asyncio.to_thread(hours_source_of)
|
if int(target or 0) <= 0:
|
||||||
intervals, auto_mode = await asyncio.to_thread(_current_intervals)
|
if use_pool:
|
||||||
|
await asyncio.to_thread(_release_pool, emp_id, True)
|
||||||
|
return
|
||||||
if not course_list:
|
if not course_list:
|
||||||
_set_user_status(emp_id, state="学习失败", message="没有可用的课程")
|
_set_user_status(emp_id, state="学习失败", message="没有可用的课程")
|
||||||
|
if use_pool:
|
||||||
|
await asyncio.to_thread(_release_pool, emp_id, True)
|
||||||
return
|
return
|
||||||
|
hours_source = await asyncio.to_thread(hours_source_of)
|
||||||
assert self._sem is not None
|
assert self._sem is not None
|
||||||
await self._study_user(
|
await self._study_user(
|
||||||
emp_id, target, pw, cred, proxy, workers, use_pool,
|
emp_id, target, pw, cred, proxy, workers, use_pool,
|
||||||
course_list, intervals, auto_mode, hours_source, self._sem,
|
course_list, hours_source, self._sem,
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log.warning("用户 %s 自动学习失败: %s", emp_id, exc)
|
log.warning("用户 %s 自动学习失败: %s", emp_id, exc)
|
||||||
@@ -1649,8 +1695,8 @@ class AutoStudyWorker:
|
|||||||
|
|
||||||
async def _study_user(self, employee_id: str, target: int,
|
async def _study_user(self, employee_id: str, target: int,
|
||||||
password: str, credential: dict, proxy: str | None,
|
password: str, credential: dict, proxy: str | None,
|
||||||
workers: int, use_pool: bool, course_list: list, intervals: dict,
|
workers: int, use_pool: bool, course_list: list,
|
||||||
auto_mode: bool, hours_source: str, sem: asyncio.Semaphore) -> None:
|
hours_source: str, sem: asyncio.Semaphore) -> None:
|
||||||
assert self._async_stop is not None
|
assert self._async_stop is not None
|
||||||
user_stop = asyncio.Event()
|
user_stop = asyncio.Event()
|
||||||
with _halt_lock:
|
with _halt_lock:
|
||||||
@@ -1660,6 +1706,18 @@ class AutoStudyWorker:
|
|||||||
_user_halts[employee_id] = user_stop
|
_user_halts[employee_id] = user_stop
|
||||||
_running.add(employee_id)
|
_running.add(employee_id)
|
||||||
try:
|
try:
|
||||||
|
if user_stop.is_set():
|
||||||
|
_set_user_status(employee_id, state="已停止")
|
||||||
|
return
|
||||||
|
if use_pool:
|
||||||
|
from euniv.proxy_pool import acquire
|
||||||
|
|
||||||
|
proxy = await asyncio.to_thread(acquire, employee_id)
|
||||||
|
if user_stop.is_set():
|
||||||
|
_set_user_status(employee_id, state="已停止")
|
||||||
|
return
|
||||||
|
if not proxy:
|
||||||
|
_set_user_status(employee_id, message="正在直连")
|
||||||
if user_stop.is_set():
|
if user_stop.is_set():
|
||||||
_set_user_status(employee_id, state="已停止")
|
_set_user_status(employee_id, state="已停止")
|
||||||
return
|
return
|
||||||
@@ -1671,14 +1729,17 @@ class AutoStudyWorker:
|
|||||||
_set_user_status(employee_id, state="已停止")
|
_set_user_status(employee_id, state="已停止")
|
||||||
return
|
return
|
||||||
if not token:
|
if not token:
|
||||||
message = "请重新登录" if reason == "expired" else "无法连接学习平台"
|
if reason == "expired":
|
||||||
_set_user_status(employee_id, state="会话失效", message=message)
|
_set_user_status(employee_id, state="会话失效", message="请重新登录")
|
||||||
|
log.info("用户 %s 需要重新登录", employee_id)
|
||||||
|
else:
|
||||||
|
_set_user_status(employee_id, state="学习失败", message="无法连接学习平台")
|
||||||
|
log.info("用户 %s 无法连接学习平台", employee_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
async with StudySession(
|
async with StudySession(
|
||||||
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool
|
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool
|
||||||
) as session:
|
) as session:
|
||||||
session._employee_id = employee_id # type: ignore[attr-defined]
|
|
||||||
session._request_limit = sem
|
session._request_limit = sem
|
||||||
if user_stop.is_set():
|
if user_stop.is_set():
|
||||||
_set_user_status(employee_id, state="已停止")
|
_set_user_status(employee_id, state="已停止")
|
||||||
@@ -1690,8 +1751,7 @@ class AutoStudyWorker:
|
|||||||
ticker = asyncio.create_task(hours.ticker(self._async_stop))
|
ticker = asyncio.create_task(hours.ticker(self._async_stop))
|
||||||
try:
|
try:
|
||||||
failed = await self._study_courses(
|
failed = await self._study_courses(
|
||||||
session, employee_id, course_list, intervals,
|
session, employee_id, course_list, hours, user_id, org_id, workers)
|
||||||
auto_mode, hours, user_id, org_id, workers)
|
|
||||||
if hours.reached or user_stop.is_set() or self._async_stop.is_set():
|
if hours.reached or user_stop.is_set() or self._async_stop.is_set():
|
||||||
return
|
return
|
||||||
if failed:
|
if failed:
|
||||||
@@ -1718,8 +1778,7 @@ class AutoStudyWorker:
|
|||||||
await asyncio.to_thread(release, employee_id)
|
await asyncio.to_thread(release, employee_id)
|
||||||
|
|
||||||
async def _study_courses(self, session: StudySession, employee_id: str,
|
async def _study_courses(self, session: StudySession, employee_id: str,
|
||||||
course_list: list, intervals: dict,
|
course_list: list, hours: HoursWatcher,
|
||||||
auto_mode: bool, hours: HoursWatcher,
|
|
||||||
user_id: str, org_id: str, workers: int) -> int:
|
user_id: str, org_id: str, workers: int) -> int:
|
||||||
"""N 个协程顺着课程表往下领,已完成的跳过,未完成的发心跳。"""
|
"""N 个协程顺着课程表往下领,已完成的跳过,未完成的发心跳。"""
|
||||||
assert self._async_stop is not None
|
assert self._async_stop is not None
|
||||||
@@ -1728,6 +1787,7 @@ class AutoStudyWorker:
|
|||||||
finished = await asyncio.to_thread(_load_finished, employee_id)
|
finished = await asyncio.to_thread(_load_finished, employee_id)
|
||||||
streak = {"n": 0, "wait": 60}
|
streak = {"n": 0, "wait": 60}
|
||||||
failed = {"n": 0}
|
failed = {"n": 0}
|
||||||
|
skipped = {"n": 0}
|
||||||
streak_lock = asyncio.Lock()
|
streak_lock = asyncio.Lock()
|
||||||
|
|
||||||
async def worker_loop(index: int) -> None:
|
async def worker_loop(index: int) -> None:
|
||||||
@@ -1741,7 +1801,7 @@ class AutoStudyWorker:
|
|||||||
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,
|
session, employee_id, path, title, kind,
|
||||||
intervals, auto_mode, hours, user_id, org_id, view, finished,
|
hours, user_id, org_id, view, finished, skipped,
|
||||||
)
|
)
|
||||||
pause = 0
|
pause = 0
|
||||||
async with streak_lock:
|
async with streak_lock:
|
||||||
@@ -1761,25 +1821,23 @@ class AutoStudyWorker:
|
|||||||
if pause and await wait_stop(pause, self._async_stop, hours.user_stop):
|
if pause and await wait_stop(pause, self._async_stop, hours.user_stop):
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
async with asyncio.TaskGroup() as group:
|
||||||
async with asyncio.TaskGroup() as group:
|
for index in range(1, count + 1):
|
||||||
for index in range(1, count + 1):
|
group.create_task(worker_loop(index))
|
||||||
group.create_task(worker_loop(index))
|
|
||||||
except ExceptionGroup:
|
|
||||||
log.warning("用户 %s 有学习协程没有跑完", employee_id)
|
|
||||||
return failed["n"]
|
return failed["n"]
|
||||||
|
|
||||||
async def _study_one_course(self, session: StudySession, employee_id: str,
|
async def _study_one_course(self, session: StudySession, employee_id: str,
|
||||||
path: str, title: str, kind: str,
|
path: str, title: str, kind: str,
|
||||||
intervals: dict, auto_mode: bool,
|
|
||||||
hours: HoursWatcher, user_id: str, org_id: str,
|
hours: HoursWatcher, user_id: str, org_id: str,
|
||||||
worker: WorkerView | None = None, finished: set[str] | None = None) -> str:
|
worker: WorkerView | None = None,
|
||||||
|
finished: set[str] | None = None,
|
||||||
|
skipped: dict | None = None) -> str:
|
||||||
assert self._async_stop is not None
|
assert self._async_stop is not None
|
||||||
if _halted(self._async_stop, hours):
|
if _halted(self._async_stop, hours):
|
||||||
return "stop"
|
return "stop"
|
||||||
ctype = _course_type(kind, path)
|
ctype = _course_type(kind, path)
|
||||||
if ctype == "unknown":
|
if ctype == "unknown":
|
||||||
log.info("跳过未知类型课程 %s", title or path)
|
_note_unknown(skipped, title or path)
|
||||||
return "skip"
|
return "skip"
|
||||||
kid = _knowledge_id_from_path(path)
|
kid = _knowledge_id_from_path(path)
|
||||||
if not kid:
|
if not kid:
|
||||||
@@ -1787,29 +1845,44 @@ class AutoStudyWorker:
|
|||||||
known = finished if finished is not None else set()
|
known = finished if finished is not None else set()
|
||||||
if kid in known:
|
if kid in known:
|
||||||
return "skip"
|
return "skip"
|
||||||
intervals, auto_mode = await asyncio.to_thread(_current_intervals)
|
|
||||||
|
|
||||||
_set_user_status(employee_id, course=title)
|
_set_user_status(employee_id, course=title)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
progress = await session.update_progress(kid, "")
|
progress = await session.update_progress(kid, "")
|
||||||
schedule = _progress_of(progress)
|
except SessionExpired:
|
||||||
_touch(worker, course=title, knowledge_id=kid, progress=schedule, ok=True)
|
hours.user_stop.set()
|
||||||
if _completed(progress):
|
_touch(worker, ok=False)
|
||||||
known.add(kid)
|
_set_user_status(employee_id, state="会话失效", message="请重新登录")
|
||||||
await asyncio.to_thread(_remember_finished, employee_id, kid)
|
log.info("用户 %s 会话失效", employee_id)
|
||||||
await wait_stop(random.uniform(0.5, 1.5), self._async_stop, hours.user_stop)
|
return "stop"
|
||||||
return "done"
|
except Exception as exc:
|
||||||
if await wait_stop(random.uniform(2.0, 5.0), self._async_stop, hours.user_stop):
|
_touch(worker, ok=False)
|
||||||
return "stop"
|
log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
|
||||||
|
return "fail"
|
||||||
|
|
||||||
|
schedule = _progress_of(progress)
|
||||||
|
_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)
|
||||||
|
await wait_stop(random.uniform(0.5, 1.5), self._async_stop, hours.user_stop)
|
||||||
|
return "done"
|
||||||
|
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)
|
||||||
|
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}"
|
||||||
session._play_logged = False
|
session._play_logged = False
|
||||||
params = await _open_play(session, play_path)
|
params = await _open_play(session, play_path)
|
||||||
if ctype == "package":
|
if ctype == "package":
|
||||||
_touch(worker, course=title, knowledge_id=kid, progress=0, ok=True)
|
_touch(worker, course=title, knowledge_id=kid, progress=0, ok=True)
|
||||||
ok = await _study_package(session, kid, intervals, auto_mode,
|
ok = await _study_package(
|
||||||
self._async_stop, hours, user_id, org_id, worker)
|
session, kid, intervals, auto_mode,
|
||||||
|
self._async_stop, hours, user_id, org_id, worker, skipped,
|
||||||
|
)
|
||||||
if _halted(self._async_stop, hours):
|
if _halted(self._async_stop, hours):
|
||||||
return "stop"
|
return "stop"
|
||||||
if not ok:
|
if not ok:
|
||||||
@@ -1822,8 +1895,11 @@ class AutoStudyWorker:
|
|||||||
session._single_limit = str(params.get("isSingle") or "") == "1"
|
session._single_limit = str(params.get("isSingle") or "") == "1"
|
||||||
if ctype == "video":
|
if ctype == "video":
|
||||||
session._video_cap = _whole(params.get("standardStudyHours"), 0)
|
session._video_cap = _whole(params.get("standardStudyHours"), 0)
|
||||||
|
else:
|
||||||
|
session._video_cap = 0
|
||||||
if ctype == "document" and _uses_new_timer(params) and auto_mode:
|
if ctype == "document" and _uses_new_timer(params) and auto_mode:
|
||||||
wait = max(1, _whole(params.get("submitProTimes"), 30))
|
page_gap = _whole(params.get("submitProTimes"), 30)
|
||||||
|
wait = max(1, page_gap)
|
||||||
study_time = wait
|
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)
|
||||||
@@ -1838,18 +1914,20 @@ class AutoStudyWorker:
|
|||||||
return "studied"
|
return "studied"
|
||||||
if ctype == "video":
|
if ctype == "video":
|
||||||
await _study_video(
|
await _study_video(
|
||||||
session, kid, "", wait, self._async_stop, hours, worker, study_time=study_time,
|
session, kid, "", wait, self._async_stop, hours, worker,
|
||||||
|
study_time=study_time, snapshot=progress,
|
||||||
)
|
)
|
||||||
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,
|
study_time=study_time, snapshot=progress,
|
||||||
)
|
)
|
||||||
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,
|
||||||
)
|
)
|
||||||
if _halted(self._async_stop, hours):
|
if _halted(self._async_stop, hours):
|
||||||
return "stop"
|
return "stop"
|
||||||
@@ -1866,7 +1944,6 @@ class AutoStudyWorker:
|
|||||||
_touch(worker, ok=False)
|
_touch(worker, ok=False)
|
||||||
log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
|
log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
|
||||||
return "fail"
|
return "fail"
|
||||||
return "skip"
|
|
||||||
|
|
||||||
|
|
||||||
# ── 数据库更新 ──
|
# ── 数据库更新 ──
|
||||||
|
|||||||
@@ -166,7 +166,7 @@ def settle(account, live: dict | None = None, now: datetime | None = None) -> bo
|
|||||||
|
|
||||||
|
|
||||||
def payload_for(employee_id: str) -> dict:
|
def payload_for(employee_id: str) -> dict:
|
||||||
from euniv.autostudy import autostudy_status
|
from euniv.autostudy import account_status
|
||||||
from euniv.db import SessionLocal
|
from euniv.db import SessionLocal
|
||||||
from euniv.models import Account
|
from euniv.models import Account
|
||||||
|
|
||||||
@@ -186,8 +186,7 @@ def payload_for(employee_id: str) -> dict:
|
|||||||
account = db.get(Account, key)
|
account = db.get(Account, key)
|
||||||
if account is None:
|
if account is None:
|
||||||
return empty
|
return empty
|
||||||
status = autostudy_status()
|
live = account_status(key)
|
||||||
live = dict((status.get("users") or {}).get(key) or {})
|
|
||||||
if settle(account, live):
|
if settle(account, live):
|
||||||
db.commit()
|
db.commit()
|
||||||
return stamp_frame(key, assemble(account, live))
|
return stamp_frame(key, assemble(account, live))
|
||||||
|
|||||||
@@ -159,7 +159,7 @@ def test_worker_view_freezes_total_after_first_beat() -> None:
|
|||||||
|
|
||||||
_clear_user_status("u-total")
|
_clear_user_status("u-total")
|
||||||
view = WorkerView("u-total", 1)
|
view = WorkerView("u-total", 1)
|
||||||
view.update(course="甲", progress=38)
|
view.update(course="甲", knowledge_id="k-jia", progress=38)
|
||||||
view.after_beat(39, ok=True)
|
view.after_beat(39, ok=True)
|
||||||
first = autostudy_status()["users"]["u-total"]["workers"][0]["total"]
|
first = autostudy_status()["users"]["u-total"]["workers"][0]["total"]
|
||||||
assert first == 62
|
assert first == 62
|
||||||
@@ -933,8 +933,6 @@ def test_completed_course_skips_the_play_page(monkeypatch) -> None:
|
|||||||
f"/kng/view/video/{COMPACT_KID}.html",
|
f"/kng/view/video/{COMPACT_KID}.html",
|
||||||
"已完成",
|
"已完成",
|
||||||
"视频",
|
"视频",
|
||||||
{},
|
|
||||||
False,
|
|
||||||
watcher,
|
watcher,
|
||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
|
|||||||
Reference in New Issue
Block a user