diff --git a/backend/admin/routes.py b/backend/admin/routes.py index b10b04c..2534c23 100644 --- a/backend/admin/routes.py +++ b/backend/admin/routes.py @@ -22,11 +22,16 @@ from admin.users import ( set_course_workers, set_paused, set_proxy, + set_study_action, + set_study_settings, set_study_start, ) from euniv.courses import course_page, request_course_sync_now from euniv.db import get_db +from euniv.proxy_pool import ProxyProbeError from euniv.proxy_pool import page as proxy_page +from euniv.proxy_pool import probe_ids as probe_proxy_ids +from euniv.proxy_pool import probe_one as probe_proxy_one from euniv.proxy_pool import request_refresh as request_proxy_refresh public_router = APIRouter() @@ -76,6 +81,30 @@ class AdminCourseWorkersBody(BaseModel): workers: int +class AdminStudyActionBody(BaseModel): + employee_ids: list[str] + action: str + + +class AdminStudySettingsBody(BaseModel): + employee_ids: list[str] + monthly_target: int | None = None + day: int | None = None + hour: int | None = None + minute: int | None = None + second: int | None = None + workers: int | None = None + scheme: str | None = None + host: str = "" + port: int | None = None + username: str = "" + password: str | None = None + + +class AdminProxyProbeBody(BaseModel): + ids: list[int] | None = None + + def require_admin(request: Request) -> str: if not admin_session_active(request.cookies): raise HTTPException(status_code=401, detail="未登录") @@ -148,6 +177,22 @@ def post_proxies_refresh(_: str = Depends(require_admin)) -> dict: return request_proxy_refresh() +@admin_router.post("/proxies/probe") +def post_proxies_probe(body: AdminProxyProbeBody, _: str = Depends(require_admin)) -> dict: + try: + return probe_proxy_ids(body.ids) + except ProxyProbeError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + + +@admin_router.post("/proxies/{proxy_id}/probe") +def post_proxy_probe(proxy_id: int, _: str = Depends(require_admin)) -> dict: + try: + return probe_proxy_one(proxy_id) + except ProxyProbeError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + + @admin_router.get("/users") def get_users(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict]: return list_users(db) @@ -224,6 +269,34 @@ def get_user_course_workers(employee_id: str, db: Session = Depends(get_db), _: return read_course_workers(db, employee_id) +@admin_router.post("/users/study") +def post_users_study( + body: AdminStudyActionBody, db: Session = Depends(get_db), _: str = Depends(require_admin) +) -> dict: + return set_study_action(db, body.employee_ids, body.action) + + +@admin_router.put("/users/study-settings") +def put_users_study_settings( + body: AdminStudySettingsBody, db: Session = Depends(get_db), _: str = Depends(require_admin) +) -> dict: + return set_study_settings( + db, + body.employee_ids, + monthly_target=body.monthly_target, + day=body.day, + hour=body.hour, + minute=body.minute, + second=body.second, + workers=body.workers, + scheme=body.scheme, + host=body.host, + port=body.port, + username=body.username, + password=body.password, + ) + + @admin_router.get("/users/{employee_id}/credentials") def get_credentials(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: return read_credentials(db, employee_id) diff --git a/backend/admin/users.py b/backend/admin/users.py index 8d6b196..cd2a4e2 100644 --- a/backend/admin/users.py +++ b/backend/admin/users.py @@ -16,6 +16,8 @@ from euniv.course_workers import apply as apply_workers from euniv.course_workers import of as workers_of from euniv.course_workers import view_of as workers_view from euniv.proxy import ProxyError, apply, clear, enabled, summary_of, url_of, view_of +from euniv.study_control import start_now, stop_now +from euniv.study_control import view_of as study_view from euniv.study_window import StudyWindowError from euniv.study_window import apply as apply_start from euniv.study_window import label_of as start_label @@ -65,25 +67,32 @@ def _iso_time(value: datetime | None) -> str | None: def list_users(db: Session) -> list[dict]: accounts = db.scalars(select(Account).order_by(Account.employee_id)).all() - return [ - { - "employee_id": account.employee_id, - "has_credential": bool(account.credential_cipher), - "refresh_paused": bool(account.refresh_paused), - "last_refresh_at": _iso_time(account.last_refresh_at), - "credential_valid": _optional_bool(account.credential_valid), - "month_hours": account.month_hours or "", - "has_proxy": enabled(account), - "proxy": summary_of(account), - "study_start": start_label(account), - "study_start_day": int(account.study_start_day or 1), - "study_start_hour": int(account.study_start_hour or 0), - "study_start_minute": int(account.study_start_minute or 0), - "study_start_second": int(account.study_start_second or 0), - "course_workers": workers_of(account), - } - for account in accounts - ] + rows = [] + for account in accounts: + control = study_view(account) + rows.append( + { + "employee_id": account.employee_id, + "has_credential": bool(account.credential_cipher), + "refresh_paused": bool(account.refresh_paused), + "last_refresh_at": _iso_time(account.last_refresh_at), + "credential_valid": _optional_bool(account.credential_valid), + "month_hours": account.month_hours or "", + "monthly_target": int(account.monthly_target or 600), + "has_proxy": enabled(account), + "proxy": summary_of(account), + "study_start": start_label(account), + "study_start_day": int(account.study_start_day or 1), + "study_start_hour": int(account.study_start_hour or 0), + "study_start_minute": int(account.study_start_minute or 0), + "study_start_second": int(account.study_start_second or 0), + "course_workers": workers_of(account), + "study_paused": control["paused"], + "study_ignore_window": control["ignore_window"], + "study_started": control["started"], + } + ) + return rows def _require(db: Session, employee_id: str) -> Account: @@ -270,6 +279,63 @@ def set_course_workers(db: Session, employee_ids: list[str], workers: int) -> di return {"ok": True, "count": len(accounts)} +def set_study_action(db: Session, employee_ids: list[str], action: str) -> dict: + kind = (action or "").strip().lower() + if kind not in {"start", "stop"}: + raise HTTPException(status_code=400, detail="请选择开始或停止") + accounts = _accounts_by_ids(db, employee_ids) + from euniv.autostudy import request_stop, request_wake + + for account in accounts: + if kind == "start": + start_now(account) + else: + stop_now(account) + db.commit() + if kind == "start": + request_wake() + else: + for account in accounts: + request_stop(account.employee_id) + return {"ok": True, "count": len(accounts), "action": kind} + + +def set_study_settings( + db: Session, + employee_ids: list[str], + monthly_target: int | None = None, + day: int | None = None, + hour: int | None = None, + minute: int | None = None, + second: int | None = None, + workers: int | None = None, + scheme: str | None = None, + host: str = "", + port: object = None, + username: str = "", + password: str | None = None, +) -> dict: + accounts = _accounts_by_ids(db, employee_ids) + if monthly_target is not None: + if not isinstance(monthly_target, int) or isinstance(monthly_target, bool) or not 0 <= monthly_target <= 9999: + raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数") + try: + for account in accounts: + if monthly_target is not None: + account.monthly_target = monthly_target + if day is not None: + apply_start(account, day, hour, minute, second) + if workers is not None: + apply_workers(account, workers) + if scheme is not None: + apply(account, scheme, host, port, username, password) + except (StudyWindowError, CourseWorkersError, ProxyError) as exc: + db.rollback() + raise HTTPException(status_code=400, detail=str(exc)) from exc + db.commit() + return {"ok": True, "count": len(accounts)} + + def delete_user(db: Session, employee_id: str) -> dict: account = _require(db, employee_id) db.delete(account) diff --git a/backend/alembic/versions/0012_study_control.py b/backend/alembic/versions/0012_study_control.py new file mode 100644 index 0000000..9619b42 --- /dev/null +++ b/backend/alembic/versions/0012_study_control.py @@ -0,0 +1,25 @@ +"""账号自动学习启停:暂停标记与立即开始(忽略开始时刻)。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0012_study_control" +down_revision = "0011_proxy_pool" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.add_column( + sa.Column("study_paused", sa.Boolean(), nullable=False, server_default=sa.false()) + ) + batch.add_column( + sa.Column("study_ignore_window", sa.Boolean(), nullable=False, server_default=sa.false()) + ) + + +def downgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.drop_column("study_ignore_window") + batch.drop_column("study_paused") diff --git a/backend/euniv/api.py b/backend/euniv/api.py index c8d319f..600cc59 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -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: diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index e06354e..f2dba6f 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -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() diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 207c1db..19355c8 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -116,6 +116,45 @@ def _by_closeness(items: list[dict], key: str) -> list[dict]: return ordered +_HISTORY_ROW_RE = re.compile( + r'\s*' + r'([\s\S]*?)\s*' + r'\s*(\d+)\s*\s*' + r'\s*([^<]+?)\s*', + 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"
  • ", 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 = {} diff --git a/backend/euniv/models.py b/backend/euniv/models.py index b59f959..fc5dc7a 100644 --- a/backend/euniv/models.py +++ b/backend/euniv/models.py @@ -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): diff --git a/backend/euniv/proxy_pool.py b/backend/euniv/proxy_pool.py index 28e545e..efc8a0c 100644 --- a/backend/euniv/proxy_pool.py +++ b/backend/euniv/proxy_pool.py @@ -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) diff --git a/backend/euniv/service.py b/backend/euniv/service.py index f1aade2..594631a 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -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 diff --git a/backend/euniv/study_control.py b/backend/euniv/study_control.py new file mode 100644 index 0000000..997d124 --- /dev/null +++ b/backend/euniv/study_control.py @@ -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, + } diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index 19ebbbf..e21b3e4 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -445,6 +445,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None: "last_refresh_at", "credential_valid", "month_hours", + "monthly_target", "has_proxy", "proxy", "study_start", @@ -453,6 +454,9 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None: "study_start_minute", "study_start_second", "course_workers", + "study_paused", + "study_ignore_window", + "study_started", } assert saved["has_credential"] is True assert saved["refresh_paused"] is False @@ -791,3 +795,60 @@ def test_admin_can_turn_off_proxy_with_scheme() -> None: detail = client.get("/api/admin/users/off-user/proxy") assert detail.json()["enabled"] is False assert detail.json()["scheme"] == "off" + + +def test_admin_can_start_and_stop_study_for_selected_users() -> None: + _add_account("run-user") + _add_account("wait-user") + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + started = client.post("/api/admin/users/study", json={"employee_ids": ["run-user", "wait-user"], "action": "start"}) + assert started.status_code == 200 + assert started.json()["count"] == 2 + listed = client.get("/api/admin/users").json() + one = next(item for item in listed if item["employee_id"] == "run-user") + two = next(item for item in listed if item["employee_id"] == "wait-user") + assert one["study_started"] is True + assert two["study_paused"] is False + stopped = client.post("/api/admin/users/study", json={"employee_ids": ["run-user"], "action": "stop"}) + assert stopped.status_code == 200 + listed = client.get("/api/admin/users").json() + one = next(item for item in listed if item["employee_id"] == "run-user") + two = next(item for item in listed if item["employee_id"] == "wait-user") + assert one["study_started"] is False + assert one["study_paused"] is True + assert two["study_started"] is True + bad = client.post("/api/admin/users/study", json={"employee_ids": ["run-user"], "action": "pause"}) + assert bad.status_code == 400 + + +def test_admin_can_save_study_settings_in_one_request() -> None: + _add_account("set-user") + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + saved = client.put( + "/api/admin/users/study-settings", + json={ + "employee_ids": ["set-user"], + "monthly_target": 120, + "day": 8, + "hour": 9, + "minute": 10, + "second": 11, + "workers": 2, + "scheme": "http", + "host": "10.0.0.8", + "port": 8080, + "username": "", + "password": "", + }, + ) + assert saved.status_code == 200 + listed = client.get("/api/admin/users").json() + one = next(item for item in listed if item["employee_id"] == "set-user") + assert one["monthly_target"] == 120 + assert one["study_start"] == "每月8日 09:10:11" + assert one["course_workers"] == 2 + assert one["proxy"] == "HTTP 10.0.0.8:8080" diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 9fbc9a7..e4b5a3b 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -65,6 +65,16 @@ class FakeClient: "unionId": credential["ucs_union_id"], } + def study_history(self) -> list[dict]: + return [ + { + "title": "ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN)", + "minutes": 2, + "studied_at": "2026-11-14 23:55", + "path": "/kng/view/document/125c7576c22e4ae7be92ce005171facb.html", + } + ] + def home_snapshot(self) -> dict: if self._token == "yxt-1": self._token = "yxt-2" @@ -123,6 +133,8 @@ def test_login_stores_password_and_credential_only() -> None: "study_start_second", "course_workers", "use_proxy_pool", + "study_paused", + "study_ignore_window", } home = client.get("/api/home") @@ -538,6 +550,82 @@ def test_user_can_set_monthly_study_start() -> None: assert bad.status_code == 400 +def test_user_can_start_and_stop_study_immediately() -> None: + import euniv.api as api_module + import euniv.service as service_module + + api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( + db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts + ) + client = TestClient(api_module.app) + assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 + client.put("/api/settings/study-start", json={"day": 31, "hour": 23, "minute": 59, "second": 59}) + idle = client.get("/api/settings/study-control") + assert idle.status_code == 200 + started = client.post("/api/settings/study-control", json={"action": "start"}) + assert started.status_code == 200 + assert started.json()["started"] is True + assert started.json()["ignore_window"] is True + assert started.json()["paused"] is False + stopped = client.post("/api/settings/study-control", json={"action": "stop"}) + assert stopped.status_code == 200 + assert stopped.json()["started"] is False + assert stopped.json()["paused"] is True + assert stopped.json()["ignore_window"] is False + bad = client.post("/api/settings/study-control", json={"action": "pause"}) + assert bad.status_code == 400 + + +def test_user_can_read_study_history() -> None: + import euniv.api as api_module + import euniv.service as service_module + + api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( + db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts + ) + api_module.fetch_study_history = lambda db, employee_id: service_module.fetch_study_history( + db, employee_id, FakeClient + ) + client = TestClient(api_module.app) + assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 + history = client.get("/api/home/history") + assert history.status_code == 200 + body = history.json() + assert body["total"] == 1 + assert body["items"][0]["title"].startswith("ZXCTN") + assert body["items"][0]["minutes"] == 2 + + +def test_study_history_parses_period_table() -> None: + from euniv.client import EunivClient + + html = """ + + + + + + + +
    来源学时日期
    + ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN) + [详情] + 22026-11-14 23:55
    + """ + client = EunivClient.__new__(EunivClient) + client._study_period_page = lambda: html # type: ignore[method-assign] + rows = client._study_history_page() + assert rows == [ + { + "title": "ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN)", + "minutes": 2, + "studied_at": "2026-11-14 23:55", + "path": "/kng/view/document/125c7576c22e4ae7be92ce005171facb.html", + } + ] + + def test_exam_list_rejects_unrecognized_page() -> None: from euniv.client import EunivClient diff --git a/backend/tests/test_autostudy.py b/backend/tests/test_autostudy.py index 94a5a88..32a4018 100644 --- a/backend/tests/test_autostudy.py +++ b/backend/tests/test_autostudy.py @@ -7,6 +7,7 @@ from datetime import datetime from euniv.autostudy import CourseCursor, HoursWatcher, _parse_minutes, _study_video, wait_stop from euniv.course_workers import CourseWorkersError, of as workers_of, validate as validate_workers from euniv.proxy import ProxyError, apply as apply_proxy, build_proxy_url, parse_proxy, view_of as proxy_view +from euniv.study_control import eligible as study_eligible, start_now, stop_now from euniv.study_window import CN_TZ, StudyWindowError, validate_start, window_open @@ -172,6 +173,8 @@ class _Start: self.study_start_hour = hour self.study_start_minute = minute self.study_start_second = second + self.study_paused = False + self.study_ignore_window = False def test_study_window_opens_after_configured_time() -> None: @@ -188,6 +191,19 @@ def test_study_window_clamps_missing_day() -> None: assert window_open(account, datetime(2026, 2, 28, 16, 0, 0, tzinfo=CN_TZ)) is True +def test_immediate_start_skips_monthly_window() -> None: + account = _Start(28, 23, 59, 59) + assert study_eligible(account) is False + start_now(account) + assert account.study_paused is False + assert account.study_ignore_window is True + assert study_eligible(account) is True + stop_now(account) + assert account.study_paused is True + assert account.study_ignore_window is False + assert study_eligible(account) is False + + def test_study_window_rejects_invalid_parts() -> None: with pytest.raises(StudyWindowError): validate_start(32, 0, 0, 0) diff --git a/backend/tests/test_proxy_pool.py b/backend/tests/test_proxy_pool.py index 87040cc..803caa1 100644 --- a/backend/tests/test_proxy_pool.py +++ b/backend/tests/test_proxy_pool.py @@ -7,7 +7,7 @@ from euniv.db import SessionLocal from euniv.models import Account, ProxyNode from euniv.proxy import apply as apply_proxy from euniv.proxy import bind_url, is_proxy_failure, view_of -from euniv.proxy_pool import acquire, mark_failed, page, refresh_once, release +from euniv.proxy_pool import PROBE_URLS, acquire, mark_failed, page, probe, refresh_once, release from euniv.proxy_pool import _holds INITIAL_PASSWORD = "242520" @@ -189,6 +189,57 @@ def test_failed_proxy_is_not_reprobed(monkeypatch) -> None: assert node.status == "dead" +def test_probe_averages_euniv_related_sites(monkeypatch) -> None: + seen: list[str] = [] + + class FakeResponse: + status_code = 200 + + class FakeClient: + def __init__(self, **_kwargs) -> None: + return None + + def __enter__(self): + return self + + def __exit__(self, *_args) -> bool: + return False + + def get(self, url: str): + seen.append(url) + return FakeResponse() + + ticks = iter([0.0, 0.12, 0.12, 0.34, 0.34, 0.64]) + monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient) + monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks)) + ok, latency, reason = probe("http", "10.0.0.9", 8080) + assert seen == list(PROBE_URLS) + assert ok is True + assert latency == 213 + assert reason == "" + + +def test_admin_can_probe_one_and_all_proxies(monkeypatch) -> None: + import euniv.api as api_module + + _holds.clear() + one = _node("10.0.0.7", 8007) + two = _node("10.0.0.8", 8008, status="new") + monkeypatch.setattr("euniv.proxy_pool.probe", lambda scheme, host, port: (True, 321 if host.endswith("7") else 654, "")) + client = TestClient(api_module.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + single = client.post(f"/api/admin/proxies/{one.id}/probe") + assert single.status_code == 200 + assert single.json()["latency_ms"] == 321 + assert single.json()["status"] == "alive" + bulk = client.post("/api/admin/proxies/probe", json={"ids": [two.id]}) + assert bulk.status_code == 200 + assert bulk.json()["count"] == 1 + assert bulk.json()["items"][0]["latency_ms"] == 654 + missing = client.post("/api/admin/proxies/99999/probe") + assert missing.status_code == 404 + + def test_is_proxy_failure_detects_connect_errors() -> None: assert is_proxy_failure(httpx.ConnectError("boom")) assert is_proxy_failure(httpx.ConnectTimeout("late")) diff --git a/web/src/features/admin/CoursesView.vue b/web/src/features/admin/CoursesView.vue index 0702544..e359574 100644 --- a/web/src/features/admin/CoursesView.vue +++ b/web/src/features/admin/CoursesView.vue @@ -1,6 +1,7 @@ + + diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index ef78ba2..539e943 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -1,7 +1,7 @@