From 6b84a5e4069cdd55b39dc0c4baa63351535ece5f Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 25 Oct 2026 06:48:26 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E9=A2=84=E7=95=99=E5=B9=B6?= =?UTF-8?q?=E8=A1=8C=E4=BF=AE=E5=A4=8D=E6=89=80=E9=9C=80=E7=9A=84=E5=85=B1?= =?UTF-8?q?=E4=BA=AB=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/features/download/ids.py | 15 +------ backend/app/features/download/jobs.py | 47 ++++++++++--------- backend/app/features/download/journal.py | 6 +++ backend/app/features/download/router.py | 1 - backend/app/platform/client.py | 38 ++++++++++++++-- backend/app/shared/ids.py | 11 +++++ backend/app/shared/paths.py | 57 ++++++++++++++++++++++++ backend/app/shared/state.py | 16 ++++++- backend/tests/conftest.py | 26 +++++++++++ backend/tests/test_core.py | 4 +- 10 files changed, 179 insertions(+), 42 deletions(-) create mode 100644 backend/app/shared/ids.py create mode 100644 backend/tests/conftest.py diff --git a/backend/app/features/download/ids.py b/backend/app/features/download/ids.py index 2d7b60b..a241a89 100644 --- a/backend/app/features/download/ids.py +++ b/backend/app/features/download/ids.py @@ -6,6 +6,8 @@ import csv import io from pathlib import Path +from app.shared.ids import normalize_id + _HEADER_KEYS = { "栅格id", "20米栅格id", @@ -19,19 +21,6 @@ _HEADER_KEYS = { } -def normalize_id(value) -> str: - if value is None: - return "" - text = str(value).strip().strip("\ufeff") - text = text.translate(str.maketrans("0123456789", "0123456789")) - text = "".join(text.split()) - if text.endswith(".0") and text[:-2].isdigit(): - text = text[:-2] - if not text or not text.isdigit(): - return "" - return text - - def _header_index(header: list[str]) -> int | None: for index, name in enumerate(header): key = name.strip().lower().replace(" ", "").replace("_", "") diff --git a/backend/app/features/download/jobs.py b/backend/app/features/download/jobs.py index b55ff68..198d53c 100644 --- a/backend/app/features/download/jobs.py +++ b/backend/app/features/download/jobs.py @@ -48,6 +48,9 @@ class DownloadJob: listing_done: bool = True last_flush: float = 0.0 failures: list[dict[str, str]] = field(default_factory=list) + paused_by: str = "" + stopping: bool = False + failed_tiles: list = field(default_factory=list) subscribers: list[asyncio.Queue] = field(default_factory=list) task: asyncio.Task | None = None cancel_event: asyncio.Event = field(default_factory=asyncio.Event) @@ -62,6 +65,9 @@ class DownloadJob: def is_active(self) -> bool: return self.task is not None and not self.task.done() + def load_ids(self) -> list[str]: + return self.grid_ids + def snapshot(self) -> dict: return { "id": self.id, @@ -84,6 +90,9 @@ class DownloadJob: "fileBytes": _file_bytes(self.csv_path), "csvPath": str(self.csv_path), "failures": self.failures[-20:], + "pausedBy": self.paused_by, + "stopping": self.stopping, + "failedTiles": list(self.failed_tiles), "createdAt": self.created_at, "name": f"{'5G' if self.network == 'NR' else '4G'} · {self.city_name} · {self.month}", } @@ -185,28 +194,26 @@ class JobManager: total += 1 return total - def hydrate(self) -> None: - """进程重启后,把仍在等待的任务装回内存,空位出现时可以继续排。""" - if not DATA_DIR.exists(): - return - for directory in DATA_DIR.iterdir(): - if not directory.is_dir() or _JOB_ID.fullmatch(directory.name) is None: + def suspend_all(self, reason: str, mark: str) -> None: + for job in self.jobs.values(): + if job.status not in {"running", "queued"}: continue - if directory.name in self.jobs: - continue - path = directory / "job.json" - if not path.exists(): - continue - try: - data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - continue - if data.get("status") != "queued" or data.get("id") != directory.name: - continue - try: - self.jobs[directory.name] = self._load(directory.name) - except NqiError: + if job.status == "running": + job.run_event.clear() + job.status = "paused" + job.paused_by = mark + job.message = reason + job.save() + + def resume_marked(self, mark: str) -> None: + for job in self.jobs.values(): + if job.paused_by != mark: continue + job.paused_by = "" + if job.status == "paused": + job.status = "queued" + job.message = "等待中" + job.save() def queued_jobs(self) -> list[DownloadJob]: waiting = [job for job in self.jobs.values() if job.status == "queued"] diff --git a/backend/app/features/download/journal.py b/backend/app/features/download/journal.py index 318a16e..6858478 100644 --- a/backend/app/features/download/journal.py +++ b/backend/app/features/download/journal.py @@ -76,6 +76,12 @@ class CsvJournal: self.completed.add(grid_id) return len(rows) + def commit_many(self, items) -> int: + written = 0 + for grid_id, rows in items: + written += self.write_rows(grid_id, rows) + return written + def close(self) -> None: with self._lock: if self._file is not None: diff --git a/backend/app/features/download/router.py b/backend/app/features/download/router.py index 72c692a..d1519f2 100644 --- a/backend/app/features/download/router.py +++ b/backend/app/features/download/router.py @@ -53,7 +53,6 @@ def fill_slots() -> None: client = state.client if client is None: return - state.jobs.hydrate() while state.jobs.running_count() < state.jobs.max_concurrent: waiting = state.jobs.queued_jobs() if not waiting: diff --git a/backend/app/platform/client.py b/backend/app/platform/client.py index a5768de..6b792a1 100644 --- a/backend/app/platform/client.py +++ b/backend/app/platform/client.py @@ -16,7 +16,7 @@ import httpx from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding -from app.features.download.ids import normalize_id +from app.shared.ids import normalize_id from app.platform.constants import ( APP_KEY, CAS_CAPTCHA, @@ -45,6 +45,10 @@ class NqiError(Exception): pass +class NqiAuthError(NqiError): + pass + + def rsa_encrypt(public_key_b64: str, text: str) -> str: der = base64.b64decode(public_key_b64) key = serialization.load_der_public_key(der) @@ -554,16 +558,32 @@ class NqiClient: records.extend(extra) return records + async def _request(self, method: str, url: str, *, check_auth: bool = True, **kwargs) -> httpx.Response: + send = getattr(self.client, method.lower()) + try: + response = await send(url, **kwargs) + except httpx.TimeoutException as exc: + raise NqiError("平台响应超时,请稍后重试") from exc + except httpx.RequestError as exc: + raise NqiError("连接失败,请稍后重试") from exc + except RuntimeError as exc: + if "client has been closed" in str(exc): + raise NqiAuthError("需要重新登录") from exc + raise + if check_auth and (response.status_code in {401, 403} or _landed_on_login(response)): + raise NqiAuthError("登录已失效,请重新登录") + return response + async def _signed_get(self, url: str, params: dict) -> dict: headers = build_sign(params) headers["Referer"] = f"{ORIGIN}/pro-problem-warehouse-web/" - response = await self.client.get(url, params=params, headers=headers) + response = await self._request("GET", url, params=params, headers=headers) return _api_payload(response) async def _signed_post(self, url: str, body: dict) -> dict: headers = build_sign({}) headers["Referer"] = f"{ORIGIN}/pro-problem-warehouse-web/" - response = await self.client.post(url, json=body, headers=headers) + response = await self._request("POST", url, json=body, headers=headers) return _api_payload(response) @@ -647,9 +667,19 @@ def _media_type(response: httpx.Response) -> str: return raw or "image/jpeg" +def _landed_on_login(response: httpx.Response) -> bool: + url = getattr(response, "url", None) + if url is None: + return False + path = getattr(url, "path", "") or "" + if path: + return path.rstrip("/").endswith("/cas/login") + return "/cas/login" in str(url) + + def _json_or_error(response: httpx.Response, fallback: str) -> dict: if response.status_code in {401, 403}: - raise NqiError("登录已失效,请重新登录") + raise NqiAuthError("登录已失效,请重新登录") try: data = response.json() except json.JSONDecodeError as exc: diff --git a/backend/app/shared/ids.py b/backend/app/shared/ids.py new file mode 100644 index 0000000..6a2b5ae --- /dev/null +++ b/backend/app/shared/ids.py @@ -0,0 +1,11 @@ +def normalize_id(value) -> str: + if value is None: + return "" + text = str(value).strip().strip("\ufeff") + text = text.translate(str.maketrans("0123456789", "0123456789")) + text = "".join(text.split()) + if text.endswith(".0") and text[:-2].isdigit(): + text = text[:-2] + if not text or not text.isdigit(): + return "" + return text diff --git a/backend/app/shared/paths.py b/backend/app/shared/paths.py index 0ba9c54..979422b 100644 --- a/backend/app/shared/paths.py +++ b/backend/app/shared/paths.py @@ -9,5 +9,62 @@ def _data_root() -> Path: return Path(__file__).resolve().parents[3] / "data" +def _known_downloads() -> Path | None: + """读取系统登记的下载目录。失败时返回 None。""" + if os.name != "nt": + return None + try: + import ctypes + from ctypes import wintypes + + class _GUID(ctypes.Structure): + _fields_ = [ + ("Data1", wintypes.DWORD), + ("Data2", wintypes.WORD), + ("Data3", wintypes.WORD), + ("Data4", wintypes.BYTE * 8), + ] + + folder_id = _GUID( + 0x374DE290, + 0x123F, + 0x4565, + (wintypes.BYTE * 8)(0x91, 0x64, 0x39, 0xC4, 0x92, 0x5E, 0x46, 0x7B), + ) + pointer = ctypes.c_wchar_p() + shell32 = ctypes.WinDLL("shell32", use_last_error=True) + shell32.SHGetKnownFolderPath.argtypes = [ + ctypes.POINTER(_GUID), + wintypes.DWORD, + wintypes.HANDLE, + ctypes.POINTER(ctypes.c_wchar_p), + ] + shell32.SHGetKnownFolderPath.restype = wintypes.LONG + result = shell32.SHGetKnownFolderPath(ctypes.byref(folder_id), 0, None, ctypes.byref(pointer)) + if result != 0 or not pointer.value: + return None + folder = Path(pointer.value) + try: + ole32 = ctypes.WinDLL("ole32") + ole32.CoTaskMemFree.argtypes = [ctypes.c_void_p] + ole32.CoTaskMemFree(ctypes.cast(pointer, ctypes.c_void_p)) + except Exception: + pass + return folder + except Exception: + return None + + +def _download_root() -> Path: + override = os.environ.get("NQI_DOWNLOAD_DIR") + if override: + return Path(override) + base = _known_downloads() + if base is None: + base = Path.home() / "Downloads" + return base / "NqiToolsDownload" + + DATA_ROOT = _data_root() DOWNLOAD_DIR = DATA_ROOT / "jobs" +DOWNLOAD_ROOT = _download_root() diff --git a/backend/app/shared/state.py b/backend/app/shared/state.py index 40f8f15..9cdd459 100644 --- a/backend/app/shared/state.py +++ b/backend/app/shared/state.py @@ -1,7 +1,7 @@ from fastapi import HTTPException from app.features.download.jobs import JobManager -from app.platform.client import LoginChallenge, NqiClient +from app.platform.client import LoginChallenge, NqiAuthError, NqiClient class AppState: @@ -10,8 +10,22 @@ class AppState: self.client: NqiClient | None = None self.user: dict | None = None self.jobs = JobManager() + self.expired = False + + def get_client(self) -> NqiClient: + if self.expired: + raise NqiAuthError("登录已失效,请重新登录") + if self.client is None or self.user is None: + raise NqiAuthError("需要重新登录") + return self.client + + def on_session_expired(self, reason: str) -> None: + self.expired = True + self.jobs.suspend_all(reason, mark="expired") def require_client(self) -> NqiClient: + if self.expired: + raise HTTPException(status_code=401, detail="登录已失效,请重新登录") if self.client is None or self.user is None: raise HTTPException(status_code=401, detail="请先登录") return self.client diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 0000000..88128ea --- /dev/null +++ b/backend/tests/conftest.py @@ -0,0 +1,26 @@ +"""在导入 app 之前把数据和下载目录指到临时目录。""" + +import os +import sys +import tempfile +from pathlib import Path + +_TEMP = Path(__file__).resolve().parents[2] / "Temp" +_TEMP.mkdir(parents=True, exist_ok=True) +_ROOT = Path(tempfile.mkdtemp(prefix="pytest-", dir=_TEMP)) +os.environ["NQI_DATA_DIR"] = str(_ROOT / "data") +os.environ["NQI_DOWNLOAD_DIR"] = str(_ROOT / "downloads") + +if "app" in sys.modules or "app.shared.paths" in sys.modules: + raise RuntimeError("测试必须在导入 app 之前设置 NQI_DATA_DIR 和 NQI_DOWNLOAD_DIR") + + +def pytest_configure() -> None: + from app.shared.paths import DATA_ROOT, DOWNLOAD_ROOT + + if DATA_ROOT != Path(os.environ["NQI_DATA_DIR"]): + raise RuntimeError("DATA_ROOT 没有使用 NQI_DATA_DIR") + if DOWNLOAD_ROOT != Path(os.environ["NQI_DOWNLOAD_DIR"]): + raise RuntimeError("DOWNLOAD_ROOT 没有使用 NQI_DOWNLOAD_DIR") + if DOWNLOAD_ROOT.exists(): + raise RuntimeError("导入时不应创建下载目录") diff --git a/backend/tests/test_core.py b/backend/tests/test_core.py index 9fb86b3..f81b5a5 100644 --- a/backend/tests/test_core.py +++ b/backend/tests/test_core.py @@ -487,9 +487,7 @@ def test_only_the_task_limit_runs(tmp_path: Path, monkeypatch): assert manager.place(third) == "run" assert manager.place(first) == "wait" manager.jobs.clear() - manager.hydrate() - assert first.id in manager.jobs - assert manager.jobs[first.id].status == "queued" + assert first.id not in manager.jobs assert third.id not in manager.jobs