fix: 补齐审查清单里还没落地的交互和代理复测

This commit is contained in:
2026-11-16 16:17:31 +08:00
parent 58b3dedb2a
commit 50a8ae2e27
19 changed files with 444 additions and 192 deletions
+3 -3
View File
@@ -79,7 +79,7 @@ def list_users(db: Session) -> list[dict]:
"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),
"monthly_target": account.monthly_target if account.monthly_target is not None else 600,
"has_proxy": enabled(account),
"proxy": summary_of(account),
"study_start": start_label(account),
@@ -109,7 +109,7 @@ 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
from euniv.proxy_pool import MAX_SWITCHES, retire_if_dead
account = _require(db, employee_id)
if not account.credential_cipher:
@@ -133,7 +133,7 @@ def check_employee(db: Session, employee_id: str) -> dict:
break
except Exception as exc:
if pooled and proxy and is_proxy_failure(exc):
mark_failed(employee_id, proxy, str(exc)[:200])
retire_if_dead(employee_id, proxy, str(exc)[:200])
client.close()
client = None
continue
+10 -8
View File
@@ -34,6 +34,7 @@ from euniv.client import (
_load_cookies,
as_uuid,
compact_id,
guard_https,
play_page_params,
study_progress_fields,
)
@@ -665,14 +666,12 @@ class HoursWatcher:
target: int,
user_stop: asyncio.Event,
interval: float = _HOURS_REFRESH_SECONDS,
source: str = "api",
) -> None:
self.session = session
self.employee_id = employee_id
self.target = target
self.user_stop = user_stop
self.interval = interval
self.source = source if source in ("api", "history") else "api"
self._lock = asyncio.Lock()
self.reached = False
from euniv.study_window import month_key
@@ -764,6 +763,7 @@ class StudySession:
timeout=30,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
event_hooks={"request": [guard_https]},
)
_load_cookies(self._client, self._initial_cookies)
self._proxy_lock = asyncio.Lock()
@@ -780,7 +780,7 @@ class StudySession:
if not self._use_pool:
return False
from euniv.proxy import async_httpx_client, parse_proxy
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
from euniv.proxy_pool import MAX_SWITCHES, acquire, retire_if_dead
if self._proxy_lock is None:
self._proxy_lock = asyncio.Lock()
@@ -790,8 +790,10 @@ class StudySession:
return True
if self._switches >= MAX_SWITCHES:
return False
dead = await asyncio.to_thread(retire_if_dead, self._employee_id, failed)
if not dead:
return True
self._switches += 1
await asyncio.to_thread(mark_failed, self._employee_id, failed)
nxt = await asyncio.to_thread(acquire, self._employee_id)
parsed = parse_proxy(nxt)
if parsed == failed:
@@ -801,6 +803,7 @@ class StudySession:
timeout=30,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
event_hooks={"request": [guard_https]},
)
cookies = self._initial_cookies
if self._client is not None:
@@ -1454,7 +1457,7 @@ def _prepare_session(employee_id: str, password: str,
use_pool: bool = False
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
"""同步:恢复会话并导出 cookies。最后一项是 expired 或 network。"""
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
from euniv.proxy_pool import MAX_SWITCHES, acquire, retire_if_dead
current = proxy
last_reason = "network"
@@ -1477,9 +1480,8 @@ def _prepare_session(employee_id: str, password: str,
except Exception as exc:
log.warning("用户 %s 准备会话失败: %s", employee_id, exc)
if use_pool and current and is_proxy_failure(exc):
mark_failed(employee_id, current, str(exc)[:200])
if retire_if_dead(employee_id, current, str(exc)[:200]):
current = acquire(employee_id)
last_reason = "network"
continue
last_reason = "expired" if isinstance(exc, SessionExpired) else "network"
return "", "", "", [], current, last_reason
@@ -1748,7 +1750,7 @@ class AutoStudyWorker:
_set_user_status(employee_id, state="已停止")
return
_set_user_status(employee_id, state="学习中")
hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source)
hours = HoursWatcher(session, employee_id, target, user_stop)
if await hours.refresh():
return
ticker = asyncio.create_task(hours.ticker(self._async_stop))
+11 -6
View File
@@ -755,9 +755,14 @@ class QrWaiting(Exception):
"""二维码尚未扫过或还在等待确认。"""
def _https_only(request: httpx.Request) -> None:
def guard_https(request: httpx.Request) -> None:
if request.url.scheme != "https":
raise RuntimeError("只允许 https 请求")
host = (request.url.host or "").rstrip(".").lower()
if host in {"zte.com.cn", "yunxuetang.cn"} or host.endswith((".zte.com.cn", ".yunxuetang.cn")):
return
request.headers.pop("token", None)
request.headers.pop("Token", None)
def _login_secret_too_long(value: str) -> bool:
@@ -776,7 +781,7 @@ class EunivClient:
timeout=30,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
event_hooks={"request": [_https_only]},
event_hooks={"request": [guard_https]},
)
self._profile: dict = {}
self._yxt_token = ""
@@ -992,7 +997,7 @@ class EunivClient:
if profile.get("unionId"):
jar["iuacUnionId"] = str(profile["unionId"])
for name, value in jar.items():
self.client.cookies.set(name, value, domain=domain, path="/")
self.client.cookies.set(name, value, domain=domain, path="/", secure=True)
self._uac_post(
"/authentication/token/verify.serv",
@@ -1057,8 +1062,8 @@ class EunivClient:
token = str(credential.get("yxt_token") or "")
self._yxt_token = token
if token:
self.client.cookies.set("ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/")
self.client.cookies.set("ELEARNING_00024", token, domain=".yunxuetang.cn", path="/")
self.client.cookies.set("ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/", secure=True)
self.client.cookies.set("ELEARNING_00024", token, domain=".yunxuetang.cn", path="/", secure=True)
def session_token(self) -> str:
for cookie in self.client.cookies.jar:
@@ -1081,7 +1086,7 @@ class EunivClient:
if refreshed:
self._yxt_token = refreshed
for domain in ("euniv.zte.com.cn", ".yunxuetang.cn"):
self.client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/")
self.client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/", secure=True)
if response.status_code == 401:
raise SessionExpired("学习平台登录已失效")
if response.status_code == 403:
+2 -2
View File
@@ -201,7 +201,7 @@ def _fetch_and_store(trigger: str) -> bool:
password = decrypt_secret(account.password_cipher)
credential = json.loads(decrypt_secret(account.credential_cipher))
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
from euniv.proxy_pool import MAX_SWITCHES, mark_failed
from euniv.proxy_pool import MAX_SWITCHES, retire_if_dead
proxy = bind_url(account)
courses = None
@@ -219,7 +219,7 @@ def _fetch_and_store(trigger: str) -> bool:
except Exception as exc:
last_exc = exc
if uses_pool(account) and proxy and is_proxy_failure(exc):
mark_failed(employee_id, proxy, str(exc)[:200])
if retire_if_dead(employee_id, proxy, str(exc)[:200]):
proxy = bind_url(account)
continue
_cool_failed_sync(employee_id)
+3
View File
@@ -332,6 +332,9 @@ def is_proxy_failure(exc: BaseException) -> bool:
httpx.ProxyError,
httpx.ConnectError,
httpx.ConnectTimeout,
httpx.ReadTimeout,
httpx.ReadError,
httpx.RemoteProtocolError,
SocksProxyError,
ProxyConnectionError,
ProxyTimeoutError,
+13
View File
@@ -332,6 +332,19 @@ def release(employee_id: str) -> None:
db.commit()
def retire_if_dead(employee_id: str, proxy_url: str | None, reason: str = "") -> bool:
"""立刻复测当前节点。还通就继续用;不通就标死。"""
parsed = _parse_proxy_url(proxy_url)
if parsed is None:
mark_failed(employee_id, proxy_url, reason)
return True
ok, _latency, why = probe(parsed[0], parsed[1], parsed[2])
if ok:
return False
mark_failed(employee_id, proxy_url, why or reason)
return True
def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None:
key = (employee_id or "").strip()
parsed = _parse_proxy_url(proxy_url)
+2 -2
View File
@@ -181,14 +181,14 @@ def _client(factory, employee_id: str, password: str, account: Account | None =
def _switch_proxy(account: Account | None, client, exc: BaseException) -> bool:
from euniv.proxy import is_proxy_failure, uses_pool
from euniv.proxy_pool import mark_failed
from euniv.proxy_pool import retire_if_dead
if account is None or not uses_pool(account):
return False
proxy = getattr(client, "proxy", None)
if not proxy or not is_proxy_failure(exc):
return False
mark_failed(account.employee_id, proxy, str(exc)[:200])
retire_if_dead(account.employee_id, proxy, str(exc)[:200])
return True
+10
View File
@@ -28,6 +28,16 @@ _last_flush: dict[str, float] = {}
def attach_loop(loop: asyncio.AbstractEventLoop) -> None:
global _loop
if _loop is loop:
return
for handle in list(_pending.values()):
handle.cancel()
_pending.clear()
_inflight.clear()
_dirty.clear()
_urgent.clear()
_last_flush.clear()
_clients.clear()
_loop = loop
+27 -15
View File
@@ -68,7 +68,7 @@ def _settings_body(**overrides) -> dict:
return body
def test_admin_login_succeeds_and_wrong_password_skips_euniv() -> None:
def test_admin_login_succeeds_and_wrong_password_skips_euniv(monkeypatch) -> None:
api = _app()
calls = []
@@ -76,7 +76,7 @@ def test_admin_login_succeeds_and_wrong_password_skips_euniv() -> None:
calls.append("euniv")
raise AssertionError("不应走 e 学登录")
api.login_and_store = spy
monkeypatch.setattr(api, "login_and_store", spy)
statements = []
def hear(_connection, _cursor, statement, _parameters, _context, _executemany):
@@ -134,12 +134,16 @@ def test_legacy_default_password_is_replaced_and_failures_are_limited() -> None:
assert blocked.status_code == 429
def test_admin_identity_uses_memory_until_reload() -> None:
def test_admin_identity_uses_memory_until_reload(monkeypatch) -> None:
api = _app()
calls = []
api.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: calls.append(employee_id) or {
monkeypatch.setattr(
api,
"login_and_store",
lambda db, employee_id, password, manual=False, auto_attempts=3: calls.append(employee_id) or {
"employee_id": employee_id
}
},
)
with SessionLocal() as db:
row = db.get(SystemConfig, 1)
assert row is not None
@@ -198,7 +202,7 @@ def test_seed_does_not_reset_saved_admin() -> None:
assert verify_password(row.admin_password_cipher, "next-secret")
def test_login_config_changes_meaning_with_visibility() -> None:
def test_login_config_changes_meaning_with_visibility(monkeypatch) -> None:
api = _app()
seen = {}
@@ -207,7 +211,7 @@ def test_login_config_changes_meaning_with_visibility() -> None:
seen["attempts"] = auto_attempts
return {"employee_id": employee_id}
api.login_and_store = spy
monkeypatch.setattr(api, "login_and_store", spy)
client = TestClient(api.app)
opened = client.get("/api/login-config")
assert opened.json() == {"show_manual_checkbox": True, "manual_checkbox_checked": False}
@@ -447,7 +451,7 @@ def test_paused_account_still_updates_when_opening_home() -> None:
assert json.loads(decrypt_secret(account.credential_cipher))["yxt_token"] == "yxt-2"
def test_check_skips_empty_credential_and_updates_saved_one() -> None:
def test_check_skips_empty_credential_and_updates_saved_one(monkeypatch) -> None:
import admin.users as users
stamped = datetime(2026, 10, 2, 9, 30, tzinfo=timezone.utc)
@@ -459,7 +463,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
calls.append(login_name)
return _Alive(login_name, password)
users.build_client = factory
monkeypatch.setattr(users, "build_client", factory)
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
@@ -517,7 +521,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
assert calls == []
def test_check_all_reports_each_saved_account() -> None:
def test_check_all_reports_each_saved_account(monkeypatch) -> None:
import admin.users as users
_add_account("a-user")
@@ -531,7 +535,7 @@ def test_check_all_reports_each_saved_account() -> None:
raise RuntimeError("网络失败")
return _Alive(login_name, password)
users.build_client = factory
monkeypatch.setattr(users, "build_client", factory)
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
@@ -550,10 +554,14 @@ def test_check_all_reports_each_saved_account() -> None:
assert untouched is not None and untouched.last_refresh_at is None
def test_credentials_and_delete_user() -> None:
def test_credentials_and_delete_user(monkeypatch) -> None:
import admin.users as users
users.build_client = lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("不应请求 e 学"))
monkeypatch.setattr(
users,
"build_client",
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("不应请求 e 学")),
)
_add_account("6650000146")
_add_account("empty-user", credential=None)
api = _app()
@@ -604,9 +612,13 @@ def test_pause_only_changes_refresh_flag() -> None:
assert row["has_credential"] is True
def test_user_cannot_call_admin_and_logout_clears_only_its_cookie() -> None:
def test_user_cannot_call_admin_and_logout_clears_only_its_cookie(monkeypatch) -> None:
api = _app()
api.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: {"employee_id": employee_id}
monkeypatch.setattr(
api,
"login_and_store",
lambda db, employee_id, password, manual=False, auto_attempts=3: {"employee_id": employee_id},
)
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
_add_account("6650000146")
+101 -37
View File
@@ -109,7 +109,7 @@ class FakeClient:
}
def test_login_stores_password_and_credential_only() -> None:
def test_login_stores_password_and_credential_only(monkeypatch) -> None:
import euniv.api as api_module
import euniv.service as service_module
@@ -119,11 +119,17 @@ def test_login_stores_password_and_credential_only() -> None:
self._token = "yxt-2"
return super().home_summary()
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
monkeypatch.setattr(
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_home_summary = lambda db, employee_id: service_module.fetch_home_summary(
db, employee_id, RefreshingClient
monkeypatch.setattr(
api_module,
"fetch_home_summary",
lambda db, employee_id: service_module.fetch_home_summary(db, employee_id, RefreshingClient),
)
client = TestClient(api_module.app)
response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
@@ -177,14 +183,18 @@ def test_login_stores_password_and_credential_only() -> None:
assert "测试用户" not in decrypt_secret(account.password_cipher)
def test_qr_mark_cannot_password_login_and_unicode_password_is_safe() -> None:
def test_qr_mark_cannot_password_login_and_unicode_password_is_safe(monkeypatch) -> None:
import euniv.api as api_module
import euniv.service as service_module
from euniv.client import QR_PASSWORD_MARK
from euniv.crypto import encrypt_secret
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
monkeypatch.setattr(
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)
with SessionLocal() as db:
@@ -206,7 +216,7 @@ def test_qr_mark_cannot_password_login_and_unicode_password_is_safe() -> None:
assert second.status_code == 200
def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
def test_manual_jigsaw_keeps_image_pixels_and_retries(monkeypatch) -> None:
import euniv.api as api_module
import euniv.service as service_module
@@ -267,10 +277,14 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
"yxt_token": "yxt-manual",
}
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
monkeypatch.setattr(
api_module,
"login_and_store",
lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
db, employee_id, password, ManualClient, manual=manual, auto_attempts=auto_attempts
),
)
api_module.submit_jigsaw = service_module.submit_jigsaw
monkeypatch.setattr(api_module, "submit_jigsaw", service_module.submit_jigsaw)
client = TestClient(api_module.app)
started = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert started.status_code == 200
@@ -295,7 +309,7 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
assert decrypt_secret(account.password_cipher) == "secret-pass"
def test_browser_session_logout_and_revoke() -> None:
def test_browser_session_logout_and_revoke(monkeypatch) -> None:
import euniv.api as api_module
import euniv.service as service_module
@@ -306,8 +320,12 @@ def test_browser_session_logout_and_revoke() -> None:
calls["login"] += 1
return super().login(manual=manual, auto_attempts=auto_attempts)
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
monkeypatch.setattr(
api_module,
"login_and_store",
lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
db, employee_id, password, RememberClient, manual=manual, auto_attempts=auto_attempts
),
)
client = TestClient(api_module.app)
first = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
@@ -342,12 +360,16 @@ def test_browser_session_logout_and_revoke() -> None:
assert account.password_cipher == ""
def test_logout_keeps_the_other_browser_until_revoke() -> None:
def test_logout_keeps_the_other_browser_until_revoke(monkeypatch) -> 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(
monkeypatch.setattr(
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
),
)
first = TestClient(api_module.app)
assert first.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
@@ -496,16 +518,20 @@ def test_exam_and_training_details() -> None:
}
def test_home_sections_are_separate() -> None:
def test_home_sections_are_separate(monkeypatch) -> 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(
monkeypatch.setattr(
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_home_summary = lambda db, employee_id: {"name": "分段"}
api_module.fetch_home_exams = lambda db, employee_id: {"exams": [{"name": "一门考试"}]}
api_module.fetch_home_trainings = lambda db, employee_id: {"trainings": [{"name": "一门培训"}]}
monkeypatch.setattr(api_module, "fetch_home_summary", lambda db, employee_id: {"name": "分段"})
monkeypatch.setattr(api_module, "fetch_home_exams", lambda db, employee_id: {"exams": [{"name": "一门考试"}]})
monkeypatch.setattr(api_module, "fetch_home_trainings", lambda db, employee_id: {"trainings": [{"name": "一门培训"}]})
client = TestClient(api_module.app)
response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert response.status_code == 200
@@ -535,12 +561,16 @@ def test_period_page_is_not_fetched_twice() -> None:
assert len(calls) == 1
def test_user_can_set_proxy_with_or_without_password() -> None:
def test_user_can_set_proxy_with_or_without_password(monkeypatch) -> 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(
monkeypatch.setattr(
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
@@ -585,12 +615,16 @@ def test_user_can_set_proxy_with_or_without_password() -> None:
assert cleared.json()["scheme"] == "off"
def test_user_can_set_course_workers() -> None:
def test_user_can_set_course_workers(monkeypatch) -> 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(
monkeypatch.setattr(
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
@@ -604,12 +638,16 @@ def test_user_can_set_course_workers() -> None:
assert bad.status_code == 400
def test_user_can_set_monthly_study_start() -> None:
def test_user_can_set_monthly_study_start(monkeypatch) -> 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(
monkeypatch.setattr(
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
@@ -652,8 +690,12 @@ def test_user_can_start_and_stop_study_immediately(monkeypatch) -> 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(
monkeypatch.setattr(
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)
_freeze_beijing(monkeypatch, 2026, 11, 15)
@@ -679,12 +721,16 @@ def test_user_can_start_and_stop_study_immediately(monkeypatch) -> None:
assert bad.status_code == 400
def test_study_control_stays_stopped_when_month_hours_met() -> None:
def test_study_control_stays_stopped_when_month_hours_met(monkeypatch) -> 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(
monkeypatch.setattr(
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
@@ -706,8 +752,12 @@ def test_study_control_websocket_sends_snapshot(monkeypatch) -> None:
import euniv.service as service_module
from starlette.websockets import WebSocketDisconnect
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
monkeypatch.setattr(
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)
_freeze_beijing(monkeypatch, 2026, 11, 15)
@@ -730,15 +780,21 @@ def test_study_control_websocket_sends_snapshot(monkeypatch) -> None:
assert pong["started"] is False
def test_user_can_read_study_history() -> None:
def test_user_can_read_study_history(monkeypatch) -> 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(
monkeypatch.setattr(
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
monkeypatch.setattr(
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
@@ -768,14 +824,22 @@ def test_home_and_history_hours_follow_source(monkeypatch) -> 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(
monkeypatch.setattr(
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_home_summary = lambda db, employee_id: service_module.fetch_home_summary(
db, employee_id, FakeClient
monkeypatch.setattr(
api_module,
"fetch_home_summary",
lambda db, employee_id: service_module.fetch_home_summary(db, employee_id, FakeClient),
)
api_module.fetch_study_history = lambda db, employee_id: service_module.fetch_study_history(
db, employee_id, FakeClient
monkeypatch.setattr(
api_module,
"fetch_study_history",
lambda db, employee_id: service_module.fetch_study_history(db, employee_id, FakeClient),
)
from euniv.client import history_hour_totals
from euniv.study_window import CN_TZ
+2 -1
View File
@@ -209,6 +209,7 @@ def test_hours_watcher_stops_when_target_reached(monkeypatch) -> None:
def test_hours_watcher_history_source_uses_month_history(monkeypatch) -> None:
saved: list[tuple[str, str]] = []
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda eid, hours: saved.append((eid, hours)))
monkeypatch.setattr("admin.settings.hours_source_of", lambda: "history")
class _HistorySession:
async def month_history_minutes(self) -> int:
@@ -219,7 +220,7 @@ def test_hours_watcher_history_source_uses_month_history(monkeypatch) -> None:
async def main() -> None:
user_stop = asyncio.Event()
watcher = HoursWatcher(_HistorySession(), "u1", 600, user_stop, source="history")
watcher = HoursWatcher(_HistorySession(), "u1", 600, user_stop)
assert await watcher.refresh() is True
assert watcher.reached
assert saved == [("u1", "600")]
+9 -2
View File
@@ -309,6 +309,9 @@ def test_admin_can_probe_one_and_all_proxies(monkeypatch) -> None:
def test_is_proxy_failure_detects_connect_errors() -> None:
assert is_proxy_failure(httpx.ConnectError("boom"))
assert is_proxy_failure(httpx.ConnectTimeout("late"))
assert is_proxy_failure(httpx.ReadTimeout("slow"))
assert is_proxy_failure(httpx.ReadError("reset"))
assert is_proxy_failure(httpx.RemoteProtocolError("bad"))
assert not is_proxy_failure(RuntimeError("登录需要重新验证"))
@@ -343,7 +346,7 @@ def test_admin_proxy_page_and_pool_assignment() -> None:
assert detail.json()["enabled"] is True
def test_user_can_enable_pool_proxy() -> None:
def test_user_can_enable_pool_proxy(monkeypatch) -> None:
import euniv.api as api_module
import euniv.service as service_module
@@ -386,8 +389,12 @@ def test_user_can_enable_pool_proxy() -> None:
def credential_alive(self) -> bool:
return True
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
monkeypatch.setattr(
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
+28 -7
View File
@@ -35,6 +35,8 @@ const pageSizes = [20, 50, 100];
const kindTotal = computed(() => kinds.value.reduce((sum, item) => sum + item.count, 0));
const fetching = ref(false);
let poll = 0;
let disposed = false;
let loadSeq = 0;
function asCourse(value: unknown): CourseRow | null {
if (!isRecord(value) || typeof value.title !== "string") return null;
@@ -60,6 +62,7 @@ function courseKey(row: CourseRow, index: number) {
}
async function load(clamp = true) {
const seq = ++loadSeq;
if (items.value.length === 0) loading.value = true;
try {
const params = new URLSearchParams({
@@ -69,7 +72,14 @@ async function load(clamp = true) {
limit: String(pageSize.value),
});
const response = await fetch(`/api/admin/courses?${params}`);
if (disposed || seq !== loadSeq) return;
const payload = await response.json().catch(() => ({}));
if (disposed || seq !== loadSeq) return;
if (response.status === 401) {
stopPoll();
if (!items.value.length) setError("课程清单没有获取到。");
return;
}
if (!response.ok) {
setError("课程清单没有获取到。");
return;
@@ -93,19 +103,22 @@ async function load(clamp = true) {
await load(false);
}
} catch {
setError("课程清单没有获取到。");
if (!disposed && seq === loadSeq) setError("课程清单没有获取到。");
} finally {
loading.value = false;
if (seq === loadSeq) loading.value = false;
}
}
function startPoll() {
if (poll) return;
poll = window.setInterval(() => void load(), 3000);
if (disposed || poll) return;
poll = window.setTimeout(() => {
poll = 0;
if (!disposed) void load();
}, 3000);
}
function stopPoll() {
window.clearInterval(poll);
window.clearTimeout(poll);
poll = 0;
}
@@ -155,11 +168,19 @@ function search() {
void load();
}
function clearSearch() {
query.value = "";
search();
}
onMounted(() => {
void load();
});
onUnmounted(() => stopPoll());
onUnmounted(() => {
disposed = true;
stopPoll();
});
</script>
<template>
@@ -177,7 +198,7 @@ onUnmounted(() => stopPoll());
</template>
加载课程清单
</n-tooltip>
<n-input v-model:value="query" placeholder="名称或贡献者" clearable @clear="search" />
<n-input v-model:value="query" placeholder="名称或贡献者" clearable @clear="clearSearch" />
<n-button attr-type="submit">搜索</n-button>
</form>
</header>
+29 -7
View File
@@ -43,6 +43,8 @@ const fetching = ref(false);
const probingId = ref<number | null>(null);
const probingAll = ref(false);
let poll = 0;
let disposed = false;
let loadSeq = 0;
const kinds = computed<StatusOption[]>(() => [
{ name: "可用", value: "alive", count: alive.value },
@@ -113,6 +115,7 @@ function statusClass(row: ProxyRow) {
}
async function load(clamp = true) {
const seq = ++loadSeq;
if (items.value.length === 0) loading.value = true;
try {
const params = new URLSearchParams({
@@ -122,7 +125,14 @@ async function load(clamp = true) {
limit: String(pageSize.value),
});
const response = await fetch(`/api/admin/proxies?${params}`);
if (disposed || seq !== loadSeq) return;
const payload: unknown = await response.json().catch(() => ({}));
if (disposed || seq !== loadSeq) return;
if (response.status === 401) {
stopPoll();
if (!items.value.length) setError("代理列表没有获取到。");
return;
}
if (!response.ok) {
setError("代理列表没有获取到。");
return;
@@ -148,19 +158,22 @@ async function load(clamp = true) {
await load(false);
}
} catch {
setError("代理列表没有获取到。");
if (!disposed && seq === loadSeq) setError("代理列表没有获取到。");
} finally {
loading.value = false;
if (seq === loadSeq) loading.value = false;
}
}
function startPoll() {
if (poll) return;
poll = window.setInterval(() => void load(), 2000);
if (disposed || poll) return;
poll = window.setTimeout(() => {
poll = 0;
if (!disposed) void load();
}, 2000);
}
function stopPoll() {
window.clearInterval(poll);
window.clearTimeout(poll);
poll = 0;
}
@@ -238,6 +251,7 @@ async function probeAll() {
return;
}
for (let attempt = 0; attempt < 120; attempt += 1) {
if (disposed) return;
const status = await fetch("/api/admin/proxies/probe");
const body: unknown = await status.json().catch(() => ({}));
if (!status.ok || !isRecord(body)) break;
@@ -296,11 +310,19 @@ function search() {
void load();
}
function clearSearch() {
query.value = "";
search();
}
onMounted(() => {
void load();
});
onUnmounted(() => stopPoll());
onUnmounted(() => {
disposed = true;
stopPoll();
});
</script>
<template>
@@ -322,7 +344,7 @@ onUnmounted(() => stopPoll());
<n-button size="small" attr-type="button" :loading="probingAll" :disabled="probingAll || fetching" @click="probeAll">
测试{{ probeScope }}
</n-button>
<n-input v-model:value="query" placeholder="地址" clearable @clear="search" />
<n-input v-model:value="query" placeholder="地址" clearable @clear="clearSearch" />
<n-button attr-type="submit">搜索</n-button>
</form>
</header>
+15 -2
View File
@@ -26,11 +26,19 @@ const hoursSource = ref("api");
let savedTimer = 0;
function detailOf(payload: unknown, fallback: string) {
if (payload && typeof payload === "object" && "detail" in payload) {
if (!payload || typeof payload !== "object" || !("detail" in payload)) return fallback;
const detail = (payload as { detail?: unknown }).detail;
if (typeof detail === "string" && detail) return detail;
if (!Array.isArray(detail)) return fallback;
const texts = detail.flatMap((item) => {
if (typeof item === "string" && item) return [item];
if (item && typeof item === "object" && "msg" in item) {
const msg = (item as { msg?: unknown }).msg;
if (typeof msg === "string" && msg) return [msg];
}
return fallback;
return [];
});
return texts.length ? texts.join(";") : fallback;
}
function readNumber(value: unknown) {
@@ -107,6 +115,11 @@ async function save() {
return;
}
}
if (hbMode.value !== "manual") {
if (hbVideo.value == null) hbVideo.value = 30;
if (hbDocument.value == null) hbDocument.value = 120;
if (hbScorm.value == null) hbScorm.value = 120;
}
const adminUsername = username.value.trim();
if (!adminUsername) {
errorText.value = "请填写管理员用户名";
+53 -18
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { NAlert, NButton, NCheckbox, NDropdown, NForm, NFormItem, NIcon, NInputNumber, NModal, NRadioButton, NRadioGroup, NSelect, NTimePicker, NTooltip, useDialog, type DropdownOption } from "naive-ui";
import { EllipsisHorizontalOutline, EllipsisVerticalOutline, PauseOutline, PlayOutline, SettingsOutline } from "@vicons/ionicons5";
import { EllipsisHorizontalOutline, EllipsisVerticalOutline, PauseOutline, PlayOutline, RefreshOutline, SettingsOutline } from "@vicons/ionicons5";
import ProxyFields from "../../shared/ProxyFields.vue";
import { STUDY_DAY_DEFAULT, STUDY_DAY_MAX, STUDY_DAY_MIN, dayOptions, workerOptions } from "../../shared/studyFields";
import { isRecord, textOf } from "../../shared/text";
@@ -99,6 +99,7 @@ const tokenFields: { label: string; key: string }[] = [
];
const QR_PASSWORD_MARK = "扫码登陆";
let credentialRequest = 0;
let settingsRequest = 0;
let settingsBaseline: SettingsBaseline | null = null;
interface SettingsBaseline {
@@ -140,8 +141,16 @@ const startTime = computed({
});
function detailOf(payload: unknown, fallback: string) {
if (isRecord(payload) && typeof payload.detail === "string" && payload.detail) return payload.detail;
return fallback;
if (!isRecord(payload)) return fallback;
const detail = payload.detail;
if (typeof detail === "string" && detail) return detail;
if (!Array.isArray(detail)) return fallback;
const texts = detail.flatMap((item) => {
if (typeof item === "string" && item) return [item];
if (isRecord(item) && typeof item.msg === "string" && item.msg) return [item.msg];
return [];
});
return texts.length ? texts.join(";") : fallback;
}
function readValid(value: unknown): boolean | null {
@@ -493,34 +502,40 @@ function applyRowSettings(row: UserRow) {
async function openSettings(ids: string[]) {
if (!ids.length) return;
const current = ++settingsRequest;
const employeeId = ids.length === 1 ? ids[0] : "";
settingsIds.value = ids;
settingsReady.value = false;
resetSettingsForm();
settingsOpen.value = true;
if (ids.length !== 1) {
if (!employeeId) {
settingsBaseline = captureSettings();
settingsReady.value = true;
return;
}
const row = users.value.find((item) => item.employee_id === ids[0]);
const row = users.value.find((item) => item.employee_id === employeeId);
if (row) applyRowSettings(row);
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(ids[0])}/proxy`);
const response = await fetch(`/api/admin/users/${encodeURIComponent(employeeId)}/proxy`);
if (current !== settingsRequest || !settingsOpen.value) return;
const payload: unknown = await response.json().catch(() => ({}));
if (current !== settingsRequest || !settingsOpen.value) return;
if (!response.ok || !isRecord(payload)) {
proxyScheme.value = "keep";
settingsError.value = "代理没有获取到,这次不会修改代理。";
} else {
settingsError.value = "代理没有获取到,不能保存。";
return;
}
proxyScheme.value = textOf(payload.scheme) || "off";
proxyHost.value = textOf(payload.host);
proxyPort.value = typeof payload.port === "number" ? payload.port : null;
proxyUser.value = textOf(payload.username);
proxyHasPassword.value = payload.has_password === true;
}
} catch {
proxyScheme.value = "keep";
settingsError.value = "代理没有获取到,这次不会修改代理。";
if (current === settingsRequest && settingsOpen.value) {
settingsError.value = "代理没有获取到,不能保存。";
}
return;
}
if (current !== settingsRequest || !settingsOpen.value) return;
settingsBaseline = captureSettings();
settingsReady.value = true;
}
@@ -696,14 +711,26 @@ async function setStudy(ids: string[], action: "start" | "stop") {
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, action === "start" ? "没有开始。" : "没有停止。");
return;
}
await load();
} catch {
errorText.value = action === "start" ? "没有开始。" : "没有停止。";
} finally {
studyBusy.value = false;
}
const failed = errorText.value;
await load();
if (failed) errorText.value = failed;
studyBusy.value = false;
}
function confirmStudy(ids: string[], action: "start" | "stop") {
if (!ids.length || studyBusy.value) return;
const verb = action === "start" ? "立即开始" : "停止任务";
dialog.warning({
title: verb,
content: `${verb}已选 ${ids.length} 个账号?`,
positiveText: action === "start" ? "开始" : "停止",
negativeText: "取消",
onPositiveClick: () => setStudy(ids, action),
});
}
async function clearProxy(ids: string[]) {
@@ -772,6 +799,14 @@ onMounted(() => {
<section class="page admin-page">
<header class="page-head">
<div class="page-head-actions">
<n-tooltip>
<template #trigger>
<n-button quaternary circle :loading="loading" aria-label="刷新用户列表" @click="load">
<template #icon><n-icon><RefreshOutline /></n-icon></template>
</n-button>
</template>
刷新
</n-tooltip>
<n-tooltip>
<template #trigger>
<n-button quaternary circle :disabled="!pickedIds.length" aria-label="学习设置" @click="openSettings(pickedIds)">
@@ -782,7 +817,7 @@ onMounted(() => {
</n-tooltip>
<n-tooltip>
<template #trigger>
<n-button quaternary circle :disabled="!pickedIds.length" :loading="studyBusy" aria-label="立即开始" @click="setStudy(pickedIds, 'start')">
<n-button quaternary circle :disabled="!pickedIds.length" :loading="studyBusy" aria-label="立即开始" @click="confirmStudy(pickedIds, 'start')">
<template #icon><n-icon><PlayOutline /></n-icon></template>
</n-button>
</template>
@@ -790,7 +825,7 @@ onMounted(() => {
</n-tooltip>
<n-tooltip>
<template #trigger>
<n-button quaternary circle :disabled="!pickedIds.length" :loading="studyBusy" aria-label="停止任务" @click="setStudy(pickedIds, 'stop')">
<n-button quaternary circle :disabled="!pickedIds.length" :loading="studyBusy" aria-label="停止任务" @click="confirmStudy(pickedIds, 'stop')">
<template #icon><n-icon><PauseOutline /></n-icon></template>
</n-button>
</template>
+70 -37
View File
@@ -44,15 +44,16 @@ const avatarBroken = ref(false);
let refreshRunning = false;
let busy = false;
let studyTick = 0;
let studySocket: WebSocket | null = null;
let studySocket: PingSocket | null = null;
let studyReconnect = 0;
let studyPing = 0;
let studyFallback = 0;
let studyBackoff = 1000;
let studyClosed = false;
const nowTick = ref(Date.now());
const monthlyTarget = ref<number | null>(null);
const progressHours = ref("");
const progressTarget = ref(0);
const targetLoaded = ref(false);
const scheduleSaving = ref(false);
const scheduleError = ref("");
@@ -87,9 +88,9 @@ const studyFailed = computed(() => {
});
const monthProgress = computed(() => {
const match = String(summary.value?.month_hours ?? "").match(/(\d+)/);
const match = progressHours.value.match(/(\d+)/);
const current = match ? Number(match[1]) : 0;
const target = monthlyTarget.value ?? 0;
const target = progressTarget.value;
const pct = target > 0 ? Math.min(100, Math.round((current * 100) / target)) : 0;
return { current, target, pct };
});
@@ -114,6 +115,9 @@ const studyHint = computed(() => {
if (studyingWorkers.value.length) return "";
if (studyControl.value.hours_met) return "达到本月目标后不能再开始。改大目标并保存后才会再启动。";
if (studyFailed.value) return "点立即开始或保存定时配置会再启动。";
if (studyControl.value.state === "已停止" || studyControl.value.paused) {
return "本月已停止,下月定时照常;点立即开始可恢复。";
}
if (studyControl.value.started || studyControl.value.active) return "开始后会列出正在学的课。";
if (!studyControl.value.schedule_enabled) return "关闭定时后,只能点立即开始。";
return "到点后会自动开始。保存定时配置时,若已过点且未达标也会立刻启动。";
@@ -262,11 +266,13 @@ async function loadSummary() {
}
}
const settingsLoadError = ref("");
function refresh() {
if (refreshRunning) return;
refreshRunning = true;
refreshing.value = true;
void Promise.all([loadSummary(), loadStudyControl()]).finally(() => {
void Promise.all([loadSummary(), loadStudyControl(), loadSettings()]).finally(() => {
refreshRunning = false;
refreshing.value = false;
});
@@ -275,12 +281,14 @@ function refresh() {
async function loadTarget() {
try {
const res = await fetch("/api/settings/monthly-target");
if (res.ok) {
if (!res.ok) return false;
const data = await res.json();
monthlyTarget.value = data.monthly_target ?? 600;
targetLoaded.value = true;
return true;
} catch {
return false;
}
} catch { /* 静默 */ }
}
const startLoaded = ref(false);
@@ -307,7 +315,7 @@ const startTime = computed({
async function loadStart() {
try {
const res = await fetch("/api/settings/study-start");
if (res.ok) {
if (!res.ok) return false;
const data = await res.json();
startDay.value = typeof data.day === "number" ? data.day : STUDY_DAY_DEFAULT;
startHour.value = typeof data.hour === "number" ? data.hour : 0;
@@ -315,8 +323,10 @@ async function loadStart() {
startSecond.value = typeof data.second === "number" ? data.second : 0;
scheduleEnabled.value = data.enabled !== false;
startLoaded.value = true;
return true;
} catch {
return false;
}
} catch { /* 静默 */ }
}
const workersLoaded = ref(false);
@@ -326,12 +336,14 @@ const scheduleReady = computed(() => targetLoaded.value && startLoaded.value &&
async function loadWorkers() {
try {
const res = await fetch("/api/settings/course-workers");
if (res.ok) {
if (!res.ok) return false;
const data = await res.json();
courseWorkers.value = typeof data.workers === "number" ? data.workers : 1;
workersLoaded.value = true;
return true;
} catch {
return false;
}
} catch { /* 静默 */ }
}
async function putJson(url: string, body: Record<string, unknown>, fallback: string) {
@@ -441,7 +453,7 @@ async function loadProxy() {
try {
const res = await fetch("/api/settings/proxy");
const data = await res.json().catch(() => ({}));
if (!res.ok) return;
if (!res.ok) return false;
proxyScheme.value = typeof data.scheme === "string" && data.scheme ? data.scheme : "off";
proxyHost.value = typeof data.host === "string" ? data.host : "";
proxyPort.value = typeof data.port === "number" ? data.port : null;
@@ -450,7 +462,20 @@ async function loadProxy() {
proxyHasPassword.value = data.has_password === true;
proxyLoaded.value = true;
rememberProxy();
} catch { /* 静默 */ }
return true;
} catch {
return false;
}
}
async function loadSettings() {
const [target, start, workers, proxy] = await Promise.all([
loadTarget(),
loadStart(),
loadWorkers(),
loadProxy(),
]);
settingsLoadError.value = target && start && workers && proxy ? "" : "定时配置没有获取到。";
}
function proxyPasswordPayload() {
@@ -530,8 +555,12 @@ function applyStudyControl(payload: Record<string, unknown>) {
message: typeof payload.message === "string" ? payload.message : "",
workers: asWorkers(payload.workers),
};
if (typeof payload.month_hours === "string" && payload.month_hours && summary.value) {
summary.value = { ...summary.value, month_hours: payload.month_hours };
if (typeof payload.month_hours === "string") {
progressHours.value = payload.month_hours;
if (summary.value) summary.value = { ...summary.value, month_hours: payload.month_hours };
}
if (typeof payload.monthly_target === "number" && Number.isFinite(payload.monthly_target)) {
progressTarget.value = Math.trunc(payload.monthly_target);
}
}
@@ -572,20 +601,25 @@ function startStudyFallback() {
void tick();
}
type PingSocket = WebSocket & { ping?: number };
function clearSocketPing(ws: PingSocket) {
if (!ws.ping) return;
window.clearInterval(ws.ping);
ws.ping = 0;
}
function stopStudySocket() {
studyClosed = true;
if (studyReconnect) {
window.clearTimeout(studyReconnect);
studyReconnect = 0;
}
if (studyPing) {
window.clearInterval(studyPing);
studyPing = 0;
}
stopStudyFallback();
const ws = studySocket;
studySocket = null;
if (ws) {
clearSocketPing(ws);
ws.onclose = null;
ws.onerror = null;
ws.onmessage = null;
@@ -616,9 +650,10 @@ function connectStudySocket() {
scheduleStudyReconnect();
return;
}
studySocket = ws;
const socket = ws as PingSocket;
studySocket = socket;
let welcomed = false;
ws.onmessage = (event) => {
socket.onmessage = (event) => {
if (!welcomed) {
welcomed = true;
studyBackoff = 1000;
@@ -628,20 +663,18 @@ function connectStudySocket() {
if (data && typeof data === "object") applyStudyControl(data as Record<string, unknown>);
} catch { /* ignore */ }
};
ws.onopen = () => {
socket.onopen = () => {
stopStudyFallback();
void loadStudyControl();
if (studyPing) window.clearInterval(studyPing);
studyPing = window.setInterval(() => {
if (ws.readyState === WebSocket.OPEN) ws.send("ping");
clearSocketPing(socket);
socket.ping = window.setInterval(() => {
if (socket.readyState === WebSocket.OPEN) socket.send("ping");
}, 8000);
};
ws.onclose = (event) => {
if (studyPing) {
window.clearInterval(studyPing);
studyPing = 0;
}
if (studySocket === ws) studySocket = null;
socket.onclose = (event) => {
clearSocketPing(socket);
if (studySocket !== socket) return;
studySocket = null;
if (event.code === 4401 || event.code === 4403) {
studyClosed = true;
stopStudyFallback();
@@ -652,8 +685,8 @@ function connectStudySocket() {
scheduleStudyReconnect();
}
};
ws.onerror = () => {
ws.close();
socket.onerror = () => {
socket.close();
};
}
@@ -730,10 +763,6 @@ async function toggleStudy() {
onMounted(() => {
refresh();
loadTarget();
loadStart();
loadWorkers();
loadProxy();
connectStudySocket();
document.addEventListener("visibilitychange", onStudyVisible);
window.addEventListener("focus", studyWake);
@@ -808,6 +837,10 @@ onUnmounted(() => {
<h3>自动学习</h3>
</header>
<n-alert v-if="studyError" class="summary-error" type="error">{{ studyError }}</n-alert>
<n-alert v-if="settingsLoadError" class="summary-error" type="error">
{{ settingsLoadError }}
<n-button class="retry-settings" size="tiny" quaternary @click="loadSettings">重试</n-button>
</n-alert>
<n-alert v-if="scheduleError" class="summary-error" type="error">{{ scheduleError }}</n-alert>
<div class="study-card-body">
<div class="study-config">
+14 -3
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from "vue";
import { NButton, NDropdown, NIcon, NLayout, NLayoutSider, NMenu, NTooltip } from "naive-ui";
import { NButton, NDropdown, NIcon, NLayout, NLayoutSider, NMenu, NTooltip, useDialog } from "naive-ui";
import { LogOutOutline, MoonOutline, PersonOutline, SunnyOutline } from "@vicons/ionicons5";
import { isDark, toggleTheme } from "../shared/theme";
import { navOptions, type PageKey } from "./navigation";
@@ -11,6 +11,7 @@ import TrainingsView from "../features/trainings/TrainingsView.vue";
const props = defineProps<{ employeeId: string }>();
const emit = defineEmits<{ logout: []; revoke: [] }>();
const dialog = useDialog();
const page = ref<PageKey>(pageFromHash());
const collapsed = ref(window.innerWidth < 800);
const holdOpen = ref(false);
@@ -82,8 +83,18 @@ function onMenu(key: string) {
}
function onLogout(key: string) {
if (key === "revoke") emit("revoke");
else emit("logout");
if (key !== "revoke") {
emit("logout");
return;
}
dialog.warning({
title: "注销当前账号",
content: "注销后所有设备都会退出,正在进行的学习会停止,已保存的密码和登录凭证也会清除。",
positiveText: "注销",
negativeText: "取消",
positiveButtonProps: { type: "error" },
onPositiveClick: () => emit("revoke"),
});
}
</script>
+1 -1
View File
@@ -1646,7 +1646,7 @@ body .n-base-select-menu .n-base-select-option__content {
}
.compact-nform .n-form-item-label {
width: 100% !important;
width: 100%;
max-width: 100%;
height: auto;
}