diff --git a/backend/admin/routes.py b/backend/admin/routes.py index 95933d6..cbbe980 100644 --- a/backend/admin/routes.py +++ b/backend/admin/routes.py @@ -17,20 +17,16 @@ from admin.users import ( list_users, read_credentials, read_proxy, - read_course_workers, - read_study_start, - 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_state as proxy_probe_state +from euniv.proxy_pool import request_probe as request_proxy_probe from euniv.proxy_pool import probe_one as probe_proxy_one from euniv.proxy_pool import request_refresh as request_proxy_refresh @@ -57,32 +53,10 @@ class PauseBody(BaseModel): paused: bool -class AdminProxyBody(BaseModel): - employee_ids: list[str] - scheme: str - host: str = "" - port: int | None = None - username: str = "" - password: str | None = None - - class AdminProxyClearBody(BaseModel): employee_ids: list[str] -class AdminStudyStartBody(BaseModel): - employee_ids: list[str] - day: int - hour: int - minute: int - second: int - - -class AdminCourseWorkersBody(BaseModel): - employee_ids: list[str] - workers: int - - class AdminStudyActionBody(BaseModel): employee_ids: list[str] action: str @@ -185,10 +159,12 @@ def post_proxies_refresh(_: str = Depends(require_admin)) -> dict: @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 + return request_proxy_probe(body.ids) + + +@admin_router.get("/proxies/probe") +def get_proxies_probe(_: str = Depends(require_admin)) -> dict: + return proxy_probe_state() @admin_router.post("/proxies/{proxy_id}/probe") @@ -224,19 +200,6 @@ def post_refresh( return set_paused(db, employee_id, body.paused) -@admin_router.put("/users/proxy") -def put_users_proxy(body: AdminProxyBody, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: - return set_proxy( - db, - body.employee_ids, - body.scheme, - body.host, - body.port, - body.username, - body.password, - ) - - @admin_router.post("/users/proxy/clear") def post_users_proxy_clear( body: AdminProxyClearBody, @@ -251,30 +214,6 @@ def get_user_proxy(employee_id: str, db: Session = Depends(get_db), _: str = Dep return read_proxy(db, employee_id) -@admin_router.put("/users/study-start") -def put_users_study_start( - body: AdminStudyStartBody, db: Session = Depends(get_db), _: str = Depends(require_admin) -) -> dict: - return set_study_start(db, body.employee_ids, body.day, body.hour, body.minute, body.second) - - -@admin_router.get("/users/{employee_id}/study-start") -def get_user_study_start(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: - return read_study_start(db, employee_id) - - -@admin_router.put("/users/course-workers") -def put_users_course_workers( - body: AdminCourseWorkersBody, db: Session = Depends(get_db), _: str = Depends(require_admin) -) -> dict: - return set_course_workers(db, body.employee_ids, body.workers) - - -@admin_router.get("/users/{employee_id}/course-workers") -def get_user_course_workers(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: - 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) diff --git a/backend/admin/users.py b/backend/admin/users.py index 93c46e6..599fe7b 100644 --- a/backend/admin/users.py +++ b/backend/admin/users.py @@ -113,20 +113,38 @@ def _require(db: Session, employee_id: str) -> Account: def check_employee(db: Session, employee_id: str) -> dict: + from euniv.proxy import bind_url, is_proxy_failure, url_of, uses_pool + from euniv.proxy_pool import MAX_SWITCHES, mark_failed + account = _require(db, employee_id) if not account.credential_cipher: return {"employee_id": employee_id, "result": "未保存"} before_password = account.password_cipher before_credential = account.credential_cipher + password = decrypt_secret(account.password_cipher) if account.password_cipher else "" + credential = json.loads(decrypt_secret(account.credential_cipher)) + pooled = uses_pool(account) + db.commit() client = None result = "检查失败" valid: bool | None = None try: - client = _open_client(employee_id, decrypt_secret(account.password_cipher), url_of(account)) - client.restore(json.loads(decrypt_secret(account.credential_cipher))) - alive = bool(client.credential_alive()) - result = "有效" if alive else "已失效" - valid = alive + for _ in range(MAX_SWITCHES + 1): + proxy = bind_url(account) if pooled else url_of(account) + client = _open_client(employee_id, password, proxy) + try: + client.restore(credential) + alive = bool(client.credential_alive()) + result = "有效" if alive else "已失效" + valid = alive + break + except Exception as exc: + if pooled and proxy and is_proxy_failure(exc): + mark_failed(employee_id, proxy, str(exc)[:200]) + client.close() + client = None + continue + raise except Exception: db.rollback() account = db.get(Account, employee_id) @@ -239,6 +257,10 @@ def set_proxy( db.rollback() raise HTTPException(status_code=400, detail=str(exc)) from exc db.commit() + from euniv.autostudy import restart_work + + for account in accounts: + restart_work(account.employee_id) return {"ok": True, "count": len(accounts)} @@ -247,6 +269,10 @@ def clear_proxy(db: Session, employee_ids: list[str]) -> dict: for account in accounts: clear(account) db.commit() + from euniv.autostudy import restart_work + + for account in accounts: + restart_work(account.employee_id) return {"ok": True, "count": len(accounts)} @@ -348,10 +374,13 @@ def set_study_settings( db.rollback() raise HTTPException(status_code=400, detail=str(exc)) from exc db.commit() - from euniv.autostudy import sync_work + from euniv.autostudy import restart_work, sync_work for account in accounts: - sync_work(account.employee_id) + if scheme is not None: + restart_work(account.employee_id) + else: + sync_work(account.employee_id) return {"ok": True, "count": len(accounts)} diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 4677c4e..92897d5 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -72,6 +72,16 @@ class CourseWorkersBody(_BaseModel): workers: int +class StudyBundleBody(_BaseModel): + monthly_target: int + day: int + hour: int + minute: int + second: int + enabled: bool = True + workers: int + + class StudyControlBody(_BaseModel): action: str @@ -371,6 +381,34 @@ def put_study_start(body: StudyStartBody, request: Request, db: Session = Depend return view_of(account) +@app.put("/api/settings/study") +def put_study_bundle(body: StudyBundleBody, request: Request, db: Session = Depends(get_db)) -> dict: + from euniv.course_workers import CourseWorkersError, apply as apply_workers + from euniv.study_window import StudyWindowError, apply as apply_start, view_of + + if not 0 <= body.monthly_target <= 9999: + raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数") + account = db.get(Account, _signed_in(request, db)) + if account is None: + raise HTTPException(status_code=401, detail="未登录") + try: + account.monthly_target = body.monthly_target + apply_start(account, body.day, body.hour, body.minute, body.second) + account.study_schedule_enabled = bool(body.enabled) + apply_workers(account, body.workers) + except (StudyWindowError, CourseWorkersError) as exc: + db.rollback() + raise HTTPException(status_code=400, detail=str(exc)) from exc + db.commit() + from euniv.autostudy import sync_work + + sync_work(account.employee_id) + payload = view_of(account) + payload["monthly_target"] = account.monthly_target + payload["workers"] = account.course_workers + return payload + + @app.get("/api/settings/course-workers") def get_course_workers(request: Request, db: Session = Depends(get_db)) -> dict: from euniv.course_workers import view_of @@ -418,6 +456,9 @@ def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db)) except ProxyError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc db.commit() + from euniv.autostudy import restart_work + + restart_work(account.employee_id) return view_of(account) @@ -430,13 +471,16 @@ def delete_proxy(request: Request, db: Session = Depends(get_db)) -> dict: raise HTTPException(status_code=401, detail="未登录") clear(account) db.commit() + from euniv.autostudy import restart_work + + restart_work(account.employee_id) return view_of(account) @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 assemble, settle + from euniv.study_control import assemble, settle, stamp_frame employee_id = _signed_in(request, db) account = db.get(Account, employee_id) diff --git a/backend/euniv/autostudy.py b/backend/euniv/autostudy.py index 8beafbb..85c1096 100644 --- a/backend/euniv/autostudy.py +++ b/backend/euniv/autostudy.py @@ -424,6 +424,14 @@ def sync_work(employee_id: str) -> None: halt_work(key) +def restart_work(employee_id: str) -> None: + """代理或学习配置变了,正在跑的这一轮先停掉,再按新配置评估。""" + key = (employee_id or "").strip() + if key and work_running(key): + halt_work(key) + sync_work(key) + + _KIND_RANK = {"视频": 0, "文档": 1, "课程包": 2, "课程": 3} diff --git a/backend/euniv/courses.py b/backend/euniv/courses.py index 67b9c8e..6be54c5 100644 --- a/backend/euniv/courses.py +++ b/backend/euniv/courses.py @@ -157,6 +157,25 @@ def _run(trigger: str) -> None: _running = False +def _cool_failed_sync(employee_id: str, *, invalid: bool = False) -> None: + from euniv.db import SessionLocal + + if not employee_id: + return + with SessionLocal() as db: + sync = db.get(CourseSync, 1) + if sync is None: + sync = CourseSync(id=1, last_employee_id=employee_id, course_count=0) + db.add(sync) + sync.last_employee_id = employee_id + sync.next_allowed_at = datetime.now(timezone.utc) + timedelta(minutes=30) + if invalid: + account = db.get(Account, employee_id) + if account is not None: + account.credential_valid = False + db.commit() + + def _fetch_and_store(trigger: str) -> bool: from euniv.client import EunivClient from euniv.crypto import decrypt_secret @@ -184,6 +203,7 @@ def _fetch_and_store(trigger: str) -> bool: try: client.restore(credential) if not client.credential_alive(): + _cool_failed_sync(employee_id, invalid=True) return False courses = client.list_courses() last_exc = None @@ -194,10 +214,12 @@ def _fetch_and_store(trigger: str) -> bool: mark_failed(employee_id, proxy, str(exc)[:200]) proxy = bind_url(account) continue + _cool_failed_sync(employee_id) return False finally: client.close() if last_exc is not None or not courses: + _cool_failed_sync(employee_id) return False with SessionLocal() as db: db.execute(delete(Course)) diff --git a/backend/euniv/proxy_pool.py b/backend/euniv/proxy_pool.py index f2c4b68..c2141d8 100644 --- a/backend/euniv/proxy_pool.py +++ b/backend/euniv/proxy_pool.py @@ -48,6 +48,8 @@ _assign_lock = threading.Lock() _holds: dict[str, int] = {} _refresh_lock = threading.Lock() _stop: threading.Event | None = None +_probe_guard = threading.Lock() +_probe_state = {"running": False, "count": 0, "error": ""} def _now() -> datetime: @@ -507,7 +509,44 @@ def probe_one(node_id: int) -> dict: return view_item(node) +def request_probe(ids: list[int] | None = None) -> dict: + """整表探测放到后台,避免一次请求卡住到超时。""" + with _probe_guard: + if _probe_state["running"]: + return {"running": True, "count": _probe_state["count"], "items": []} + _probe_state["running"] = True + _probe_state["error"] = "" + _probe_state["count"] = 0 + + def work() -> None: + try: + result = probe_ids(ids) + with _probe_guard: + _probe_state["count"] = int(result.get("count") or 0) + _probe_state["error"] = "" + except Exception as exc: + with _probe_guard: + _probe_state["error"] = str(exc)[:200] + finally: + with _probe_guard: + _probe_state["running"] = False + + threading.Thread(target=work, name="euniv-proxy-probe", daemon=True).start() + return {"running": True, "count": 0, "items": []} + + +def probe_state() -> dict: + with _probe_guard: + return { + "running": _probe_state["running"], + "count": _probe_state["count"], + "error": _probe_state["error"], + } + + def probe_ids(ids: list[int] | None = None) -> dict: + if ids is not None and not ids: + return {"ok": True, "count": 0, "items": []} with SessionLocal() as db: if ids: wanted = [] diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 46f5160..6d03d0d 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -38,7 +38,7 @@ def _credential_lock(employee_id: str) -> threading.Lock: with _credential_guard: lock = _credential_locks.get(employee_id) if lock is None: - lock = threading.Lock() + lock = threading.RLock() _credential_locks[employee_id] = lock return lock @@ -104,6 +104,11 @@ def _drop_employee(employee_id: str) -> None: def _persist(db: Session, employee_id: str, password: str | None, client: EunivClient, profile: dict) -> None: + with _credential_lock(employee_id): + _persist_locked(db, employee_id, password, client, profile) + + +def _persist_locked(db: Session, employee_id: str, password: str | None, client: EunivClient, profile: dict) -> None: from sqlalchemy.exc import IntegrityError client.authorize(profile) @@ -421,6 +426,7 @@ def _live(db: Session, employee_id: str, client_factory, read): credential = json.loads(decrypt_secret(account.credential_cipher)) attempts = _auto_attempts(db) password = decrypt_secret(account.password_cipher) if account.password_cipher else "" + db.commit() last_exc: BaseException | None = None for _ in range(MAX_SWITCHES + 1): client = _client(client_factory, employee_id, password, account) @@ -515,14 +521,19 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None: password = decrypt_secret(account.password_cipher) previous = json.loads(decrypt_secret(account.credential_cipher)) + db.commit() for _ in range(MAX_SWITCHES + 1): client = _client(client_factory, employee_id, password, account) try: client.restore(previous) if client.credential_alive(): updated = client.export_credential() - if _dump(updated) != _dump(previous): - account.credential_cipher = encrypt_secret(_dump(updated)) + with _credential_lock(employee_id): + db.refresh(account) + current_raw = account.credential_cipher + current = json.loads(decrypt_secret(current_raw)) if current_raw else {} + if current_raw and _dump(current) == _dump(previous) and _dump(updated) != _dump(previous): + account.credential_cipher = encrypt_secret(_dump(updated)) valid = True checked_alive = True elif is_qr_password(password): diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index 3591274..c53885a 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -707,7 +707,7 @@ def test_admin_can_set_and_clear_proxy_for_selected_users() -> None: 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/proxy", + "/api/admin/users/study-settings", json={ "employee_ids": ["p1-user", "p2-user"], "scheme": "socks5", @@ -736,7 +736,7 @@ def test_admin_can_set_and_clear_proxy_for_selected_users() -> None: assert one["has_proxy"] is False assert two["has_proxy"] is True no_auth = client.put( - "/api/admin/users/proxy", + "/api/admin/users/study-settings", json={ "employee_ids": ["p1-user"], "scheme": "http", @@ -762,7 +762,7 @@ def test_admin_can_set_study_start_for_selected_users() -> None: 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-start", + "/api/admin/users/study-settings", json={"employee_ids": ["s1-user", "s2-user"], "day": 5, "hour": 16, "minute": 8, "second": 9}, ) assert saved.status_code == 200 @@ -773,7 +773,7 @@ def test_admin_can_set_study_start_for_selected_users() -> None: assert one["study_start"] == "每月5日 16:08:09" assert two["study_start"] == "每月5日 16:08:09" one_only = client.put( - "/api/admin/users/study-start", + "/api/admin/users/study-settings", json={"employee_ids": ["s1-user"], "day": 20, "hour": 0, "minute": 0, "second": 0}, ) assert one_only.status_code == 200 @@ -782,8 +782,7 @@ def test_admin_can_set_study_start_for_selected_users() -> None: two = next(item for item in listed if item["employee_id"] == "s2-user") assert one["study_start"] == "每月20日 00:00:00" assert two["study_start"] == "每月5日 16:08:09" - detail = client.get("/api/admin/users/s1-user/study-start") - assert detail.json()["day"] == 20 + assert one["study_start_day"] == 20 def test_admin_can_set_course_workers_for_selected_users() -> None: @@ -796,7 +795,7 @@ def test_admin_can_set_course_workers_for_selected_users() -> None: one = next(item for item in listed if item["employee_id"] == "w1-user") assert one["course_workers"] == 1 saved = client.put( - "/api/admin/users/course-workers", + "/api/admin/users/study-settings", json={"employee_ids": ["w1-user", "w2-user"], "workers": 4}, ) assert saved.status_code == 200 @@ -807,7 +806,7 @@ def test_admin_can_set_course_workers_for_selected_users() -> None: assert one["course_workers"] == 4 assert two["course_workers"] == 4 one_only = client.put( - "/api/admin/users/course-workers", + "/api/admin/users/study-settings", json={"employee_ids": ["w1-user"], "workers": 1}, ) assert one_only.status_code == 200 @@ -817,12 +816,10 @@ def test_admin_can_set_course_workers_for_selected_users() -> None: assert one["course_workers"] == 1 assert two["course_workers"] == 4 bad = client.put( - "/api/admin/users/course-workers", + "/api/admin/users/study-settings", json={"employee_ids": ["w1-user"], "workers": 9}, ) assert bad.status_code == 400 - detail = client.get("/api/admin/users/w1-user/course-workers") - assert detail.json()["workers"] == 1 def test_admin_can_turn_off_proxy_with_scheme() -> None: @@ -831,14 +828,14 @@ def test_admin_can_turn_off_proxy_with_scheme() -> None: client = TestClient(api.app) assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 client.put( - "/api/admin/users/proxy", + "/api/admin/users/study-settings", json={"employee_ids": ["off-user"], "scheme": "http", "host": "1.1.1.1", "port": 8080}, ) listed = client.get("/api/admin/users").json() one = next(item for item in listed if item["employee_id"] == "off-user") assert one["has_proxy"] is True closed = client.put( - "/api/admin/users/proxy", + "/api/admin/users/study-settings", json={"employee_ids": ["off-user"], "scheme": "off"}, ) assert closed.status_code == 200 diff --git a/backend/tests/test_proxy_pool.py b/backend/tests/test_proxy_pool.py index d0e59b6..8a96743 100644 --- a/backend/tests/test_proxy_pool.py +++ b/backend/tests/test_proxy_pool.py @@ -290,8 +290,18 @@ def test_admin_can_probe_one_and_all_proxies(monkeypatch) -> None: 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 + assert bulk.json()["running"] is True + finished = {"running": True} + for _ in range(40): + finished = client.get("/api/admin/proxies/probe").json() + if finished["running"] is False: + break + import time + time.sleep(0.05) + assert finished["running"] is False + listed = client.get("/api/admin/proxies").json() + probed = next(item for item in listed["items"] if item["id"] == two.id) + assert probed["latency_ms"] == 654 missing = client.post("/api/admin/proxies/99999/probe") assert missing.status_code == 404 @@ -318,7 +328,7 @@ def test_admin_proxy_page_and_pool_assignment() -> None: assert body["items"][0]["host"] == "10.0.0.5" assert body["items"][0]["status_text"] == "可用" saved = client.put( - "/api/admin/users/proxy", + "/api/admin/users/study-settings", json={"employee_ids": ["a-user", "b-user"], "scheme": "pool"}, ) assert saved.status_code == 200 diff --git a/web/src/features/admin/ProxiesView.vue b/web/src/features/admin/ProxiesView.vue index 7c8801f..7e537b3 100644 --- a/web/src/features/admin/ProxiesView.vue +++ b/web/src/features/admin/ProxiesView.vue @@ -252,6 +252,16 @@ async function probeAll() { setError("没有测出延迟。"); return; } + for (let attempt = 0; attempt < 120; attempt += 1) { + const status = await fetch("/api/admin/proxies/probe"); + const body: unknown = await status.json().catch(() => ({})); + if (!status.ok || !isRecord(body)) break; + if (body.running !== true) { + if (typeof body.error === "string" && body.error) setError(body.error); + break; + } + await new Promise((resolve) => window.setTimeout(resolve, 500)); + } await load(); } catch { setError("没有测出延迟。"); diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index 40bfa25..25078c1 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -378,9 +378,15 @@ async function saveSchedule() { scheduleSaving.value = true; scheduleError.value = ""; try { - await putJson("/api/settings/monthly-target", { monthly_target: target }, "没有保存每月目标。"); - await putJson("/api/settings/study-start", { day, hour, minute, second, enabled: scheduleEnabled.value }, "没有保存定时启动。"); - await putJson("/api/settings/course-workers", { workers }, "没有保存同时学习课程数。"); + await putJson("/api/settings/study", { + monthly_target: target, + day, + hour, + minute, + second, + enabled: scheduleEnabled.value, + workers, + }, "没有保存定时配置。"); await loadStudyControl(); } catch (exc) { scheduleError.value = exc instanceof Error ? exc.message : "没有保存。";