117 lines
3.6 KiB
Python
117 lines
3.6 KiB
Python
"""本机保存的登录凭证。只存平台会话,不存密码。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from datetime import datetime
|
|
|
|
import httpx
|
|
|
|
from app.platform.client import NqiClient, NqiError
|
|
from app.shared.paths import DATA_ROOT
|
|
|
|
STORE = DATA_ROOT / "sessions.json"
|
|
|
|
|
|
def _read() -> list[dict]:
|
|
if not STORE.is_file():
|
|
return []
|
|
try:
|
|
data = json.loads(STORE.read_text(encoding="utf-8"))
|
|
except (OSError, json.JSONDecodeError):
|
|
return []
|
|
accounts = data.get("accounts") if isinstance(data, dict) else None
|
|
if not isinstance(accounts, list):
|
|
return []
|
|
return [item for item in accounts if isinstance(item, dict) and item.get("loginId") and item.get("cookies")]
|
|
|
|
|
|
def _write(accounts: list[dict]) -> None:
|
|
STORE.parent.mkdir(parents=True, exist_ok=True)
|
|
payload = json.dumps({"accounts": accounts}, ensure_ascii=False, indent=2)
|
|
temporary = STORE.with_suffix(".json.tmp")
|
|
temporary.write_text(payload, encoding="utf-8")
|
|
temporary.replace(STORE)
|
|
|
|
|
|
def remember(user: dict, cookies: list[dict]) -> None:
|
|
login_id = str(user.get("loginId") or "").strip()
|
|
if not login_id or not cookies:
|
|
return
|
|
accounts = [item for item in _read() if item.get("loginId") != login_id]
|
|
accounts.insert(
|
|
0,
|
|
{
|
|
"loginId": login_id,
|
|
"userName": user.get("userName") or "",
|
|
"cityName": user.get("cityName") or "",
|
|
"orgName": user.get("orgName") or "",
|
|
"savedAt": datetime.now().isoformat(timespec="seconds"),
|
|
"cookies": cookies,
|
|
},
|
|
)
|
|
_write(accounts)
|
|
|
|
|
|
def forget(login_id: str) -> None:
|
|
_write([item for item in _read() if item.get("loginId") != login_id])
|
|
|
|
|
|
def public_view(item: dict) -> dict:
|
|
return {
|
|
"loginId": item.get("loginId") or "",
|
|
"userName": item.get("userName") or "",
|
|
"cityName": item.get("cityName") or "",
|
|
"orgName": item.get("orgName") or "",
|
|
}
|
|
|
|
|
|
async def available_accounts() -> list[dict]:
|
|
"""向平台确认每条凭证。失效的删掉,暂时连不上的先留着但不显示。"""
|
|
kept: list[dict] = []
|
|
visible: list[dict] = []
|
|
for item in _read():
|
|
client = NqiClient()
|
|
try:
|
|
client.import_cookies(item.get("cookies") or [])
|
|
user = await client.current_user()
|
|
except NqiError:
|
|
continue
|
|
except (httpx.TimeoutException, httpx.RequestError):
|
|
kept.append(item)
|
|
continue
|
|
else:
|
|
item.update(
|
|
{
|
|
"loginId": user["loginId"] or item.get("loginId"),
|
|
"userName": user["userName"],
|
|
"cityName": user["cityName"],
|
|
"orgName": user["orgName"],
|
|
}
|
|
)
|
|
kept.append(item)
|
|
visible.append(public_view(item))
|
|
finally:
|
|
await client.aclose()
|
|
_write(kept)
|
|
return visible
|
|
|
|
|
|
async def resume(login_id: str) -> tuple[NqiClient, dict]:
|
|
matched = next((item for item in _read() if item.get("loginId") == login_id), None)
|
|
if matched is None:
|
|
raise NqiError("这个账号的登录已失效")
|
|
client = NqiClient()
|
|
try:
|
|
client.import_cookies(matched.get("cookies") or [])
|
|
user = await client.current_user()
|
|
except NqiError:
|
|
await client.aclose()
|
|
forget(login_id)
|
|
raise NqiError("这个账号的登录已失效")
|
|
except (httpx.TimeoutException, httpx.RequestError):
|
|
await client.aclose()
|
|
raise NqiError("连接失败,请稍后重试")
|
|
remember(user, client.export_cookies())
|
|
return client, user
|