Compare commits

...
2 Commits
7 changed files with 434 additions and 192 deletions
+2 -3
View File
@@ -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
View File
@@ -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"
# ── 数据库更新 ── # ── 数据库更新 ──
+58 -15
View File
@@ -15,6 +15,7 @@ log = logging.getLogger(__name__)
CHINA = {"cn", "chn", "china", "中国"} CHINA = {"cn", "chn", "china", "中国"}
_SOURCE_TITLES = {"proxyhub": "ProxyHub"} _SOURCE_TITLES = {"proxyhub": "ProxyHub"}
MAX_RESPONSE_BYTES = 1_048_576
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -163,19 +164,57 @@ def parse_proxyhub_result(payload: object) -> list[ProxyCandidate]:
return [] return []
def _read_mcp(response: httpx.Response) -> dict: def _json_dict(text: str) -> dict:
ctype = (response.headers.get("content-type") or "").lower() try:
if "json" in ctype: payload = json.loads(text or "{}")
payload = response.json() except json.JSONDecodeError:
return payload if isinstance(payload, dict) else {} return {}
for line in response.text.splitlines():
if line.startswith("data:"):
payload = json.loads(line[5:].strip() or "{}")
return payload if isinstance(payload, dict) else {}
payload = json.loads(response.text or "{}")
return payload if isinstance(payload, dict) else {} return payload if isinstance(payload, dict) else {}
def _limited_body(response: httpx.Response) -> bytes:
declared = response.headers.get("content-length")
if declared and declared.isdigit() and int(declared) > MAX_RESPONSE_BYTES:
raise ValueError("上游响应过大")
chunks: list[bytes] = []
total = 0
for chunk in response.iter_bytes():
total += len(chunk)
if total > MAX_RESPONSE_BYTES:
raise ValueError("上游响应过大")
chunks.append(chunk)
return b"".join(chunks)
def _read_mcp(response: httpx.Response) -> dict:
text = _limited_body(response).decode("utf-8", errors="replace")
ctype = (response.headers.get("content-type") or "").lower()
if "json" in ctype and "event-stream" not in ctype:
parsed = _json_dict(text)
if parsed or text.strip() in {"", "{}"}:
return parsed
chosen: dict | None = None
saw_data = False
for line in text.splitlines():
if not line.startswith("data:"):
continue
saw_data = True
raw = line[5:].strip()
if not raw:
continue
try:
payload = json.loads(raw)
except json.JSONDecodeError:
continue
if not isinstance(payload, dict):
continue
if chosen is None or "result" in payload or "error" in payload:
chosen = payload
if saw_data:
return chosen or {}
return _json_dict(text)
class ProxyHubCollector(Collector): class ProxyHubCollector(Collector):
name = "proxyhub" name = "proxyhub"
url = "https://proxyhub.me/api/mcp" url = "https://proxyhub.me/api/mcp"
@@ -185,9 +224,13 @@ class ProxyHubCollector(Collector):
def collect(self) -> list[ProxyCandidate]: def collect(self) -> list[ProxyCandidate]:
items: list[ProxyCandidate] = [] items: list[ProxyCandidate] = []
with ThreadPoolExecutor(max_workers=len(self.types)) as pool: with ThreadPoolExecutor(max_workers=len(self.types)) as pool:
futures = [pool.submit(self._list, kind) for kind in self.types] futures = {pool.submit(self._list, kind): kind for kind in self.types}
for future in as_completed(futures): for future in as_completed(futures):
items.extend(future.result()) kind = futures[future]
try:
items.extend(future.result())
except Exception:
log.warning("上游 %s 的 %s 没有获取到", self.name, kind, exc_info=True)
return items return items
def _list(self, kind: str) -> list[ProxyCandidate]: def _list(self, kind: str) -> list[ProxyCandidate]:
@@ -213,9 +256,9 @@ class ProxyHubCollector(Collector):
"Mcp-Name": "list_proxies", "Mcp-Name": "list_proxies",
} }
with httpx.Client(timeout=20, follow_redirects=True, trust_env=False) as client: with httpx.Client(timeout=20, follow_redirects=True, trust_env=False) as client:
response = client.post(self.url, headers=headers, json=body) with client.stream("POST", self.url, headers=headers, json=body) as response:
response.raise_for_status() response.raise_for_status()
return parse_proxyhub_result(_read_mcp(response)) return parse_proxyhub_result(_read_mcp(response))
register(ProxyHubCollector()) register(ProxyHubCollector())
+58 -15
View File
@@ -26,15 +26,42 @@ def canonical_scheme(scheme: str | None) -> str:
return kind return kind
def _unwrap_host(host: str) -> str:
text = host.strip()
if len(text) >= 2 and text.startswith("[") and text.endswith("]"):
return text[1:-1]
return text
def _host_is_public(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
return not (
ip.is_private
or ip.is_loopback
or ip.is_link_local
or ip.is_reserved
or ip.is_multicast
or ip.is_unspecified
)
def _reject_private(addresses: list[ipaddress.IPv4Address | ipaddress.IPv6Address]) -> None:
for ip in addresses:
if not _host_is_public(ip):
raise ProxyError("代理只允许公网地址")
def assert_public_host(host: str) -> None: def assert_public_host(host: str) -> None:
"""手填和采集都只接受公网地址。""" """手填和采集都只接受公网地址。"""
address = (host or "").strip() address = (host or "").strip()
if not address or any(char in address for char in "@/#?"): if not address or any(char in address for char in "@/#?"):
raise ProxyError("代理只允许公网地址") raise ProxyError("代理只允许公网地址")
bare = _unwrap_host(address)
if bare != address and (not bare or any(char in bare for char in "[]/@#?")):
raise ProxyError("代理地址不合法")
try: try:
addresses = [ipaddress.ip_address(address)] addresses = [ipaddress.ip_address(bare)]
except ValueError: except ValueError:
if not re.fullmatch(r"[A-Za-z0-9.-]+", address) or ".." in address or address.startswith("-"): if bare != address or not re.fullmatch(r"[A-Za-z0-9.-]+", address) or ".." in address or address.startswith("-"):
raise ProxyError("代理地址不合法") raise ProxyError("代理地址不合法")
try: try:
found = socket.getaddrinfo(address, None) found = socket.getaddrinfo(address, None)
@@ -48,24 +75,35 @@ def assert_public_host(host: str) -> None:
continue continue
if not addresses: if not addresses:
raise ProxyError("代理地址无法解析") raise ProxyError("代理地址无法解析")
for ip in addresses: _reject_private(addresses)
if (
ip.is_private
or ip.is_loopback
or ip.is_link_local
or ip.is_reserved
or ip.is_multicast
or ip.is_unspecified
):
raise ProxyError("代理只允许公网地址")
def _host_for_url(host: str) -> str: def _host_for_url(host: str) -> str:
bare = _unwrap_host(host)
try: try:
ipaddress.IPv6Address(host) ipaddress.IPv6Address(bare)
except ValueError: except ValueError:
return host return host.strip() or host
return f"[{host}]" return f"[{bare}]"
def _written_host(host: str) -> str:
"""主机名只留字母、数字、点和横线;IPv6 写入时加方括号。"""
address = host.strip()
if not address or any(char in address for char in "@/#?"):
raise ProxyError("代理地址不合法")
bare = _unwrap_host(address)
if bare != address and (not bare or any(char in bare for char in "[]")):
raise ProxyError("代理地址不合法")
try:
parsed = ipaddress.ip_address(bare)
except ValueError:
if bare != address or not re.fullmatch(r"[A-Za-z0-9.-]+", address) or ".." in address or address.startswith("-"):
raise ProxyError("代理地址不合法")
return address
if isinstance(parsed, ipaddress.IPv6Address):
return f"[{bare}]"
return bare
def parse_proxy(value: str | None) -> str | None: def parse_proxy(value: str | None) -> str | None:
@@ -79,6 +117,8 @@ def parse_proxy(value: str | None) -> str | None:
scheme = canonical_scheme(parsed.scheme) scheme = canonical_scheme(parsed.scheme)
if scheme not in SCHEMES: if scheme not in SCHEMES:
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5") raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
if parsed.path not in ("", "/") or parsed.query or parsed.fragment:
raise ProxyError("代理地址不合法")
if not parsed.hostname: if not parsed.hostname:
raise ProxyError("代理地址不完整") raise ProxyError("代理地址不完整")
host = _host_for_url(parsed.hostname) host = _host_for_url(parsed.hostname)
@@ -115,6 +155,9 @@ def validate_parts(scheme: str, host: str, port: object, username: str = "") ->
address = (host or "").strip() address = (host or "").strip()
if not address or "://" in address or any(ch.isspace() for ch in address): if not address or "://" in address or any(ch.isspace() for ch in address):
raise ProxyError("请填写代理地址") raise ProxyError("请填写代理地址")
if len(address) > 255:
raise ProxyError("代理地址过长")
address = _written_host(address)
if len(address) > 255: if len(address) > 255:
raise ProxyError("代理地址过长") raise ProxyError("代理地址过长")
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535: if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
+136 -53
View File
@@ -11,6 +11,7 @@ from urllib.parse import urlparse
import httpx import httpx
from sqlalchemy import case, func, select from sqlalchemy import case, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API
@@ -30,6 +31,7 @@ LATENCY_LIMIT = 3.0
LATENCY_LIMIT_MS = 3000 LATENCY_LIMIT_MS = 3000
PROBE_CONCURRENCY = 16 PROBE_CONCURRENCY = 16
MAX_PROBES = 80 MAX_PROBES = 80
ALIVE_REPROBE_SLOTS = 20
MAX_SWITCHES = 8 MAX_SWITCHES = 8
PROBE_URL = EUNIV + "/" PROBE_URL = EUNIV + "/"
PROBE_URLS = ( PROBE_URLS = (
@@ -62,10 +64,20 @@ def _url(node: ProxyNode) -> str:
def _sync_row(db: Session) -> ProxyPoolSync: def _sync_row(db: Session) -> ProxyPoolSync:
row = db.get(ProxyPoolSync, 1) row = db.get(ProxyPoolSync, 1)
if row is None: if row is not None:
row = ProxyPoolSync(id=1) return row
db.add(row) row = ProxyPoolSync(id=1)
db.flush() try:
with db.begin_nested():
db.add(row)
db.flush()
except IntegrityError:
if row in db:
db.expunge(row)
found = db.get(ProxyPoolSync, 1)
if found is None:
raise
return found
return row return row
@@ -193,8 +205,6 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
reasons.append(_short_reason(exc)) reasons.append(_short_reason(exc))
except Exception as exc: except Exception as exc:
return False, 0, _short_reason(exc) return False, 0, _short_reason(exc)
if not samples:
return False, 0, reasons[0] if reasons else "无法连接"
average = int(round(sum(samples) / len(samples))) average = int(round(sum(samples) / len(samples)))
if reasons: if reasons:
return False, average, reasons[0] return False, average, reasons[0]
@@ -218,15 +228,28 @@ def _direct_reaches_target() -> bool:
return False return False
def _clip_reason(reason: str, fallback: str = "失效") -> str:
text = (reason or "").strip() or fallback
if len(text) <= 200:
return text
log.warning("代理失败原因:%s", text)
return text[:200]
def _short_reason(exc: BaseException) -> str: def _short_reason(exc: BaseException) -> str:
from python_socks import ProxyConnectionError, ProxyTimeoutError from python_socks import ProxyConnectionError, ProxyTimeoutError
if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException, ProxyTimeoutError)):
return "超时"
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, ProxyConnectionError)):
return "无法连接"
text = str(exc).strip() or type(exc).__name__ text = str(exc).strip() or type(exc).__name__
return text[:200] if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException, ProxyTimeoutError)):
stored = "超时"
elif isinstance(exc, (httpx.ProxyError, httpx.ConnectError, ProxyConnectionError)):
stored = "无法连接"
else:
stored = text
if stored != text:
log.warning("代理失败原因:%s", text)
return stored
return _clip_reason(stored)
def _find_node(db: Session, scheme: str, host: str, port: int) -> ProxyNode | None: def _find_node(db: Session, scheme: str, host: str, port: int) -> ProxyNode | None:
@@ -267,24 +290,47 @@ def acquire(employee_id: str) -> str | None:
if held is not None and held.status == STATUS_ALIVE: if held is not None and held.status == STATUS_ALIVE:
return _url(held) return _url(held)
_holds.pop(key, None) _holds.pop(key, None)
if held is not None:
held.assigns = _occupancy(held.id)
nodes = list(db.scalars(select(ProxyNode).where(ProxyNode.status == STATUS_ALIVE)).all()) nodes = list(db.scalars(select(ProxyNode).where(ProxyNode.status == STATUS_ALIVE)).all())
if not nodes: if not nodes:
db.commit()
return None return None
load = {node.id: 0 for node in nodes} load = {node.id: 0 for node in nodes}
for node_id in _holds.values(): for node_id in _holds.values():
if node_id in load: if node_id in load:
load[node_id] += 1 load[node_id] += 1
nodes.sort(key=lambda node: (load[node.id], node.assigns, node.id)) for node in nodes:
node.assigns = load[node.id]
nodes.sort(key=lambda node: (load[node.id], _latency_rank(node), node.assigns, node.id))
pick = nodes[0] pick = nodes[0]
_holds[key] = pick.id _holds[key] = pick.id
pick.assigns = int(pick.assigns or 0) + 1 pick.assigns = load[pick.id] + 1
db.commit() db.commit()
return _url(pick) return _url(pick)
def _latency_rank(node: ProxyNode) -> int:
if node.latency_ms is None:
return 1_000_000_000
return int(node.latency_ms)
def _occupancy(node_id: int) -> int:
return sum(1 for held in _holds.values() if held == node_id)
def release(employee_id: str) -> None: def release(employee_id: str) -> None:
with _assign_lock: key = (employee_id or "").strip()
_holds.pop((employee_id or "").strip(), None) with SessionLocal() as db, _assign_lock:
node_id = _holds.pop(key, None)
if node_id is None:
return
node = db.get(ProxyNode, node_id)
if node is None:
return
node.assigns = _occupancy(node_id)
db.commit()
def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None: def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None:
@@ -300,8 +346,9 @@ def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = ""
if held == node.id: if held == node.id:
_holds.pop(key, None) _holds.pop(key, None)
node.status = STATUS_DEAD node.status = STATUS_DEAD
node.fail_reason = (reason or "失效")[:200] node.fail_reason = _clip_reason(reason)
node.last_checked_at = _now() node.last_checked_at = _now()
node.assigns = 0
_evict_node(node.id) _evict_node(node.id)
db.commit() db.commit()
@@ -365,8 +412,12 @@ def _refresh_body() -> dict:
elif node.status == STATUS_ALIVE: elif node.status == STATUS_ALIVE:
alive_ids.append(node.id) alive_ids.append(node.id)
for node in existing.values(): for node in existing.values():
if node.status == STATUS_ALIVE and node.id not in alive_ids and node.id not in new_ids: if node.id in alive_ids or node.id in new_ids or node.id in dead_ids:
continue
if node.status == STATUS_ALIVE:
alive_ids.append(node.id) alive_ids.append(node.id)
elif node.status == STATUS_NEW:
new_ids.append(node.id)
db.commit() db.commit()
probe_ids = _pick_probe_ids(db, new_ids, alive_ids, dead_ids) probe_ids = _pick_probe_ids(db, new_ids, alive_ids, dead_ids)
nodes = [db.get(ProxyNode, node_id) for node_id in probe_ids] nodes = [db.get(ProxyNode, node_id) for node_id in probe_ids]
@@ -389,16 +440,7 @@ def _refresh_body() -> dict:
node = db.get(ProxyNode, node_id) node = db.get(ProxyNode, node_id)
if node is None: if node is None:
continue continue
node.last_checked_at = _now() _apply_probe(node, ok, latency, reason)
node.latency_ms = latency
if ok:
node.status = STATUS_ALIVE
node.last_ok_at = node.last_checked_at
node.fail_reason = ""
else:
node.status = STATUS_DEAD
node.fail_reason = reason or "失效"
_evict_node(node.id)
sync.checked_at = _now() sync.checked_at = _now()
sync.running = False sync.running = False
db.flush() db.flush()
@@ -421,42 +463,69 @@ def _refresh_body() -> dict:
return sync_view(db) return sync_view(db)
def _aware(value: datetime | None) -> datetime | None:
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
def _load_nodes(db: Session, ids: list[int]) -> list[ProxyNode]:
nodes: list[ProxyNode] = []
seen: set[int] = set()
for node_id in ids:
if node_id in seen:
continue
seen.add(node_id)
node = db.get(ProxyNode, node_id)
if node is not None:
nodes.append(node)
return nodes
def _unchecked_first(node: ProxyNode) -> tuple:
checked = _aware(node.last_checked_at)
return (checked is not None, checked or datetime.min.replace(tzinfo=timezone.utc), node.id)
def _pick_probe_ids(db: Session, new_ids: list[int], alive_ids: list[int], dead_ids: list[int] | None = None) -> list[int]: def _pick_probe_ids(db: Session, new_ids: list[int], alive_ids: list[int], dead_ids: list[int] | None = None) -> list[int]:
new_nodes = _load_nodes(db, new_ids)
new_nodes.sort(key=_unchecked_first)
alive_nodes = _load_nodes(db, alive_ids)
alive_nodes.sort(key=_unchecked_first)
reserve = min(ALIVE_REPROBE_SLOTS, len(alive_nodes))
new_budget = MAX_PROBES - reserve
ordered: list[int] = [] ordered: list[int] = []
seen: set[int] = set() seen: set[int] = set()
for node_id in new_ids:
if node_id not in seen: def add(node_id: int) -> None:
seen.add(node_id) if node_id in seen or len(ordered) >= MAX_PROBES:
ordered.append(node_id) return
if len(ordered) >= MAX_PROBES: seen.add(node_id)
return ordered[:MAX_PROBES] ordered.append(node_id)
alive_nodes = [
node for node in new_nodes:
for node in (db.get(ProxyNode, node_id) for node_id in alive_ids) if len(ordered) >= new_budget:
if node is not None break
] add(node.id)
alive_nodes.sort(key=lambda node: (node.last_checked_at is not None, node.last_checked_at or _now(), node.id))
for node in alive_nodes: for node in alive_nodes:
if node.id in seen:
continue
seen.add(node.id)
ordered.append(node.id)
if len(ordered) >= MAX_PROBES: if len(ordered) >= MAX_PROBES:
break break
add(node.id)
for node in new_nodes:
if len(ordered) >= MAX_PROBES:
break
add(node.id)
cutoff = _now() - timedelta(minutes=30) cutoff = _now() - timedelta(minutes=30)
for node_id in dead_ids or []: for node_id in dead_ids or []:
if len(ordered) >= MAX_PROBES or node_id in seen: if len(ordered) >= MAX_PROBES or node_id in seen:
continue continue
node = db.get(ProxyNode, node_id) node = db.get(ProxyNode, node_id)
checked = node.last_checked_at if node is not None else None checked = _aware(node.last_checked_at) if node is not None else None
if checked is None: if checked is None or checked > cutoff:
continue continue
if checked.tzinfo is None: add(node_id)
checked = checked.replace(tzinfo=timezone.utc)
if checked > cutoff:
continue
seen.add(node_id)
ordered.append(node_id)
return ordered return ordered
@@ -489,7 +558,8 @@ def _apply_probe(node: ProxyNode, ok: bool, latency: int, reason: str) -> None:
node.fail_reason = "" node.fail_reason = ""
else: else:
node.status = STATUS_DEAD node.status = STATUS_DEAD
node.fail_reason = (reason or "失效")[:200] node.fail_reason = _clip_reason(reason)
node.assigns = 0
_evict_node(node.id) _evict_node(node.id)
@@ -525,8 +595,10 @@ def request_probe(ids: list[int] | None = None) -> dict:
_probe_state["count"] = int(result.get("count") or 0) _probe_state["count"] = int(result.get("count") or 0)
_probe_state["error"] = "" _probe_state["error"] = ""
except Exception as exc: except Exception as exc:
log.warning("代理探测失败:%s", exc, exc_info=True)
with _probe_guard: with _probe_guard:
_probe_state["error"] = str(exc)[:200] text = str(exc).strip() or "探测失败"
_probe_state["error"] = text[:200]
finally: finally:
with _probe_guard: with _probe_guard:
_probe_state["running"] = False _probe_state["running"] = False
@@ -597,8 +669,19 @@ def request_refresh() -> dict:
return payload return payload
def _reset_pool_running() -> None:
with _probe_guard:
_probe_state["running"] = False
with SessionLocal() as db:
row = db.get(ProxyPoolSync, 1)
if row is not None and row.running:
row.running = False
db.commit()
def start_proxy_pool() -> threading.Event: def start_proxy_pool() -> threading.Event:
global _stop global _stop
_reset_pool_running()
stop = threading.Event() stop = threading.Event()
_stop = stop _stop = stop
+2 -3
View File
@@ -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))
+1 -3
View File
@@ -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,
"", "",
"", "",