feat: 采集按分组选表和固定时刻运行,号池可检查凭证,管理页不再退出

This commit is contained in:
2026-11-09 17:55:31 +08:00
parent 152cf92df9
commit 78ad5cea6b
19 changed files with 554 additions and 247 deletions
+73 -25
View File
@@ -15,11 +15,12 @@ from app.config import env_database, hosted, installed, result_dir
from app.install import InstallError, perform_install
from app.db import get_session, session_scope
from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow
from app.nqi.adhoc import TIME_MODES, categories, tables, time_window
from app.collect.schedule import next_run_at, parse_schedule
from app.nqi.adhoc import TIME_MODES, catalog_tree, categories, tables, time_window
from app.nqi.client import NqiAuthError, NqiClient, NqiError
from app.nqi.flows import drop, purge, remember, take
from app.security import hash_password, issue_token, verify_password
from app.tasks.runner import check_concurrency, check_period, check_refresh, enqueue_export
from app.tasks.runner import check_concurrency, check_refresh, enqueue_export
router = APIRouter(prefix="/api")
# 在响应发出前提交,客户端紧接着发出的请求才能读到刚写入的内容。
@@ -443,21 +444,69 @@ def admin_dashboard(actor: Actor = Depends(current_actor), session: Session = db
def list_pool(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor)
rows = session.scalars(select(NqiAccount).order_by(NqiAccount.id.desc())).all()
return {"accounts": [_public_account(row) for row in rows]}
@router.post("/admin/pool/check")
def check_pool(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor)
rows = session.scalars(select(NqiAccount).order_by(NqiAccount.id.desc())).all()
for row in rows:
_check_account(row)
return {"accounts": [_public_account(row) for row in rows]}
@router.post("/admin/pool/{account_id}/check")
def check_pool_account(account_id: int, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor)
account = session.get(NqiAccount, account_id)
if account is None:
raise _bad("账号不存在", 404)
_check_account(account)
return {"account": _public_account(account)}
def _public_account(row: NqiAccount) -> dict:
return {
"accounts": [
{
"id": row.id,
"loginId": row.login_id,
"userName": row.user_name,
"cityName": row.city_name,
"sessionOpen": row.session_open,
"credentialValid": row.credential_valid,
}
for row in rows
]
"id": row.id,
"loginId": row.login_id,
"userName": row.user_name,
"cityName": row.city_name,
"credentialValid": row.credential_valid,
"savedAt": row.saved_at.isoformat() if row.saved_at else "",
"createdAt": row.created_at.isoformat() if row.created_at else "",
}
def _check_account(account: NqiAccount) -> None:
cookies = list(account.cookies or [])
if not cookies:
account.credential_valid = False
account.saved_at = utcnow()
return
async def run() -> tuple[bool, list]:
client = NqiClient()
try:
client.import_cookies(cookies)
await client.current_user()
await client.renew_ticket()
return True, client.export_cookies()
except NqiAuthError:
return False, cookies
finally:
await client.aclose()
try:
valid, refreshed = asyncio.run(run())
except NqiError as exc:
raise _bad(str(exc)) from exc
account.credential_valid = valid
account.saved_at = utcnow()
if valid:
account.cookies = refreshed
@router.delete("/admin/pool/{account_id}")
def delete_pool(account_id: int, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor)
@@ -469,7 +518,7 @@ def delete_pool(account_id: int, actor: Actor = Depends(current_actor), session:
@router.get("/admin/nqi/catalog")
def nqi_catalog(code: int | None = None, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
def nqi_catalog(code: int | None = None, tree: bool = False, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor)
cookies = _pool_cookies(session)
@@ -479,6 +528,8 @@ def nqi_catalog(code: int | None = None, actor: Actor = Depends(current_actor),
client.import_cookies(cookies)
await client.current_user()
try:
if tree:
return {"groups": await catalog_tree(client)}
if code is None:
return {"categories": await categories(client)}
return {"tables": await tables(client, code)}
@@ -513,7 +564,7 @@ def list_sources(actor: Actor = Depends(current_actor), session: Session = db_se
@router.post("/admin/sources")
def create_source(body: dict, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
require_admin(actor)
source = CollectionSource(name="采集", kind="ftp", period_days=1, config={}, enabled=True, next_run_at=utcnow())
source = CollectionSource(name="采集", kind="nqi", period_days=1, config={}, enabled=True)
_apply_source(source, body)
session.add(source)
session.flush()
@@ -545,14 +596,9 @@ def _apply_source(source: CollectionSource, body: dict) -> None:
source.name = str(body.get("name") or "").strip() or source.name
if "kind" in body:
kind = str(body.get("kind") or "")
if kind not in {"ftp", "nqi"}:
raise _bad("采集来源不正确")
if kind != "nqi":
raise _bad("只采集 NQI")
source.kind = kind
if "periodDays" in body:
try:
source.period_days = check_period(int(body.get("periodDays")))
except (TypeError, ValueError) as exc:
raise _bad(str(exc)) from exc
if "enabled" in body:
source.enabled = bool(body.get("enabled"))
if "config" in body and isinstance(body.get("config"), dict):
@@ -560,8 +606,9 @@ def _apply_source(source: CollectionSource, body: dict) -> None:
current = dict(source.config or {})
if not incoming.get("password"):
incoming["password"] = current.get("password") or ""
if source.kind == "nqi" and "tables" in incoming:
if source.kind == "nqi":
incoming = _nqi_tables(incoming)
source.next_run_at = next_run_at(incoming["schedule"], utcnow())
source.config = incoming
@@ -591,12 +638,13 @@ def _nqi_tables(config: dict) -> dict:
raise _bad("时间数量不正确") from exc
try:
time_window(mode, count, date.today())
schedule = parse_schedule(config.get("schedule"))
except ValueError as exc:
raise _bad(str(exc)) from exc
city = str(config.get("city") or "").strip()
if len(city) > 32:
raise _bad("城市名称过长")
return {**config, "tables": cleaned, "timeMode": mode, "timeCount": count, "city": city}
return {**config, "tables": cleaned, "timeMode": mode, "timeCount": count, "city": city, "schedule": schedule}
def _public_task(task: ExportTask) -> dict:
@@ -633,7 +681,7 @@ def _pool_dashboard(rows: list[NqiAccount]) -> dict:
added_today = 0
added_week = 0
for row in rows:
saved = _as_utc(row.saved_at)
saved = _as_utc(row.created_at)
if saved is not None:
day = saved.date()
key = day.isoformat()