refactor: 预留并行修复所需的共享接口

This commit is contained in:
2026-10-25 06:48:26 +08:00
parent d96f430a7d
commit 6b84a5e406
10 changed files with 179 additions and 42 deletions
+11
View File
@@ -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
+57
View File
@@ -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()
+15 -1
View File
@@ -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