diff --git a/backend/admin/identity.py b/backend/admin/identity.py index 8c81e75..6240b24 100644 --- a/backend/admin/identity.py +++ b/backend/admin/identity.py @@ -46,9 +46,5 @@ class AdminIdentity: with self._lock: return self._username - def password_cipher(self) -> str: - with self._lock: - return self._password_cipher - identity = AdminIdentity() diff --git a/backend/admin/settings.py b/backend/admin/settings.py index ac244a2..d03b318 100644 --- a/backend/admin/settings.py +++ b/backend/admin/settings.py @@ -124,27 +124,23 @@ def load_admin_identity() -> None: identity.replace(row.admin_username, row.admin_password_cipher) -def refresh_interval_seconds(db: Session | None = None) -> int: - if db is None: - from euniv.db import SessionLocal +def refresh_interval_seconds() -> int: + from euniv.db import SessionLocal - with SessionLocal() as owned: - return int(load_config(owned).refresh_interval_minutes) * 60 - return int(load_config(db).refresh_interval_minutes) * 60 + with SessionLocal() as owned: + return int(load_config(owned).refresh_interval_minutes) * 60 def auto_attempt_count(db: Session) -> int: return int(load_config(db).auto_jigsaw_attempts) -def heartbeat_intervals(db: Session | None = None) -> dict: +def heartbeat_intervals() -> dict: """返回 {mode, video, document, scorm}。mode 为 'auto' 时三个值仅作备用。""" - if db is None: - from euniv.db import SessionLocal - with SessionLocal() as owned: - row = load_config(owned) - else: - row = load_config(db) + from euniv.db import SessionLocal + + with SessionLocal() as owned: + row = load_config(owned) return { "mode": row.heartbeat_interval_mode or "manual", "video": int(row.heartbeat_video_seconds), diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 0391df7..f3b9a8c 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -655,7 +655,6 @@ def parse_course_page(page: str) -> dict: kind = re.search(r'class="(Knowledge_[A-Za-z]+)"', row) contributor = re.search(r"title='([^']*)'[^>]*href=\"/myhome\.htm", row) numbers = re.findall(r'\s*([^<]*)', row) - comments = re.search(r"", row) courses.append({ "path": link.group(1), "title": unescape(link.group(2)).strip(), @@ -665,7 +664,6 @@ def parse_course_page(page: str) -> dict: "learners": numbers[1].strip() if len(numbers) > 1 else "", "released_on": numbers[2].strip() if len(numbers) > 2 else "", "updated_on": numbers[3].strip() if len(numbers) > 3 else "", - "comments": comments.group(1) if comments else "", }) return { "courses": courses, diff --git a/backend/euniv/courses.py b/backend/euniv/courses.py index 47e9864..60181ed 100644 --- a/backend/euniv/courses.py +++ b/backend/euniv/courses.py @@ -113,7 +113,6 @@ def course_page(db: Session, query: str, offset: int, limit: int, kind: str = "" "learners": row.learners, "released_on": row.released_on, "updated_on": row.updated_on, - "comments": row.comments, } for row in rows ], diff --git a/backend/euniv/encrypt.py b/backend/euniv/encrypt.py index d51d6db..afc932e 100644 --- a/backend/euniv/encrypt.py +++ b/backend/euniv/encrypt.py @@ -40,14 +40,6 @@ _config: dict[str, Any] = { } -def reset_encrypt_config() -> None: - with _lock: - _config["path"] = DEFAULT_ENCRYPT_PATH - _config["js_url"] = DEFAULT_JS_URL - _config["loaded_at"] = 0.0 - _config["retry_at"] = 0.0 - - def _script_host_allowed(url: str) -> bool: parsed = urlparse(url) if parsed.scheme != "https" or parsed.username or parsed.password: @@ -159,15 +151,6 @@ def _note_fetch_failure() -> None: _config["retry_at"] = time.time() + _FAIL_COOLDOWN -def refresh_encrypt_config(client: httpx.Client, origin: str, user_agent: str) -> None: - if not _stale(): - return - with _fetch_guard: - if not _stale(): - return - _fetch_js_config(client.get, origin, user_agent) - - async def refresh_encrypt_config_async( client: httpx.AsyncClient, origin: str, user_agent: str ) -> None: @@ -186,23 +169,6 @@ async def refresh_encrypt_config_async( _fetch_guard.release() -def _fetch_js_config(get, origin: str, user_agent: str) -> None: - url = _js_url(origin) - if not _script_host_allowed(url): - log.warning("播放脚本地址不在允许的主机上") - _note_fetch_failure() - return - try: - resp = get(url, headers={"User-Agent": user_agent, "Referer": origin.rstrip("/") + "/"}) - if resp.status_code == 200 and resp.text: - _update_from_js(resp.text) - return - log.warning("读取播放脚本失败:HTTP %s", getattr(resp, "status_code", "")) - except Exception: - log.warning("读取播放脚本失败", exc_info=True) - _note_fetch_failure() - - async def _fetch_js_config_async( client: httpx.AsyncClient, origin: str, user_agent: str ) -> None: @@ -267,13 +233,6 @@ def parse_encrypt_response(resp: httpx.Response) -> str: raise RuntimeError(f"GetEncryptRequest 失败: {raw[:200]}") -def fetch_encryption( - client: httpx.Client, body_json: str, *, origin: str, user_agent: str -) -> str: - refresh_encrypt_config(client, origin, user_agent) - return _post_encryption(client.post, body_json, origin, user_agent) - - async def fetch_encryption_async( client: httpx.AsyncClient, body_json: str, *, origin: str, user_agent: str ) -> str: @@ -281,13 +240,6 @@ async def fetch_encryption_async( return await _post_encryption_async(client, body_json, origin, user_agent) -def _post_encryption(post, body_json: str, origin: str, user_agent: str) -> str: - url = encrypt_url(origin) - headers = encrypt_headers(origin, user_agent) - resp = post(url, content=encrypt_payload(body_json), headers=headers) - return parse_encrypt_response(resp) - - async def _post_encryption_async( client: httpx.AsyncClient, body_json: str, origin: str, user_agent: str ) -> str: diff --git a/backend/euniv/proxy_pool.py b/backend/euniv/proxy_pool.py index 5b13eb6..900d118 100644 --- a/backend/euniv/proxy_pool.py +++ b/backend/euniv/proxy_pool.py @@ -49,7 +49,6 @@ _STATUS = {STATUS_ALIVE: "可用", STATUS_DEAD: "失效", STATUS_NEW: "待检测 _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": ""} @@ -680,10 +679,8 @@ def _reset_pool_running() -> None: def start_proxy_pool() -> threading.Event: - global _stop _reset_pool_running() stop = threading.Event() - _stop = stop def loop() -> None: if stop.wait(8): diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index 9e23dca..f0f9aec 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -696,8 +696,7 @@ def test_settings_do_not_expose_process_switches() -> None: "hours_source", } assert body["hours_source"] == "api" - assert identity.password_cipher() - assert verify_password(identity.password_cipher(), INITIAL_PASSWORD) + assert identity.password_ok(INITIAL_PASSWORD) def test_admin_can_set_and_clear_proxy_for_selected_users() -> None: diff --git a/backend/tests/test_courses.py b/backend/tests/test_courses.py index 40abe56..2704b3b 100644 --- a/backend/tests/test_courses.py +++ b/backend/tests/test_courses.py @@ -33,7 +33,6 @@ def test_parse_course_page_reads_a_catalog_row() -> None: "learners": "1513", "released_on": "2026-10-16", "updated_on": "2026-10-16", - "comments": "5", }] diff --git a/backend/tests/test_encrypt.py b/backend/tests/test_encrypt.py index dba9fb1..ac86442 100644 --- a/backend/tests/test_encrypt.py +++ b/backend/tests/test_encrypt.py @@ -1,17 +1,20 @@ +import asyncio import inspect import httpx from euniv import autostudy as autostudy_mod from euniv import client as client_mod -from euniv.encrypt import ( - encrypt_path_from_js, - encrypt_payload, - fetch_encryption, - note_play_html, - parse_encrypt_response, - reset_encrypt_config, -) +from euniv import encrypt as encrypt_mod +from euniv.encrypt import encrypt_path_from_js, encrypt_payload, fetch_encryption_async, note_play_html, parse_encrypt_response + + +def _reset_encrypt() -> None: + with encrypt_mod._lock: + encrypt_mod._config["path"] = encrypt_mod.DEFAULT_ENCRYPT_PATH + encrypt_mod._config["js_url"] = encrypt_mod.DEFAULT_JS_URL + encrypt_mod._config["loaded_at"] = 0.0 + encrypt_mod._config["retry_at"] = 0.0 def test_short_secret_is_rejected(monkeypatch) -> None: @@ -54,7 +57,7 @@ def test_parse_encrypt_response_accepts_wcf_shapes() -> None: def test_note_play_html_and_js_path() -> None: - reset_encrypt_config() + _reset_encrypt() html = ( '' @@ -68,7 +71,7 @@ def test_note_play_html_and_js_path() -> None: def test_fetch_encryption_posts_player_body() -> None: - reset_encrypt_config() + _reset_encrypt() seen: dict[str, bytes] = {} def handler(request: httpx.Request) -> httpx.Response: @@ -81,14 +84,18 @@ def test_fetch_encryption_posts_player_body() -> None: seen["body"] = request.content return httpx.Response(200, json={"Status": "OK", "Data": "b" * 32}) - with httpx.Client(transport=httpx.MockTransport(handler)) as client: - digest = fetch_encryption( - client, - '{"knowledgeId":"k1"}', - origin="https://euniv.zte.com.cn", - user_agent="UA", - ) - assert digest == "b" * 32 + async def main() -> None: + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + digest = await fetch_encryption_async( + client, + '{"knowledgeId":"k1"}', + origin="https://euniv.zte.com.cn", + user_agent="UA", + ) + assert digest == "b" * 32 + + asyncio.run(main()) assert seen["content_type"] == b"text/json" assert seen["body"] == b'{"body":"{\\"knowledgeId\\":\\"k1\\"}"}' diff --git a/backend/tests/test_study_push.py b/backend/tests/test_study_push.py index 053ea38..c1a4d07 100644 --- a/backend/tests/test_study_push.py +++ b/backend/tests/test_study_push.py @@ -15,6 +15,15 @@ class _Socket: self.payloads.append(payload) +async def _until(done) -> None: + loop = asyncio.get_running_loop() + deadline = loop.time() + 1 + while not done(): + if loop.time() >= deadline: + raise AssertionError("等待条件没有达成") + await asyncio.sleep(0) + + def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None: socket = _Socket() monkeypatch.setattr("euniv.study_control.payload_for", lambda eid: {"eid": eid, "n": len(socket.payloads)}) @@ -30,14 +39,13 @@ def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None: study_push.register("u1", socket) try: study_push.notify("u1") - await asyncio.sleep(0.05) - assert len(socket.payloads) == 1 + await _until(lambda: len(socket.payloads) == 1) study_push.notify("u1") - await asyncio.sleep(0.05) + await _until(lambda: "u1" in study_push._pending or len(socket.payloads) > 1) assert len(socket.payloads) == 1 + assert "u1" in study_push._pending study_push.notify("u1", urgent=True) - await asyncio.sleep(0.05) - assert len(socket.payloads) == 2 + await _until(lambda: len(socket.payloads) == 2) assert socket.payloads[-1]["eid"] == "u1" finally: for handle in list(study_push._pending.values()): diff --git a/web/src/features/history/HoursHistoryView.vue b/web/src/features/history/HoursHistoryView.vue index 9f40d8a..da0c594 100644 --- a/web/src/features/history/HoursHistoryView.vue +++ b/web/src/features/history/HoursHistoryView.vue @@ -173,7 +173,7 @@ onMounted(refresh);