feat: 立即开始停止学习并整理学时历史与界面

This commit is contained in:
2026-11-15 04:16:40 +08:00
parent ce2d6e08dd
commit f0a2bdd854
25 changed files with 1748 additions and 580 deletions
+55
View File
@@ -23,6 +23,7 @@ from euniv.service import (
fetch_home_exams,
fetch_home_summary,
fetch_home_trainings,
fetch_study_history,
fetch_training_detail,
login_and_store,
revoke_credential,
@@ -57,6 +58,10 @@ class CourseWorkersBody(_BaseModel):
workers: int
class StudyControlBody(_BaseModel):
action: str
@asynccontextmanager
async def lifespan(_app: FastAPI):
init_db()
@@ -336,6 +341,56 @@ def autostudy_state(request: Request, db: Session = Depends(get_db)) -> dict:
return autostudy_status()
@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.study_control import view_of
employee_id = _signed_in(request, db)
account = db.get(Account, employee_id)
if account is None:
raise HTTPException(status_code=401, detail="未登录")
payload = view_of(account)
live = (autostudy_status().get("users") or {}).get(employee_id) or {}
payload["state"] = str(live.get("state") or "")
payload["course"] = str(live.get("course") or "")
payload["active"] = bool(live) and payload["state"] not in {"已达标", "已停止", "会话失效", "会话过期"}
if payload["active"]:
payload["started"] = True
return payload
@app.post("/api/settings/study-control")
def post_study_control(body: StudyControlBody, request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.autostudy import request_stop, request_wake
from euniv.study_control import start_now, stop_now
employee_id = _signed_in(request, db)
account = db.get(Account, employee_id)
if account is None:
raise HTTPException(status_code=401, detail="未登录")
action = (body.action or "").strip().lower()
if action == "start":
start_now(account)
db.commit()
request_wake()
elif action == "stop":
stop_now(account)
db.commit()
request_stop(employee_id)
else:
raise HTTPException(status_code=400, detail="请选择开始或停止")
return get_study_control(request, db)
@app.get("/api/home/history")
def home_history(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_study_history(db, _signed_in(request, db))
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/training")
def training_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
try:
+61 -12
View File
@@ -28,7 +28,7 @@ from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpir
from euniv.course_workers import of as course_workers_of
from euniv.models import Account, Course
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
from euniv.study_window import window_open
from euniv.study_control import eligible as study_eligible
log = logging.getLogger(__name__)
@@ -37,6 +37,9 @@ _HOURS_REFRESH_SECONDS = 300.0
_lock = threading.Lock()
_status: dict = {"running": False, "users": {}, "message": "", "updated_at": ""}
_halt_lock = threading.Lock()
_user_halts: dict[str, asyncio.Event] = {}
_worker = None
def autostudy_status() -> dict:
@@ -63,6 +66,30 @@ def _clear_user_status(employee_id: str) -> None:
_status.get("users", {}).pop(employee_id, None)
def request_stop(employee_id: str) -> None:
key = (employee_id or "").strip()
if not key:
return
with _halt_lock:
event = _user_halts.get(key)
if event is not None:
event.set()
_set_user_status(key, state="已停止", course="")
def request_wake() -> None:
worker = _worker
if worker is not None:
worker.wake()
def is_studying(employee_id: str) -> bool:
key = (employee_id or "").strip()
with _halt_lock:
event = _user_halts.get(key)
return event is not None and not event.is_set()
# ── 课程路径解析 ──
_ID_RE = re.compile(r"([0-9a-fA-F]{32})")
@@ -622,6 +649,7 @@ class AutoStudyWorker:
self._thread: threading.Thread | None = None
self._loop: asyncio.AbstractEventLoop | None = None
self._async_stop: asyncio.Event | None = None
self._kick: asyncio.Event | None = None
def start(self) -> None:
self._thread = threading.Thread(target=self._run_thread, name="euniv-autostudy", daemon=True)
@@ -632,10 +660,15 @@ class AutoStudyWorker:
if self._loop and self._async_stop:
self._loop.call_soon_threadsafe(self._async_stop.set)
def wake(self) -> None:
if self._loop and self._kick is not None:
self._loop.call_soon_threadsafe(self._kick.set)
def _run_thread(self) -> None:
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
self._async_stop = asyncio.Event()
self._kick = asyncio.Event()
try:
self._loop.run_until_complete(self._main_loop())
finally:
@@ -643,18 +676,20 @@ class AutoStudyWorker:
async def _main_loop(self) -> None:
assert self._async_stop is not None
await asyncio.sleep(15)
assert self._kick is not None
await wait_stop(15, self._async_stop, self._kick)
while not self._async_stop.is_set():
self._kick.clear()
try:
await self._run_cycle()
except Exception as exc:
log.exception("自动学习周期异常: %s", exc)
_set_status(message=f"异常: {exc}")
try:
await asyncio.wait_for(self._async_stop.wait(), timeout=random.uniform(300, 600))
if self._async_stop.is_set():
return
except asyncio.TimeoutError:
pass
if self._kick.is_set():
continue
await wait_stop(random.uniform(300, 600), self._async_stop, self._kick)
async def _run_cycle(self) -> None:
assert self._async_stop is not None
@@ -681,9 +716,13 @@ class AutoStudyWorker:
course_list = [(c.path, c.title, c.kind) for c in courses]
eligible = []
waiting = 0
paused = 0
for row in users:
if not window_open(row):
waiting += 1
if not study_eligible(row):
if getattr(row, "study_paused", False):
paused += 1
else:
waiting += 1
continue
target = row.monthly_target or 600
current = _parse_minutes(row.month_hours)
@@ -713,6 +752,8 @@ class AutoStudyWorker:
if not eligible:
if waiting:
_set_status(running=False, message="未到开始时间或已达标")
elif paused:
_set_status(running=False, message="任务已停止")
else:
_set_status(running=False, message="所有用户已达标或无有效凭据")
return
@@ -740,8 +781,17 @@ class AutoStudyWorker:
workers: int, use_pool: bool, course_list: list, intervals: dict,
auto_mode: bool, sem: asyncio.Semaphore) -> None:
assert self._async_stop is not None
user_stop = asyncio.Event()
with _halt_lock:
current = _user_halts.get(employee_id)
if current is not None and not current.is_set():
return
_user_halts[employee_id] = user_stop
try:
async with sem:
if user_stop.is_set():
_set_user_status(employee_id, state="已停止")
return
_set_user_status(employee_id, state="准备", course="")
loop = asyncio.get_event_loop()
token, user_id, org_id, cookies, proxy = await loop.run_in_executor(
@@ -755,7 +805,6 @@ class AutoStudyWorker:
) as session:
session._employee_id = employee_id # type: ignore[attr-defined]
_set_user_status(employee_id, state="学习中")
user_stop = asyncio.Event()
hours = HoursWatcher(session, employee_id, target, user_stop)
if await hours.refresh():
return
@@ -769,6 +818,9 @@ class AutoStudyWorker:
with contextlib.suppress(asyncio.CancelledError):
await ticker
finally:
with _halt_lock:
if _user_halts.get(employee_id) is user_stop:
_user_halts.pop(employee_id, None)
if use_pool:
from euniv.proxy_pool import release
@@ -861,9 +913,6 @@ def _update_month_hours(employee_id: str, hours: str) -> None:
# ── 启动入口 ──
_worker: AutoStudyWorker | None = None
def start_autostudy() -> AutoStudyWorker:
global _worker
w = AutoStudyWorker()
+90
View File
@@ -116,6 +116,45 @@ def _by_closeness(items: list[dict], key: str) -> list[dict]:
return ordered
_HISTORY_ROW_RE = re.compile(
r'<tr class="alter">\s*'
r'<td class="text-left" title="([^"]*)">([\s\S]*?)</td>\s*'
r'<td class="text-center">\s*(\d+)\s*</td>\s*'
r'<td class="text-center">\s*([^<]+?)\s*</td>',
re.I,
)
def _history_api_item(row: object) -> dict | None:
if not isinstance(row, dict):
return None
title = str(row.get("targetName") or row.get("title") or row.get("kngName") or "").strip()
studied_at = str(row.get("studyDate") or row.get("studiedAt") or row.get("createTime") or "").strip()
raw_minutes = row.get("duration")
if raw_minutes is None:
raw_minutes = row.get("studyHour")
minutes: int | None = None
if isinstance(raw_minutes, bool):
minutes = None
elif isinstance(raw_minutes, (int, float)):
minutes = int(raw_minutes)
elif isinstance(raw_minutes, str) and raw_minutes.strip():
match = re.search(r"(\d+)", raw_minutes)
minutes = int(match.group(1)) if match else None
path = str(row.get("url") or row.get("knowledgeUrl") or row.get("targetUrl") or "").strip()
knowledge_id = str(row.get("knowledgeId") or row.get("kngId") or "").replace("-", "")
if not path and len(knowledge_id) == 32:
path = f"/kng/view/document/{knowledge_id}.html"
if not title and not studied_at:
return None
return {
"title": title,
"minutes": minutes,
"studied_at": studied_at,
"path": path,
}
def parse_training_cards(page: str, status: str) -> list[dict]:
items = []
for block in re.findall(r"<li class='el-plan-li-3'[\s\S]*?</li>", page):
@@ -756,6 +795,57 @@ class EunivClient:
def month_hours(self) -> str:
return self._period_minutes().get("month", "")
def study_history(self) -> list[dict]:
"""读取「我的学时」列表:来源、获得学时(分钟)、日期。"""
try:
items = self._study_history_api()
except Exception:
items = None
if items is not None:
return items
return self._study_history_page()
def _study_history_api(self) -> list[dict] | None:
response = self._request(
"POST",
f"{STUDY_API}/v1/styhis/studyhistory/daily/search",
json={"pageable": False},
)
payload = response.json()
if not isinstance(payload, dict):
return None
rows = payload.get("datas")
if rows is None:
rows = payload.get("data")
if not isinstance(rows, list):
return None
items = []
for row in rows:
item = _history_api_item(row)
if item is not None:
items.append(item)
return items
def _study_history_page(self) -> list[dict]:
text = self._study_period_page()
items = []
for match in _HISTORY_ROW_RE.finditer(text):
title = unescape(match.group(1) or "").strip()
cell = match.group(2) or ""
minutes = int(match.group(3))
studied_at = unescape(match.group(4) or "").strip()
path_match = re.search(r"GoToSource\('([^']+)'", cell)
path = path_match.group(1) if path_match else ""
items.append(
{
"title": title,
"minutes": minutes,
"studied_at": studied_at,
"path": path,
}
)
return items
def _period_minutes(self) -> dict[str, str]:
text = self._study_period_page()
found = {}
+2
View File
@@ -58,6 +58,8 @@ class Account(Base):
study_start_second: Mapped[int] = mapped_column(nullable=False, default=0, server_default="0")
course_workers: Mapped[int] = mapped_column(nullable=False, default=1, server_default="1")
use_proxy_pool: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
study_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
study_ignore_window: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
class ProxyNode(Base):
+97 -11
View File
@@ -13,7 +13,7 @@ import httpx
from sqlalchemy import case, func, select
from sqlalchemy.orm import Session
from euniv.client import EUNIV, USER_AGENT
from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API
from euniv.collectors import collect_all, is_china, source_title
from euniv.db import SessionLocal
from euniv.models import ProxyNode, ProxyPoolSync
@@ -21,6 +21,10 @@ from euniv.proxy import build_proxy_url
log = logging.getLogger(__name__)
class ProxyProbeError(ValueError):
"""延迟测试目标不存在。"""
FETCH_INTERVAL = 300
LATENCY_LIMIT = 3.0
LATENCY_LIMIT_MS = 3000
@@ -28,6 +32,11 @@ PROBE_CONCURRENCY = 16
MAX_PROBES = 80
MAX_SWITCHES = 8
PROBE_URL = EUNIV + "/"
PROBE_URLS = (
EUNIV + "/",
STUDY_API + "/",
YXT_API + "/",
)
STATUS_ALIVE = "alive"
STATUS_DEAD = "dead"
STATUS_NEW = "new"
@@ -154,7 +163,8 @@ def page(db: Session, q: str = "", status: str = "", offset: int = 0, limit: int
def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
url = build_proxy_url(scheme, host, port)
started = time.perf_counter()
samples: list[int] = []
reasons: list[str] = []
try:
with httpx.Client(
proxy=url,
@@ -162,16 +172,29 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
) as client:
response = client.get(PROBE_URL)
latency = int((time.perf_counter() - started) * 1000)
if latency > LATENCY_LIMIT_MS:
return False, latency, "超时"
if response.status_code >= 500:
return False, latency, f"HTTP {response.status_code}"
return True, latency, ""
for target in PROBE_URLS:
started = time.perf_counter()
try:
response = client.get(target)
latency = int((time.perf_counter() - started) * 1000)
if response.status_code >= 500:
samples.append(max(latency, LATENCY_LIMIT_MS))
reasons.append(f"HTTP {response.status_code}")
continue
samples.append(latency)
except Exception as exc:
samples.append(int((time.perf_counter() - started) * 1000) or LATENCY_LIMIT_MS)
reasons.append(_short_reason(exc))
except Exception as exc:
latency = int((time.perf_counter() - started) * 1000)
return False, latency, _short_reason(exc)
return False, LATENCY_LIMIT_MS, _short_reason(exc)
if not samples:
return False, LATENCY_LIMIT_MS, reasons[0] if reasons else "无法连接"
average = int(round(sum(samples) / len(samples)))
if reasons:
return False, average, reasons[0]
if average > LATENCY_LIMIT_MS:
return False, average, "超时"
return True, average, ""
def _short_reason(exc: BaseException) -> str:
@@ -413,6 +436,69 @@ def _probe_many(nodes: list[tuple[int, str, str, int]]) -> list[tuple[int, bool,
return results
def _apply_probe(node: ProxyNode, ok: bool, latency: int, reason: str) -> None:
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 "失效")[:200]
_evict_node(node.id)
def probe_one(node_id: int) -> dict:
with SessionLocal() as db:
node = db.get(ProxyNode, node_id)
if node is None:
raise ProxyProbeError("代理不存在")
snapshot = (node.id, node.scheme, node.host, int(node.port))
ok, latency, reason = probe(snapshot[1], snapshot[2], snapshot[3])
with SessionLocal() as db, _assign_lock:
node = db.get(ProxyNode, node_id)
if node is None:
raise ProxyProbeError("代理不存在")
_apply_probe(node, ok, latency, reason)
db.commit()
return view_item(node)
def probe_ids(ids: list[int] | None = None) -> dict:
with SessionLocal() as db:
if ids:
wanted = []
seen: set[int] = set()
for raw in ids:
node_id = int(raw)
if node_id in seen:
continue
seen.add(node_id)
wanted.append(node_id)
nodes = [
node
for node in (db.get(ProxyNode, node_id) for node_id in wanted)
if node is not None
]
if len(nodes) != len(wanted):
raise ProxyProbeError("代理不存在")
else:
nodes = list(db.scalars(select(ProxyNode).order_by(ProxyNode.id)).all())
snapshot = [(node.id, node.scheme, node.host, int(node.port)) for node in nodes]
results = _probe_many(snapshot)
items = []
with SessionLocal() as db, _assign_lock:
for node_id, ok, latency, reason in results:
node = db.get(ProxyNode, node_id)
if node is None:
continue
_apply_probe(node, ok, latency, reason)
items.append(view_item(node))
db.commit()
return {"ok": True, "count": len(items), "items": items}
def request_refresh() -> dict:
with SessionLocal() as db:
sync = _sync_row(db)
+7
View File
@@ -205,6 +205,13 @@ def fetch_training_detail(db: Session, employee_id: str, path: str, client_facto
return _live(db, employee_id, client_factory, lambda client: client.training_detail(path))
def fetch_study_history(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
items = _live(db, employee_id, client_factory, lambda client: client.study_history())
if not isinstance(items, list):
items = []
return {"items": items, "total": len(items)}
def _auto_attempts(db: Session) -> int:
from admin.settings import auto_attempt_count
+48
View File
@@ -0,0 +1,48 @@
"""账号自动学习任务的立即开始与停止。"""
from __future__ import annotations
from euniv.study_window import window_open
class StudyControlError(ValueError):
"""任务控制参数不符合要求。"""
def start_now(account) -> None:
account.study_paused = False
account.study_ignore_window = True
def stop_now(account) -> None:
account.study_paused = True
account.study_ignore_window = False
def is_paused(account) -> bool:
return bool(getattr(account, "study_paused", False))
def ignores_window(account) -> bool:
return bool(getattr(account, "study_ignore_window", False))
def eligible(account) -> bool:
if is_paused(account):
return False
if ignores_window(account):
return True
return window_open(account)
def view_of(account) -> dict:
paused = is_paused(account)
ignore = ignores_window(account)
opened = window_open(account)
started = (not paused) and (ignore or opened)
return {
"paused": paused,
"ignore_window": ignore,
"window_open": opened,
"started": started,
}