fix: 并发确认已保存账号,写回前重新读取再合并
This commit is contained in:
@@ -10,7 +10,7 @@ import uuid
|
|||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, HTTPException
|
||||||
|
|
||||||
from app.platform.client import NqiError, needs_captcha
|
from app.platform.client import NqiError, needs_captcha
|
||||||
from app.platform.sessions import available_accounts, remember, resume
|
from app.platform.sessions import available_accounts, remember_account, resume
|
||||||
from app.shared.state import state
|
from app.shared.state import state
|
||||||
|
|
||||||
logger = logging.getLogger("nqi.auth")
|
logger = logging.getLogger("nqi.auth")
|
||||||
@@ -129,7 +129,7 @@ async def login(body: dict) -> dict:
|
|||||||
pass
|
pass
|
||||||
raise HTTPException(status_code=400, detail=message) from exc
|
raise HTTPException(status_code=400, detail=message) from exc
|
||||||
challenge.password = ""
|
challenge.password = ""
|
||||||
remember(user, client.export_cookies())
|
await remember_account(user, client.export_cookies())
|
||||||
state.flows.pop(session_id, None)
|
state.flows.pop(session_id, None)
|
||||||
if state.client is not None and state.client is not client:
|
if state.client is not None and state.client is not client:
|
||||||
await state.client.aclose()
|
await state.client.aclose()
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ class NqiClient:
|
|||||||
self.client.cookies.set(
|
self.client.cookies.set(
|
||||||
cookie["name"],
|
cookie["name"],
|
||||||
cookie.get("value", ""),
|
cookie.get("value", ""),
|
||||||
domain=cookie.get("domain") or None,
|
domain=cookie.get("domain") or "",
|
||||||
path=cookie.get("path") or "/",
|
path=cookie.get("path") or "/",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from app.platform.sessions import remember
|
from app.platform.sessions import remember_account
|
||||||
from app.shared.state import state
|
from app.shared.state import state
|
||||||
|
|
||||||
logger = logging.getLogger("nqi.auth")
|
logger = logging.getLogger("nqi.auth")
|
||||||
@@ -18,7 +18,7 @@ async def refresh_saved_session() -> None:
|
|||||||
return
|
return
|
||||||
refreshed = await client.touch_session()
|
refreshed = await client.touch_session()
|
||||||
state.user = refreshed
|
state.user = refreshed
|
||||||
remember(refreshed, client.export_cookies())
|
await remember_account(refreshed, client.export_cookies())
|
||||||
|
|
||||||
|
|
||||||
async def session_keepalive() -> None:
|
async def session_keepalive() -> None:
|
||||||
|
|||||||
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
@@ -10,7 +12,10 @@ import httpx
|
|||||||
from app.platform.client import NqiAuthError, NqiClient, NqiError
|
from app.platform.client import NqiAuthError, NqiClient, NqiError
|
||||||
from app.shared.paths import DATA_ROOT
|
from app.shared.paths import DATA_ROOT
|
||||||
|
|
||||||
|
logger = logging.getLogger("nqi.auth")
|
||||||
STORE = DATA_ROOT / "sessions.json"
|
STORE = DATA_ROOT / "sessions.json"
|
||||||
|
PROBE_TIMEOUT_SECONDS = 8
|
||||||
|
_write_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
|
||||||
def _read() -> list[dict]:
|
def _read() -> list[dict]:
|
||||||
@@ -34,7 +39,7 @@ def _write(accounts: list[dict]) -> None:
|
|||||||
temporary.replace(STORE)
|
temporary.replace(STORE)
|
||||||
|
|
||||||
|
|
||||||
def remember(user: dict, cookies: list[dict]) -> None:
|
def _upsert(user: dict, cookies: list[dict]) -> None:
|
||||||
login_id = str(user.get("loginId") or "").strip()
|
login_id = str(user.get("loginId") or "").strip()
|
||||||
if not login_id or not cookies:
|
if not login_id or not cookies:
|
||||||
return
|
return
|
||||||
@@ -53,10 +58,25 @@ def remember(user: dict, cookies: list[dict]) -> None:
|
|||||||
_write(accounts)
|
_write(accounts)
|
||||||
|
|
||||||
|
|
||||||
|
def remember(user: dict, cookies: list[dict]) -> None:
|
||||||
|
"""同步写入。并发路径使用 remember_account,写前会重新读取。"""
|
||||||
|
_upsert(user, cookies)
|
||||||
|
|
||||||
|
|
||||||
|
async def remember_account(user: dict, cookies: list[dict]) -> None:
|
||||||
|
async with _write_lock:
|
||||||
|
_upsert(user, cookies)
|
||||||
|
|
||||||
|
|
||||||
def forget(login_id: str) -> None:
|
def forget(login_id: str) -> None:
|
||||||
_write([item for item in _read() if item.get("loginId") != login_id])
|
_write([item for item in _read() if item.get("loginId") != login_id])
|
||||||
|
|
||||||
|
|
||||||
|
async def forget_account(login_id: str) -> None:
|
||||||
|
async with _write_lock:
|
||||||
|
forget(login_id)
|
||||||
|
|
||||||
|
|
||||||
def public_view(item: dict) -> dict:
|
def public_view(item: dict) -> dict:
|
||||||
return {
|
return {
|
||||||
"loginId": item.get("loginId") or "",
|
"loginId": item.get("loginId") or "",
|
||||||
@@ -66,34 +86,74 @@ def public_view(item: dict) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def _probe(item: dict) -> tuple[str, dict | None]:
|
||||||
|
"""返回 drop、keep 或 ok。只有确认登录失效才 drop。"""
|
||||||
|
client = NqiClient()
|
||||||
|
try:
|
||||||
|
client.import_cookies(item.get("cookies") or [])
|
||||||
|
user = await asyncio.wait_for(client.current_user(), PROBE_TIMEOUT_SECONDS)
|
||||||
|
except NqiAuthError:
|
||||||
|
return "drop", None
|
||||||
|
except (NqiError, httpx.TimeoutException, httpx.RequestError, TimeoutError) as exc:
|
||||||
|
logger.info("暂时无法确认已保存账号: %s", exc)
|
||||||
|
return "keep", None
|
||||||
|
except Exception as exc:
|
||||||
|
logger.info("暂时无法确认已保存账号: %s", exc)
|
||||||
|
return "keep", None
|
||||||
|
else:
|
||||||
|
cookies = client.export_cookies() or list(item.get("cookies") or [])
|
||||||
|
login_id = str(user.get("loginId") or item.get("loginId") or "").strip()
|
||||||
|
if not login_id or not cookies:
|
||||||
|
return "keep", None
|
||||||
|
return "ok", {
|
||||||
|
"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,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
await client.aclose()
|
||||||
|
|
||||||
|
|
||||||
|
async def _merge(changes: list[tuple[str, str, dict | None]]) -> None:
|
||||||
|
"""重新读文件再合并,避免覆盖这段时间里别的写入。"""
|
||||||
|
async with _write_lock:
|
||||||
|
current = _read()
|
||||||
|
by_id: dict[str, dict] = {}
|
||||||
|
order: list[str] = []
|
||||||
|
for item in current:
|
||||||
|
login_id = str(item.get("loginId") or "")
|
||||||
|
if not login_id or login_id in by_id:
|
||||||
|
continue
|
||||||
|
by_id[login_id] = item
|
||||||
|
order.append(login_id)
|
||||||
|
for login_id, status, record in changes:
|
||||||
|
if status == "drop":
|
||||||
|
by_id.pop(login_id, None)
|
||||||
|
if login_id in order:
|
||||||
|
order.remove(login_id)
|
||||||
|
continue
|
||||||
|
if status == "ok" and record is not None:
|
||||||
|
by_id[login_id] = record
|
||||||
|
if login_id not in order:
|
||||||
|
order.insert(0, login_id)
|
||||||
|
_write([by_id[key] for key in order if key in by_id])
|
||||||
|
|
||||||
|
|
||||||
async def available_accounts() -> list[dict]:
|
async def available_accounts() -> list[dict]:
|
||||||
"""向平台确认每条凭证。失效的删掉,暂时连不上的先留着但不显示。"""
|
"""并发向平台确认每条凭证。失效的删掉,暂时连不上的留着但不显示。"""
|
||||||
kept: list[dict] = []
|
items = _read()
|
||||||
|
probed = await asyncio.gather(*(_probe(item) for item in items))
|
||||||
|
changes: list[tuple[str, str, dict | None]] = []
|
||||||
visible: list[dict] = []
|
visible: list[dict] = []
|
||||||
for item in _read():
|
for item, (status, record) in zip(items, probed):
|
||||||
client = NqiClient()
|
login_id = str(item.get("loginId") or "")
|
||||||
try:
|
changes.append((login_id, status, record))
|
||||||
client.import_cookies(item.get("cookies") or [])
|
if status == "ok" and record is not None:
|
||||||
user = await client.current_user()
|
visible.append(public_view(record))
|
||||||
except NqiAuthError:
|
await _merge(changes)
|
||||||
continue
|
|
||||||
except (NqiError, httpx.TimeoutException, httpx.RequestError, TimeoutError):
|
|
||||||
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
|
return visible
|
||||||
|
|
||||||
|
|
||||||
@@ -107,7 +167,7 @@ async def resume(login_id: str) -> tuple[NqiClient, dict]:
|
|||||||
user = await client.current_user()
|
user = await client.current_user()
|
||||||
except NqiAuthError:
|
except NqiAuthError:
|
||||||
await client.aclose()
|
await client.aclose()
|
||||||
forget(login_id)
|
await forget_account(login_id)
|
||||||
raise NqiError("这个账号的登录已失效") from None
|
raise NqiError("这个账号的登录已失效") from None
|
||||||
except NqiError:
|
except NqiError:
|
||||||
await client.aclose()
|
await client.aclose()
|
||||||
@@ -115,5 +175,5 @@ async def resume(login_id: str) -> tuple[NqiClient, dict]:
|
|||||||
except (httpx.TimeoutException, httpx.RequestError, TimeoutError):
|
except (httpx.TimeoutException, httpx.RequestError, TimeoutError):
|
||||||
await client.aclose()
|
await client.aclose()
|
||||||
raise NqiError("连接失败,请稍后重试") from None
|
raise NqiError("连接失败,请稍后重试") from None
|
||||||
remember(user, client.export_cookies())
|
await remember_account(user, client.export_cookies())
|
||||||
return client, user
|
return client, user
|
||||||
|
|||||||
Reference in New Issue
Block a user