Compare commits
2
Commits
019e75a95e
...
05f2396e35
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05f2396e35 | ||
|
|
8504ff5e85 |
@@ -462,15 +462,14 @@ def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db))
|
||||
|
||||
@app.get("/api/settings/study-control")
|
||||
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
|
||||
|
||||
employee_id = _signed_in(request, db)
|
||||
account = db.get(Account, employee_id)
|
||||
if account is None:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
status = autostudy_status()
|
||||
live = dict((status.get("users") or {}).get(employee_id) or {})
|
||||
live = account_status(employee_id)
|
||||
if settle(account, live):
|
||||
db.commit()
|
||||
return stamp_frame(employee_id, assemble(account, live))
|
||||
|
||||
+177
-100
@@ -94,6 +94,18 @@ def autostudy_status() -> dict:
|
||||
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:
|
||||
try:
|
||||
from euniv.study_push import notify
|
||||
@@ -179,10 +191,7 @@ class WorkerView:
|
||||
self._origin = 0.0
|
||||
|
||||
def update(self, **kw: object) -> None:
|
||||
course = kw.get("course")
|
||||
marker = kw.get("knowledge_id")
|
||||
if not isinstance(marker, str) or not marker:
|
||||
marker = course if isinstance(course, str) else ""
|
||||
if isinstance(marker, str) and marker and marker != self._course:
|
||||
self._course = marker
|
||||
self.sent = 0
|
||||
@@ -460,6 +469,18 @@ def _release_pool(employee_id: str, pool: bool) -> None:
|
||||
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:
|
||||
"""从账号列表行提取一次凭据。之后 work 只用这份拷贝,不再读账号表。"""
|
||||
from euniv.crypto import decrypt_secret
|
||||
@@ -472,16 +493,7 @@ def _job_from_account(row) -> tuple | None:
|
||||
pool = uses_pool(row)
|
||||
target = int(target_raw) if target_raw is not None else 600
|
||||
if target <= 0:
|
||||
return None
|
||||
try:
|
||||
proxy = bind_url(row)
|
||||
if pool and not proxy and employee_id:
|
||||
_set_user_status(employee_id, message="正在直连")
|
||||
except Exception as exc:
|
||||
log.warning("用户 %s 凭据无法读取: %s", employee_id, exc)
|
||||
_release_pool(employee_id, pool)
|
||||
if employee_id:
|
||||
_set_user_status(employee_id, state="学习失败", message="凭据无法读取")
|
||||
return None
|
||||
try:
|
||||
password = decrypt_secret(password_cipher)
|
||||
@@ -495,6 +507,16 @@ def _job_from_account(row) -> tuple | None:
|
||||
if not isinstance(credential, dict):
|
||||
_release_pool(employee_id, pool)
|
||||
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:
|
||||
_targets[employee_id] = target
|
||||
return (
|
||||
@@ -536,6 +558,24 @@ def _course_type(kind: str, path: str) -> str:
|
||||
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:
|
||||
compact = compact_id(kid)
|
||||
ctype = _course_type(kind, path)
|
||||
@@ -603,12 +643,16 @@ async def wait_stop(timeout: float, *events: asyncio.Event) -> bool:
|
||||
if timeout <= 0:
|
||||
return False
|
||||
tasks = [asyncio.create_task(event.wait()) for event in events]
|
||||
done, pending = await asyncio.wait(tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
if pending:
|
||||
await asyncio.gather(*pending, return_exceptions=True)
|
||||
return bool(done)
|
||||
try:
|
||||
done, _pending = await asyncio.wait(
|
||||
tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
return bool(done)
|
||||
finally:
|
||||
for task in tasks:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
|
||||
class HoursWatcher:
|
||||
@@ -998,31 +1042,9 @@ class StudySession:
|
||||
return 0
|
||||
return len(re.findall(r'["\']([^"\']+\.oss\.js)["\']', resp.text))
|
||||
|
||||
async def scorm_extract_answers(self, kid: str) -> list[dict]:
|
||||
assert self._client is not None
|
||||
compact = compact_id(kid)
|
||||
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 scorm_extract_answers(self, kid: str) -> int:
|
||||
"""只取页文件列表长度,不下载课件。索引失败返回 0,不让整门课失败。"""
|
||||
return await self.scorm_page_count(kid)
|
||||
|
||||
async def month_hours_text(self) -> str:
|
||||
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,
|
||||
interval: int, stop: asyncio.Event, 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 30))
|
||||
if step <= 0:
|
||||
step = 30
|
||||
view = 0
|
||||
started = False
|
||||
stall = _Stall()
|
||||
pending = snapshot
|
||||
if not getattr(session, "_play_logged", False):
|
||||
session._play_logged = True
|
||||
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):
|
||||
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:
|
||||
_touch(worker, ok=False)
|
||||
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,
|
||||
page_size: int, interval: int, stop: asyncio.Event,
|
||||
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))
|
||||
if step <= 0:
|
||||
step = 120
|
||||
started = False
|
||||
stall = _Stall()
|
||||
pending = snapshot
|
||||
while not _halted(stop, hours):
|
||||
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:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
@@ -1240,15 +1274,10 @@ async def _study_document(session: StudySession, kid: str, pkg_id: str,
|
||||
return
|
||||
try:
|
||||
await session.submit_document_heartbeat(kid, pkg_id, page_size, step, view)
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
schedule = _progress_of(progress)
|
||||
_beat(worker, schedule, ok=True)
|
||||
if _completed(progress):
|
||||
await hours.refresh()
|
||||
return
|
||||
if stall.stuck(schedule, step):
|
||||
raise RuntimeError("进度长时间没有变化")
|
||||
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,
|
||||
interval: int, stop: asyncio.Event, hours: HoursWatcher,
|
||||
user_id: str, org_id: str, worker: WorkerView | None = None,
|
||||
study_time: int | None = None, scorm_id: str = "") -> None:
|
||||
study_time: int | None = None, scorm_id: str = "",
|
||||
snapshot: dict | None = None) -> None:
|
||||
import uuid as _uuid
|
||||
step = int(study_time if study_time is not None else (interval if interval > 0 else 120))
|
||||
if step <= 0:
|
||||
step = 120
|
||||
try:
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
if snapshot is not None:
|
||||
progress = snapshot
|
||||
else:
|
||||
try:
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
except Exception:
|
||||
_touch(worker, ok=False)
|
||||
raise
|
||||
schedule = _progress_of(progress)
|
||||
_touch(worker, progress=schedule, ok=True)
|
||||
if _completed(progress):
|
||||
@@ -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,
|
||||
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)
|
||||
progress = await session.update_progress(kid, pkg_id)
|
||||
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,
|
||||
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)
|
||||
if _completed(pkg):
|
||||
_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):
|
||||
log.info("跳过没有编号的章节 %s", ch_title)
|
||||
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)
|
||||
_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:
|
||||
params = await _open_play(session, _package_chapter_path(kid, ch_kid, ch_type))
|
||||
wait, study_time, page_size = _interval_plan(ch_type, intervals, auto_mode, params)
|
||||
if is_video:
|
||||
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)
|
||||
else:
|
||||
session._video_cap = 0
|
||||
await _study_document(
|
||||
session, ch_kid, kid, page_size, wait, stop, hours, worker, study_time=study_time,
|
||||
)
|
||||
@@ -1605,6 +1645,7 @@ class AutoStudyWorker:
|
||||
if not course_list:
|
||||
_set_user_status(eid, state="学习失败", message="没有可用的课程")
|
||||
drop_work(eid)
|
||||
_release_pool_later(eid, bool(job[6]))
|
||||
return False
|
||||
_set_user_status(eid, state="排队中", course="")
|
||||
want_work(eid)
|
||||
@@ -1620,15 +1661,20 @@ class AutoStudyWorker:
|
||||
try:
|
||||
from admin.settings import hours_source_of
|
||||
|
||||
hours_source = await asyncio.to_thread(hours_source_of)
|
||||
intervals, auto_mode = await asyncio.to_thread(_current_intervals)
|
||||
if int(target or 0) <= 0:
|
||||
if use_pool:
|
||||
await asyncio.to_thread(_release_pool, emp_id, True)
|
||||
return
|
||||
if not course_list:
|
||||
_set_user_status(emp_id, state="学习失败", message="没有可用的课程")
|
||||
if use_pool:
|
||||
await asyncio.to_thread(_release_pool, emp_id, True)
|
||||
return
|
||||
hours_source = await asyncio.to_thread(hours_source_of)
|
||||
assert self._sem is not None
|
||||
await self._study_user(
|
||||
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:
|
||||
log.warning("用户 %s 自动学习失败: %s", emp_id, exc)
|
||||
@@ -1649,8 +1695,8 @@ class AutoStudyWorker:
|
||||
|
||||
async def _study_user(self, employee_id: str, target: int,
|
||||
password: str, credential: dict, proxy: str | None,
|
||||
workers: int, use_pool: bool, course_list: list, intervals: dict,
|
||||
auto_mode: bool, hours_source: str, sem: asyncio.Semaphore) -> None:
|
||||
workers: int, use_pool: bool, course_list: list,
|
||||
hours_source: str, sem: asyncio.Semaphore) -> None:
|
||||
assert self._async_stop is not None
|
||||
user_stop = asyncio.Event()
|
||||
with _halt_lock:
|
||||
@@ -1660,6 +1706,18 @@ class AutoStudyWorker:
|
||||
_user_halts[employee_id] = user_stop
|
||||
_running.add(employee_id)
|
||||
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():
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
return
|
||||
@@ -1671,14 +1729,17 @@ class AutoStudyWorker:
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
return
|
||||
if not token:
|
||||
message = "请重新登录" if reason == "expired" else "无法连接学习平台"
|
||||
_set_user_status(employee_id, state="会话失效", message=message)
|
||||
if reason == "expired":
|
||||
_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
|
||||
|
||||
async with StudySession(
|
||||
token, cookies, proxy=proxy, employee_id=employee_id, use_pool=use_pool
|
||||
) as session:
|
||||
session._employee_id = employee_id # type: ignore[attr-defined]
|
||||
session._request_limit = sem
|
||||
if user_stop.is_set():
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
@@ -1690,8 +1751,7 @@ class AutoStudyWorker:
|
||||
ticker = asyncio.create_task(hours.ticker(self._async_stop))
|
||||
try:
|
||||
failed = await self._study_courses(
|
||||
session, employee_id, course_list, intervals,
|
||||
auto_mode, hours, user_id, org_id, workers)
|
||||
session, employee_id, course_list, hours, user_id, org_id, workers)
|
||||
if hours.reached or user_stop.is_set() or self._async_stop.is_set():
|
||||
return
|
||||
if failed:
|
||||
@@ -1718,8 +1778,7 @@ class AutoStudyWorker:
|
||||
await asyncio.to_thread(release, employee_id)
|
||||
|
||||
async def _study_courses(self, session: StudySession, employee_id: str,
|
||||
course_list: list, intervals: dict,
|
||||
auto_mode: bool, hours: HoursWatcher,
|
||||
course_list: list, hours: HoursWatcher,
|
||||
user_id: str, org_id: str, workers: int) -> int:
|
||||
"""N 个协程顺着课程表往下领,已完成的跳过,未完成的发心跳。"""
|
||||
assert self._async_stop is not None
|
||||
@@ -1728,6 +1787,7 @@ class AutoStudyWorker:
|
||||
finished = await asyncio.to_thread(_load_finished, employee_id)
|
||||
streak = {"n": 0, "wait": 60}
|
||||
failed = {"n": 0}
|
||||
skipped = {"n": 0}
|
||||
streak_lock = asyncio.Lock()
|
||||
|
||||
async def worker_loop(index: int) -> None:
|
||||
@@ -1741,7 +1801,7 @@ class AutoStudyWorker:
|
||||
path, title, kind = item
|
||||
result = await self._study_one_course(
|
||||
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
|
||||
async with streak_lock:
|
||||
@@ -1761,25 +1821,23 @@ class AutoStudyWorker:
|
||||
if pause and await wait_stop(pause, self._async_stop, hours.user_stop):
|
||||
return
|
||||
|
||||
try:
|
||||
async with asyncio.TaskGroup() as group:
|
||||
for index in range(1, count + 1):
|
||||
group.create_task(worker_loop(index))
|
||||
except ExceptionGroup:
|
||||
log.warning("用户 %s 有学习协程没有跑完", employee_id)
|
||||
async with asyncio.TaskGroup() as group:
|
||||
for index in range(1, count + 1):
|
||||
group.create_task(worker_loop(index))
|
||||
return failed["n"]
|
||||
|
||||
async def _study_one_course(self, session: StudySession, employee_id: str,
|
||||
path: str, title: str, kind: str,
|
||||
intervals: dict, auto_mode: bool,
|
||||
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
|
||||
if _halted(self._async_stop, hours):
|
||||
return "stop"
|
||||
ctype = _course_type(kind, path)
|
||||
if ctype == "unknown":
|
||||
log.info("跳过未知类型课程 %s", title or path)
|
||||
_note_unknown(skipped, title or path)
|
||||
return "skip"
|
||||
kid = _knowledge_id_from_path(path)
|
||||
if not kid:
|
||||
@@ -1787,29 +1845,44 @@ class AutoStudyWorker:
|
||||
known = finished if finished is not None else set()
|
||||
if kid in known:
|
||||
return "skip"
|
||||
intervals, auto_mode = await asyncio.to_thread(_current_intervals)
|
||||
|
||||
_set_user_status(employee_id, course=title)
|
||||
|
||||
try:
|
||||
progress = await session.update_progress(kid, "")
|
||||
schedule = _progress_of(progress)
|
||||
_touch(worker, course=title, 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"
|
||||
except SessionExpired:
|
||||
hours.user_stop.set()
|
||||
_touch(worker, ok=False)
|
||||
_set_user_status(employee_id, state="会话失效", message="请重新登录")
|
||||
log.info("用户 %s 会话失效", employee_id)
|
||||
return "stop"
|
||||
except Exception as exc:
|
||||
_touch(worker, ok=False)
|
||||
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)
|
||||
session._referer = f"{EUNIV}{play_path}"
|
||||
session._play_logged = False
|
||||
params = await _open_play(session, play_path)
|
||||
if ctype == "package":
|
||||
_touch(worker, course=title, knowledge_id=kid, progress=0, ok=True)
|
||||
ok = await _study_package(session, kid, intervals, auto_mode,
|
||||
self._async_stop, hours, user_id, org_id, worker)
|
||||
ok = await _study_package(
|
||||
session, kid, intervals, auto_mode,
|
||||
self._async_stop, hours, user_id, org_id, worker, skipped,
|
||||
)
|
||||
if _halted(self._async_stop, hours):
|
||||
return "stop"
|
||||
if not ok:
|
||||
@@ -1822,8 +1895,11 @@ class AutoStudyWorker:
|
||||
session._single_limit = str(params.get("isSingle") or "") == "1"
|
||||
if ctype == "video":
|
||||
session._video_cap = _whole(params.get("standardStudyHours"), 0)
|
||||
else:
|
||||
session._video_cap = 0
|
||||
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
|
||||
if ctype == "document" and not _uses_new_timer(params):
|
||||
standard = _whole(params.get("standardStudyHours"), 0)
|
||||
@@ -1838,18 +1914,20 @@ class AutoStudyWorker:
|
||||
return "studied"
|
||||
if ctype == "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":
|
||||
await _study_document(
|
||||
session, kid, "", page_size, wait, self._async_stop, hours, worker,
|
||||
study_time=study_time,
|
||||
study_time=study_time, snapshot=progress,
|
||||
)
|
||||
elif ctype == "scorm":
|
||||
await _study_scorm(
|
||||
session, kid, "", wait, self._async_stop, hours,
|
||||
str(params.get("userID") or ""), str(params.get("orgID") or ""),
|
||||
worker, study_time=study_time, scorm_id=str(params.get("scormId") or ""),
|
||||
snapshot=progress,
|
||||
)
|
||||
if _halted(self._async_stop, hours):
|
||||
return "stop"
|
||||
@@ -1866,7 +1944,6 @@ class AutoStudyWorker:
|
||||
_touch(worker, ok=False)
|
||||
log.warning("用户 %s 课程 %s 异常: %s", employee_id, title, exc)
|
||||
return "fail"
|
||||
return "skip"
|
||||
|
||||
|
||||
# ── 数据库更新 ──
|
||||
|
||||
+58
-15
@@ -15,6 +15,7 @@ log = logging.getLogger(__name__)
|
||||
|
||||
CHINA = {"cn", "chn", "china", "中国"}
|
||||
_SOURCE_TITLES = {"proxyhub": "ProxyHub"}
|
||||
MAX_RESPONSE_BYTES = 1_048_576
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -163,19 +164,57 @@ def parse_proxyhub_result(payload: object) -> list[ProxyCandidate]:
|
||||
return []
|
||||
|
||||
|
||||
def _read_mcp(response: httpx.Response) -> dict:
|
||||
ctype = (response.headers.get("content-type") or "").lower()
|
||||
if "json" in ctype:
|
||||
payload = response.json()
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
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 "{}")
|
||||
def _json_dict(text: str) -> dict:
|
||||
try:
|
||||
payload = json.loads(text or "{}")
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
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):
|
||||
name = "proxyhub"
|
||||
url = "https://proxyhub.me/api/mcp"
|
||||
@@ -185,9 +224,13 @@ class ProxyHubCollector(Collector):
|
||||
def collect(self) -> list[ProxyCandidate]:
|
||||
items: list[ProxyCandidate] = []
|
||||
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):
|
||||
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
|
||||
|
||||
def _list(self, kind: str) -> list[ProxyCandidate]:
|
||||
@@ -213,9 +256,9 @@ class ProxyHubCollector(Collector):
|
||||
"Mcp-Name": "list_proxies",
|
||||
}
|
||||
with httpx.Client(timeout=20, follow_redirects=True, trust_env=False) as client:
|
||||
response = client.post(self.url, headers=headers, json=body)
|
||||
response.raise_for_status()
|
||||
return parse_proxyhub_result(_read_mcp(response))
|
||||
with client.stream("POST", self.url, headers=headers, json=body) as response:
|
||||
response.raise_for_status()
|
||||
return parse_proxyhub_result(_read_mcp(response))
|
||||
|
||||
|
||||
register(ProxyHubCollector())
|
||||
|
||||
+58
-15
@@ -26,15 +26,42 @@ def canonical_scheme(scheme: str | None) -> str:
|
||||
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:
|
||||
"""手填和采集都只接受公网地址。"""
|
||||
address = (host or "").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:
|
||||
addresses = [ipaddress.ip_address(address)]
|
||||
addresses = [ipaddress.ip_address(bare)]
|
||||
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("代理地址不合法")
|
||||
try:
|
||||
found = socket.getaddrinfo(address, None)
|
||||
@@ -48,24 +75,35 @@ def assert_public_host(host: str) -> None:
|
||||
continue
|
||||
if not addresses:
|
||||
raise ProxyError("代理地址无法解析")
|
||||
for ip in 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("代理只允许公网地址")
|
||||
_reject_private(addresses)
|
||||
|
||||
|
||||
def _host_for_url(host: str) -> str:
|
||||
bare = _unwrap_host(host)
|
||||
try:
|
||||
ipaddress.IPv6Address(host)
|
||||
ipaddress.IPv6Address(bare)
|
||||
except ValueError:
|
||||
return host
|
||||
return f"[{host}]"
|
||||
return host.strip() or 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:
|
||||
@@ -79,6 +117,8 @@ def parse_proxy(value: str | None) -> str | None:
|
||||
scheme = canonical_scheme(parsed.scheme)
|
||||
if scheme not in SCHEMES:
|
||||
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
|
||||
if parsed.path not in ("", "/") or parsed.query or parsed.fragment:
|
||||
raise ProxyError("代理地址不合法")
|
||||
if not parsed.hostname:
|
||||
raise ProxyError("代理地址不完整")
|
||||
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()
|
||||
if not address or "://" in address or any(ch.isspace() for ch in address):
|
||||
raise ProxyError("请填写代理地址")
|
||||
if len(address) > 255:
|
||||
raise ProxyError("代理地址过长")
|
||||
address = _written_host(address)
|
||||
if len(address) > 255:
|
||||
raise ProxyError("代理地址过长")
|
||||
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
|
||||
|
||||
+136
-53
@@ -11,6 +11,7 @@ from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import case, func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API
|
||||
@@ -30,6 +31,7 @@ LATENCY_LIMIT = 3.0
|
||||
LATENCY_LIMIT_MS = 3000
|
||||
PROBE_CONCURRENCY = 16
|
||||
MAX_PROBES = 80
|
||||
ALIVE_REPROBE_SLOTS = 20
|
||||
MAX_SWITCHES = 8
|
||||
PROBE_URL = EUNIV + "/"
|
||||
PROBE_URLS = (
|
||||
@@ -62,10 +64,20 @@ def _url(node: ProxyNode) -> str:
|
||||
|
||||
def _sync_row(db: Session) -> ProxyPoolSync:
|
||||
row = db.get(ProxyPoolSync, 1)
|
||||
if row is None:
|
||||
row = ProxyPoolSync(id=1)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
if row is not None:
|
||||
return row
|
||||
row = ProxyPoolSync(id=1)
|
||||
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
|
||||
|
||||
|
||||
@@ -193,8 +205,6 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
|
||||
reasons.append(_short_reason(exc))
|
||||
except Exception as 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)))
|
||||
if reasons:
|
||||
return False, average, reasons[0]
|
||||
@@ -218,15 +228,28 @@ def _direct_reaches_target() -> bool:
|
||||
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:
|
||||
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__
|
||||
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:
|
||||
@@ -267,24 +290,47 @@ def acquire(employee_id: str) -> str | None:
|
||||
if held is not None and held.status == STATUS_ALIVE:
|
||||
return _url(held)
|
||||
_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())
|
||||
if not nodes:
|
||||
db.commit()
|
||||
return None
|
||||
load = {node.id: 0 for node in nodes}
|
||||
for node_id in _holds.values():
|
||||
if node_id in load:
|
||||
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]
|
||||
_holds[key] = pick.id
|
||||
pick.assigns = int(pick.assigns or 0) + 1
|
||||
pick.assigns = load[pick.id] + 1
|
||||
db.commit()
|
||||
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:
|
||||
with _assign_lock:
|
||||
_holds.pop((employee_id or "").strip(), None)
|
||||
key = (employee_id or "").strip()
|
||||
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:
|
||||
@@ -300,8 +346,9 @@ def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = ""
|
||||
if held == node.id:
|
||||
_holds.pop(key, None)
|
||||
node.status = STATUS_DEAD
|
||||
node.fail_reason = (reason or "失效")[:200]
|
||||
node.fail_reason = _clip_reason(reason)
|
||||
node.last_checked_at = _now()
|
||||
node.assigns = 0
|
||||
_evict_node(node.id)
|
||||
db.commit()
|
||||
|
||||
@@ -365,8 +412,12 @@ def _refresh_body() -> dict:
|
||||
elif node.status == STATUS_ALIVE:
|
||||
alive_ids.append(node.id)
|
||||
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)
|
||||
elif node.status == STATUS_NEW:
|
||||
new_ids.append(node.id)
|
||||
db.commit()
|
||||
probe_ids = _pick_probe_ids(db, new_ids, alive_ids, dead_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)
|
||||
if node is None:
|
||||
continue
|
||||
node.last_checked_at = _now()
|
||||
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)
|
||||
_apply_probe(node, ok, latency, reason)
|
||||
sync.checked_at = _now()
|
||||
sync.running = False
|
||||
db.flush()
|
||||
@@ -421,42 +463,69 @@ def _refresh_body() -> dict:
|
||||
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]:
|
||||
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] = []
|
||||
seen: set[int] = set()
|
||||
for node_id in new_ids:
|
||||
if node_id not in seen:
|
||||
seen.add(node_id)
|
||||
ordered.append(node_id)
|
||||
if len(ordered) >= MAX_PROBES:
|
||||
return ordered[:MAX_PROBES]
|
||||
alive_nodes = [
|
||||
node
|
||||
for node in (db.get(ProxyNode, node_id) for node_id in alive_ids)
|
||||
if node is not None
|
||||
]
|
||||
alive_nodes.sort(key=lambda node: (node.last_checked_at is not None, node.last_checked_at or _now(), node.id))
|
||||
|
||||
def add(node_id: int) -> None:
|
||||
if node_id in seen or len(ordered) >= MAX_PROBES:
|
||||
return
|
||||
seen.add(node_id)
|
||||
ordered.append(node_id)
|
||||
|
||||
for node in new_nodes:
|
||||
if len(ordered) >= new_budget:
|
||||
break
|
||||
add(node.id)
|
||||
for node in alive_nodes:
|
||||
if node.id in seen:
|
||||
continue
|
||||
seen.add(node.id)
|
||||
ordered.append(node.id)
|
||||
if len(ordered) >= MAX_PROBES:
|
||||
break
|
||||
add(node.id)
|
||||
for node in new_nodes:
|
||||
if len(ordered) >= MAX_PROBES:
|
||||
break
|
||||
add(node.id)
|
||||
cutoff = _now() - timedelta(minutes=30)
|
||||
for node_id in dead_ids or []:
|
||||
if len(ordered) >= MAX_PROBES or node_id in seen:
|
||||
continue
|
||||
node = db.get(ProxyNode, node_id)
|
||||
checked = node.last_checked_at if node is not None else None
|
||||
if checked is None:
|
||||
checked = _aware(node.last_checked_at) if node is not None else None
|
||||
if checked is None or checked > cutoff:
|
||||
continue
|
||||
if checked.tzinfo is None:
|
||||
checked = checked.replace(tzinfo=timezone.utc)
|
||||
if checked > cutoff:
|
||||
continue
|
||||
seen.add(node_id)
|
||||
ordered.append(node_id)
|
||||
add(node_id)
|
||||
return ordered
|
||||
|
||||
|
||||
@@ -489,7 +558,8 @@ def _apply_probe(node: ProxyNode, ok: bool, latency: int, reason: str) -> None:
|
||||
node.fail_reason = ""
|
||||
else:
|
||||
node.status = STATUS_DEAD
|
||||
node.fail_reason = (reason or "失效")[:200]
|
||||
node.fail_reason = _clip_reason(reason)
|
||||
node.assigns = 0
|
||||
_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["error"] = ""
|
||||
except Exception as exc:
|
||||
log.warning("代理探测失败:%s", exc, exc_info=True)
|
||||
with _probe_guard:
|
||||
_probe_state["error"] = str(exc)[:200]
|
||||
text = str(exc).strip() or "探测失败"
|
||||
_probe_state["error"] = text[:200]
|
||||
finally:
|
||||
with _probe_guard:
|
||||
_probe_state["running"] = False
|
||||
@@ -597,8 +669,19 @@ def request_refresh() -> dict:
|
||||
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:
|
||||
global _stop
|
||||
_reset_pool_running()
|
||||
stop = threading.Event()
|
||||
_stop = stop
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ def settle(account, live: dict | None = None, now: datetime | None = None) -> bo
|
||||
|
||||
|
||||
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.models import Account
|
||||
|
||||
@@ -186,8 +186,7 @@ def payload_for(employee_id: str) -> dict:
|
||||
account = db.get(Account, key)
|
||||
if account is None:
|
||||
return empty
|
||||
status = autostudy_status()
|
||||
live = dict((status.get("users") or {}).get(key) or {})
|
||||
live = account_status(key)
|
||||
if settle(account, live):
|
||||
db.commit()
|
||||
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")
|
||||
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)
|
||||
first = autostudy_status()["users"]["u-total"]["workers"][0]["total"]
|
||||
assert first == 62
|
||||
@@ -933,8 +933,6 @@ def test_completed_course_skips_the_play_page(monkeypatch) -> None:
|
||||
f"/kng/view/video/{COMPACT_KID}.html",
|
||||
"已完成",
|
||||
"视频",
|
||||
{},
|
||||
False,
|
||||
watcher,
|
||||
"",
|
||||
"",
|
||||
|
||||
Reference in New Issue
Block a user