feat: 实现已确认的登录、采集和任务导出
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
sqlalchemy.url = sqlite:///./data/decom.db
|
||||
|
||||
[loggers]
|
||||
keys = root
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
@@ -0,0 +1,37 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from app.config import database_url
|
||||
from app.models import Base
|
||||
|
||||
config = context.config
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
config.set_main_option("sqlalchemy.url", database_url())
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(url=database_url(), target_metadata=target_metadata, literal_binds=True)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
configuration = config.get_section(config.config_ini_section) or {}
|
||||
configuration["sqlalchemy.url"] = database_url()
|
||||
connectable = engine_from_config(configuration, prefix="sqlalchemy.", poolclass=pool.NullPool)
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,87 @@
|
||||
"""初始表结构。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "0001_initial"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"app_setting",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("login_mode", sa.String(16), nullable=False),
|
||||
sa.Column("credential_refresh_seconds", sa.Integer(), nullable=False),
|
||||
)
|
||||
op.create_table(
|
||||
"app_user",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("username", sa.String(64), nullable=False),
|
||||
sa.Column("password_hash", sa.String(200), nullable=False),
|
||||
sa.Column("role", sa.String(16), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
)
|
||||
op.create_index("ix_app_user_username", "app_user", ["username"], unique=True)
|
||||
op.create_table(
|
||||
"nqi_account",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("login_id", sa.String(64), nullable=False),
|
||||
sa.Column("user_name", sa.String(128), nullable=False),
|
||||
sa.Column("city_name", sa.String(64), nullable=False),
|
||||
sa.Column("org_name", sa.String(128), nullable=False),
|
||||
sa.Column("cookies", sa.JSON(), nullable=False),
|
||||
sa.Column("role", sa.String(16), nullable=False),
|
||||
sa.Column("session_open", sa.Boolean(), nullable=False),
|
||||
sa.Column("credential_valid", sa.Boolean(), nullable=False),
|
||||
sa.Column("saved_at", sa.DateTime(timezone=True), nullable=False),
|
||||
)
|
||||
op.create_index("ix_nqi_account_login_id", "nqi_account", ["login_id"], unique=True)
|
||||
op.create_table(
|
||||
"CellData",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("cell_key", sa.String(128), nullable=False),
|
||||
sa.Column("observed_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("source", sa.String(16), nullable=False),
|
||||
sa.Column("metrics", sa.JSON(), nullable=False),
|
||||
sa.UniqueConstraint("cell_key", "observed_at", "source", name="uq_cell_time_source"),
|
||||
)
|
||||
op.create_index("ix_celldata_cell_key", "CellData", ["cell_key"])
|
||||
op.create_index("ix_celldata_observed_at", "CellData", ["observed_at"])
|
||||
op.create_table(
|
||||
"collection_source",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("name", sa.String(128), nullable=False),
|
||||
sa.Column("kind", sa.String(16), nullable=False),
|
||||
sa.Column("period_days", sa.Integer(), nullable=False),
|
||||
sa.Column("config", sa.JSON(), nullable=False),
|
||||
sa.Column("enabled", sa.Boolean(), nullable=False),
|
||||
sa.Column("next_run_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("last_error", sa.Text(), nullable=False),
|
||||
)
|
||||
op.create_table(
|
||||
"export_task",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("owner_kind", sa.String(16), nullable=False),
|
||||
sa.Column("owner_id", sa.String(64), nullable=False),
|
||||
sa.Column("status", sa.String(16), nullable=False),
|
||||
sa.Column("file_format", sa.String(8), nullable=False),
|
||||
sa.Column("params", sa.JSON(), nullable=False),
|
||||
sa.Column("result_name", sa.String(255), nullable=False),
|
||||
sa.Column("error", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
|
||||
)
|
||||
op.create_index("ix_export_task_owner_id", "export_task", ["owner_id"])
|
||||
op.create_index("ix_export_task_status", "export_task", ["status"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("export_task")
|
||||
op.drop_table("collection_source")
|
||||
op.drop_table("CellData")
|
||||
op.drop_table("nqi_account")
|
||||
op.drop_table("app_user")
|
||||
op.drop_table("app_setting")
|
||||
@@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
from app.security import read_token
|
||||
|
||||
|
||||
@dataclass
|
||||
class Actor:
|
||||
kind: str
|
||||
id: str
|
||||
role: str
|
||||
name: str
|
||||
|
||||
|
||||
def current_actor(authorization: str | None = Header(default=None)) -> Actor:
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise HTTPException(status_code=401, detail="请先登录")
|
||||
body = read_token(authorization.split(" ", 1)[1].strip())
|
||||
if body is None:
|
||||
raise HTTPException(status_code=401, detail="登录已失效")
|
||||
return Actor(str(body.get("kind") or ""), str(body.get("id") or ""), str(body.get("role") or "user"), str(body.get("name") or ""))
|
||||
|
||||
|
||||
def require_admin(actor: Actor) -> None:
|
||||
if actor.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="需要管理员")
|
||||
@@ -0,0 +1,455 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import Actor, current_actor, require_admin
|
||||
from app.config import RESULT_DIR
|
||||
from app.db import get_session, session_scope
|
||||
from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow
|
||||
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_period, check_refresh, enqueue_export
|
||||
|
||||
router = APIRouter(prefix="/api")
|
||||
|
||||
|
||||
def _bad(message: str, status: int = 400) -> HTTPException:
|
||||
return HTTPException(status_code=status, detail=message)
|
||||
|
||||
|
||||
def _setting(session: Session) -> AppSetting:
|
||||
setting = session.get(AppSetting, 1)
|
||||
if setting is None:
|
||||
setting = AppSetting(id=1, login_mode="local", credential_refresh_seconds=300)
|
||||
session.add(setting)
|
||||
session.flush()
|
||||
return setting
|
||||
|
||||
|
||||
def _token_for(kind: str, owner_id: str, role: str, name: str) -> dict:
|
||||
return {
|
||||
"status": "ok",
|
||||
"token": issue_token({"kind": kind, "id": owner_id, "role": role, "name": name}),
|
||||
"user": {"kind": kind, "id": owner_id, "role": role, "name": name},
|
||||
}
|
||||
|
||||
|
||||
def _captcha_body(session_id: str, challenge) -> dict:
|
||||
encoded = base64.b64encode(challenge.captcha_png).decode("ascii")
|
||||
return {
|
||||
"status": "captcha",
|
||||
"sessionId": session_id,
|
||||
"captcha": f"data:{challenge.captcha_type};base64,{encoded}",
|
||||
}
|
||||
|
||||
|
||||
def _public_source(source: CollectionSource) -> dict:
|
||||
config = dict(source.config or {})
|
||||
if "password" in config:
|
||||
config = {**config, "password": "", "passwordSet": bool(config.get("password"))}
|
||||
return {
|
||||
"id": source.id,
|
||||
"name": source.name,
|
||||
"kind": source.kind,
|
||||
"periodDays": source.period_days,
|
||||
"config": config,
|
||||
"enabled": source.enabled,
|
||||
"lastError": source.last_error,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/auth/mode")
|
||||
def auth_mode(session: Session = Depends(get_session)) -> dict:
|
||||
return {"mode": _setting(session).login_mode}
|
||||
|
||||
|
||||
@router.post("/auth/local")
|
||||
def local_login(body: dict, session: Session = Depends(get_session)) -> dict:
|
||||
if _setting(session).login_mode != "local":
|
||||
raise _bad("当前使用大数据平台账号登录")
|
||||
username = str(body.get("username") or "").strip()
|
||||
password = str(body.get("password") or "")
|
||||
user = session.scalar(select(User).where(User.username == username))
|
||||
if user is None or not verify_password(password, user.password_hash):
|
||||
raise _bad("账号或密码不正确")
|
||||
return _token_for("local", str(user.id), user.role, user.username)
|
||||
|
||||
|
||||
@router.post("/auth/nqi/start")
|
||||
async def nqi_start(body: dict) -> dict:
|
||||
await purge()
|
||||
username = str(body.get("username") or "").strip()
|
||||
purpose = "pool" if body.get("purpose") == "pool" else "login"
|
||||
if not username:
|
||||
raise _bad("请输入账号")
|
||||
with session_scope() as session:
|
||||
if _setting(session).login_mode != "nqi":
|
||||
raise _bad("当前使用自有账号登录")
|
||||
account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == username))
|
||||
resume_cookies = list(account.cookies or []) if account is not None and account.session_open and account.credential_valid else []
|
||||
resume_role = account.role if account is not None else "user"
|
||||
resume_name = (account.user_name or account.login_id) if account is not None else username
|
||||
if purpose == "login" and resume_cookies:
|
||||
resumed = await _resume(resume_cookies)
|
||||
if resumed is not None:
|
||||
user, cookies = resumed
|
||||
with session_scope() as session:
|
||||
account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == username))
|
||||
if account is not None:
|
||||
account.cookies = cookies
|
||||
account.user_name = user.get("userName") or account.user_name
|
||||
account.credential_valid = True
|
||||
account.saved_at = utcnow()
|
||||
resume_role = account.role
|
||||
resume_name = account.user_name or account.login_id
|
||||
return _token_for("nqi", username, resume_role, resume_name)
|
||||
client = NqiClient()
|
||||
try:
|
||||
challenge = await client.open_login()
|
||||
except NqiError as exc:
|
||||
await client.aclose()
|
||||
raise _bad(str(exc)) from exc
|
||||
session_id = remember(client, challenge, purpose)
|
||||
return _captcha_body(session_id, challenge)
|
||||
|
||||
|
||||
@router.post("/auth/nqi/captcha")
|
||||
async def nqi_captcha(body: dict) -> dict:
|
||||
pair = take(str(body.get("sessionId") or ""))
|
||||
if pair is None:
|
||||
raise _bad("验证码已失效,请重新打开登录")
|
||||
client, challenge, _purpose = pair
|
||||
try:
|
||||
await client.refresh_captcha(challenge)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
return _captcha_body(str(body.get("sessionId")), challenge)
|
||||
|
||||
|
||||
@router.post("/auth/nqi/sms")
|
||||
async def nqi_sms(body: dict) -> dict:
|
||||
pair = take(str(body.get("sessionId") or ""))
|
||||
if pair is None:
|
||||
raise _bad("登录已过期,请重新打开登录")
|
||||
client, challenge, _purpose = pair
|
||||
username = str(body.get("username") or "").strip()
|
||||
password = str(body.get("password") or "")
|
||||
captcha = str(body.get("captcha") or "").strip()
|
||||
if not username or not password or not captcha:
|
||||
raise _bad("请填写账号、密码和验证码")
|
||||
try:
|
||||
if not challenge.config_ready:
|
||||
await client.prepare_login(challenge, username, password, captcha)
|
||||
message = await client.send_sms(challenge)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
return {"ok": True, "message": message}
|
||||
|
||||
|
||||
@router.post("/auth/nqi/finish")
|
||||
async def nqi_finish(body: dict) -> dict:
|
||||
session_id = str(body.get("sessionId") or "")
|
||||
pair = take(session_id)
|
||||
if pair is None:
|
||||
raise _bad("验证码已失效,请重新打开登录")
|
||||
client, challenge, purpose = pair
|
||||
username = str(body.get("username") or "").strip()
|
||||
password = str(body.get("password") or "")
|
||||
captcha = str(body.get("captcha") or "").strip()
|
||||
sms_code = str(body.get("smsCode") or "").strip()
|
||||
if not username or not password or not captcha:
|
||||
raise _bad("请填写账号、密码和验证码")
|
||||
try:
|
||||
if not challenge.config_ready:
|
||||
code = await client.prepare_login(challenge, username, password, captcha)
|
||||
if code == "1" and not sms_code:
|
||||
return {"status": "sms_required"}
|
||||
user = await client.submit_login(challenge, sms_code)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
challenge.password = ""
|
||||
cookies = client.export_cookies()
|
||||
await client.aclose()
|
||||
drop(session_id)
|
||||
with session_scope() as session:
|
||||
if _setting(session).login_mode != "nqi":
|
||||
raise _bad("当前使用自有账号登录")
|
||||
account = _save_pool(session, user, cookies)
|
||||
login_id = account.login_id
|
||||
role = account.role
|
||||
name = account.user_name or account.login_id
|
||||
if purpose == "pool":
|
||||
return {"status": "ok"}
|
||||
return _token_for("nqi", login_id, role, name)
|
||||
|
||||
|
||||
@router.post("/auth/logout")
|
||||
def logout(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
if actor.kind == "nqi":
|
||||
account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == actor.id))
|
||||
if account is not None:
|
||||
account.session_open = False
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def me(actor: Actor = Depends(current_actor)) -> dict:
|
||||
return {"user": {"kind": actor.kind, "id": actor.id, "role": actor.role, "name": actor.name}}
|
||||
|
||||
|
||||
@router.get("/tasks")
|
||||
def list_tasks(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
if actor.role == "admin":
|
||||
raise _bad("管理员不在这里提交任务", 403)
|
||||
rows = session.scalars(
|
||||
select(ExportTask)
|
||||
.where(ExportTask.owner_kind == actor.kind, ExportTask.owner_id == actor.id)
|
||||
.order_by(ExportTask.id.desc())
|
||||
).all()
|
||||
return {"tasks": [_public_task(row) for row in rows]}
|
||||
|
||||
|
||||
@router.post("/tasks")
|
||||
def create_task(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
if actor.role == "admin":
|
||||
raise _bad("管理员不在这里提交任务", 403)
|
||||
file_format = str(body.get("format") or "")
|
||||
if file_format not in {"xlsx", "xls", "csv"}:
|
||||
raise _bad("结果文件只能是 xlsx、xls 或 csv")
|
||||
task = ExportTask(
|
||||
owner_kind=actor.kind,
|
||||
owner_id=actor.id,
|
||||
status="queued",
|
||||
file_format=file_format,
|
||||
params={
|
||||
"cellKey": str(body.get("cellKey") or "").strip(),
|
||||
"start": str(body.get("start") or "").strip(),
|
||||
"end": str(body.get("end") or "").strip(),
|
||||
},
|
||||
)
|
||||
session.add(task)
|
||||
session.flush()
|
||||
task_id = task.id
|
||||
session.commit()
|
||||
enqueue_export(task_id)
|
||||
return {"task": _public_task(task)}
|
||||
|
||||
|
||||
@router.get("/tasks/{task_id}/file")
|
||||
def download_task(task_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> Response:
|
||||
task = session.get(ExportTask, task_id)
|
||||
if task is None or task.owner_kind != actor.kind or task.owner_id != actor.id or task.status != "done":
|
||||
raise _bad("结果还不能下载", 404)
|
||||
path = RESULT_DIR / task.result_name
|
||||
if not path.is_file():
|
||||
raise _bad("结果还不能下载", 404)
|
||||
return Response(content=path.read_bytes(), media_type="application/octet-stream", headers={"Content-Disposition": f'attachment; filename="{task.result_name}"'})
|
||||
|
||||
|
||||
@router.get("/admin/settings")
|
||||
def admin_settings(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
setting = _setting(session)
|
||||
return {"loginMode": setting.login_mode, "credentialRefreshSeconds": setting.credential_refresh_seconds}
|
||||
|
||||
|
||||
@router.put("/admin/settings")
|
||||
def update_settings(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
setting = _setting(session)
|
||||
mode = str(body.get("loginMode") or setting.login_mode)
|
||||
if mode not in {"local", "nqi"}:
|
||||
raise _bad("登录方式不正确")
|
||||
if mode == "local" and session.scalar(select(User).where(User.role == "admin")) is None:
|
||||
raise _bad("还没有自有账号管理员,不能切换")
|
||||
if "credentialRefreshSeconds" in body:
|
||||
try:
|
||||
setting.credential_refresh_seconds = check_refresh(int(body.get("credentialRefreshSeconds")))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
setting.login_mode = mode
|
||||
return {"loginMode": setting.login_mode, "credentialRefreshSeconds": setting.credential_refresh_seconds}
|
||||
|
||||
|
||||
@router.get("/admin/users")
|
||||
def list_users(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
rows = session.scalars(select(User).order_by(User.id)).all()
|
||||
return {"users": [{"id": row.id, "username": row.username, "role": row.role} for row in rows]}
|
||||
|
||||
|
||||
@router.post("/admin/users")
|
||||
def create_user(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
username = str(body.get("username") or "").strip()
|
||||
password = str(body.get("password") or "")
|
||||
role = "admin" if body.get("role") == "admin" else "user"
|
||||
if not username or not password:
|
||||
raise _bad("请填写账号和密码")
|
||||
if session.scalar(select(User).where(User.username == username)) is not None:
|
||||
raise _bad("账号已存在")
|
||||
session.add(User(username=username, password_hash=hash_password(password), role=role))
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.delete("/admin/users/{user_id}")
|
||||
def delete_user(user_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
user = session.get(User, user_id)
|
||||
if user is None:
|
||||
raise _bad("账号不存在", 404)
|
||||
if user.role == "admin" and actor.kind == "local" and actor.id == str(user.id):
|
||||
raise _bad("不能删除当前管理员")
|
||||
session.delete(user)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/admin/pool")
|
||||
def list_pool(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
rows = session.scalars(select(NqiAccount).order_by(NqiAccount.id.desc())).all()
|
||||
return {
|
||||
"accounts": [
|
||||
{
|
||||
"id": row.id,
|
||||
"loginId": row.login_id,
|
||||
"userName": row.user_name,
|
||||
"cityName": row.city_name,
|
||||
"role": row.role,
|
||||
"sessionOpen": row.session_open,
|
||||
"credentialValid": row.credential_valid,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/admin/pool/{account_id}")
|
||||
def delete_pool(account_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
account = session.get(NqiAccount, account_id)
|
||||
if account is None:
|
||||
raise _bad("账号不存在", 404)
|
||||
session.delete(account)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.put("/admin/pool/{account_id}/role")
|
||||
def pool_role(account_id: int, body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
account = session.get(NqiAccount, account_id)
|
||||
if account is None:
|
||||
raise _bad("账号不存在", 404)
|
||||
account.role = "admin" if body.get("role") == "admin" else "user"
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/admin/sources")
|
||||
def list_sources(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
rows = session.scalars(select(CollectionSource).order_by(CollectionSource.id)).all()
|
||||
return {"sources": [_public_source(row) for row in rows]}
|
||||
|
||||
|
||||
@router.post("/admin/sources")
|
||||
def create_source(body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
source = CollectionSource(name="采集", kind="ftp", period_days=1, config={}, enabled=True, next_run_at=utcnow())
|
||||
_apply_source(source, body)
|
||||
session.add(source)
|
||||
session.flush()
|
||||
return {"source": _public_source(source)}
|
||||
|
||||
|
||||
@router.put("/admin/sources/{source_id}")
|
||||
def update_source(source_id: int, body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is None:
|
||||
raise _bad("采集不存在", 404)
|
||||
_apply_source(source, body)
|
||||
return {"source": _public_source(source)}
|
||||
|
||||
|
||||
@router.delete("/admin/sources/{source_id}")
|
||||
def delete_source(source_id: int, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is None:
|
||||
raise _bad("采集不存在", 404)
|
||||
session.delete(source)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def _apply_source(source: CollectionSource, body: dict) -> None:
|
||||
if "name" in body:
|
||||
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("采集来源不正确")
|
||||
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):
|
||||
incoming = dict(body["config"])
|
||||
current = dict(source.config or {})
|
||||
if not incoming.get("password"):
|
||||
incoming["password"] = current.get("password") or ""
|
||||
source.config = incoming
|
||||
|
||||
|
||||
def _public_task(task: ExportTask) -> dict:
|
||||
return {
|
||||
"id": task.id,
|
||||
"status": task.status,
|
||||
"format": task.file_format,
|
||||
"cellKey": (task.params or {}).get("cellKey") or "",
|
||||
"error": task.error,
|
||||
"createdAt": task.created_at.isoformat() if task.created_at else "",
|
||||
}
|
||||
|
||||
|
||||
def _save_pool(session: Session, user: dict, cookies: list) -> NqiAccount:
|
||||
login_id = str(user.get("loginId") or "").strip()
|
||||
if not login_id:
|
||||
raise _bad("平台没有返回账号")
|
||||
account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == login_id))
|
||||
has_admin = session.scalar(select(NqiAccount.id).where(NqiAccount.role == "admin")) is not None
|
||||
if account is None:
|
||||
account = NqiAccount(login_id=login_id, role="user" if has_admin else "admin")
|
||||
session.add(account)
|
||||
account.user_name = user.get("userName") or ""
|
||||
account.city_name = user.get("cityName") or ""
|
||||
account.org_name = user.get("orgName") or ""
|
||||
account.cookies = cookies
|
||||
account.session_open = True
|
||||
account.credential_valid = True
|
||||
account.saved_at = utcnow()
|
||||
session.flush()
|
||||
return account
|
||||
|
||||
|
||||
async def _resume(cookies: list):
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(cookies)
|
||||
user = await client.current_user()
|
||||
return user, client.export_cookies()
|
||||
except NqiAuthError:
|
||||
return None
|
||||
except NqiError:
|
||||
return None
|
||||
finally:
|
||||
await client.aclose()
|
||||
@@ -0,0 +1,37 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.config import BACKEND_ROOT, admin_password, admin_username
|
||||
from app.db import session_scope
|
||||
from app.models import AppSetting, User
|
||||
from app.security import hash_password
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
from app.config import DATA_DIR
|
||||
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
config = Config(str(Path(BACKEND_ROOT) / "alembic.ini"))
|
||||
config.set_main_option("script_location", str(Path(BACKEND_ROOT) / "alembic"))
|
||||
command.upgrade(config, "head")
|
||||
with session_scope() as session:
|
||||
if session.get(AppSetting, 1) is None:
|
||||
session.add(AppSetting(id=1, login_mode="local", credential_refresh_seconds=300))
|
||||
if admin_username() and admin_password() and session.scalar(select(User).where(User.role == "admin")) is None:
|
||||
session.add(
|
||||
User(
|
||||
username=admin_username(),
|
||||
password_hash=hash_password(admin_password()),
|
||||
role="admin",
|
||||
)
|
||||
)
|
||||
logger.info("已创建管理员 %s", admin_username())
|
||||
@@ -0,0 +1,148 @@
|
||||
"""把表格读成小区多期记录,并按选择的格式写出。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
import xlwt
|
||||
|
||||
CELL_HEADERS = ("小区", "cell_key", "cell")
|
||||
TIME_HEADERS = ("时间", "observed_at", "time")
|
||||
|
||||
|
||||
def decode_text(content: bytes) -> str:
|
||||
for encoding in ("utf-8-sig", "gbk"):
|
||||
try:
|
||||
return content.decode(encoding)
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return content.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def _parse_time(value: str) -> datetime:
|
||||
text = value.strip()
|
||||
if not text:
|
||||
raise ValueError("缺少时间")
|
||||
normalized = text.replace("/", "-").replace("T", " ")
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
||||
try:
|
||||
parsed = datetime.strptime(normalized, fmt)
|
||||
return parsed.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValueError("时间格式无法识别")
|
||||
|
||||
|
||||
def rows_from_table(headers: list[str], records: list[list[str]]) -> list[dict]:
|
||||
cell_index = next((index for index, name in enumerate(headers) if name.strip() in CELL_HEADERS), None)
|
||||
time_index = next((index for index, name in enumerate(headers) if name.strip() in TIME_HEADERS), None)
|
||||
if cell_index is None or time_index is None:
|
||||
raise ValueError("表格需要包含小区和时间")
|
||||
parsed: list[dict] = []
|
||||
for record in records:
|
||||
if cell_index >= len(record) or not str(record[cell_index]).strip():
|
||||
continue
|
||||
metrics = {}
|
||||
for index, name in enumerate(headers):
|
||||
if index in {cell_index, time_index} or not name.strip():
|
||||
continue
|
||||
metrics[name.strip()] = "" if index >= len(record) else str(record[index]).strip()
|
||||
parsed.append(
|
||||
{
|
||||
"cell_key": str(record[cell_index]).strip(),
|
||||
"observed_at": _parse_time(str(record[time_index]) if time_index < len(record) else ""),
|
||||
"metrics": metrics,
|
||||
}
|
||||
)
|
||||
return parsed
|
||||
|
||||
|
||||
def parse_csv(content: bytes) -> list[dict]:
|
||||
reader = csv.reader(io.StringIO(decode_text(content)))
|
||||
rows = list(reader)
|
||||
if not rows:
|
||||
return []
|
||||
return rows_from_table(rows[0], rows[1:])
|
||||
|
||||
|
||||
def parse_xlsx(content: bytes) -> list[dict]:
|
||||
book = load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
||||
sheet = book.active
|
||||
rows = [["" if cell is None else str(cell) for cell in row] for row in sheet.iter_rows(values_only=True)]
|
||||
book.close()
|
||||
if not rows:
|
||||
return []
|
||||
return rows_from_table(rows[0], rows[1:])
|
||||
|
||||
|
||||
def parse_upload(name: str, content: bytes) -> list[dict]:
|
||||
lowered = name.lower()
|
||||
if lowered.endswith(".xlsx"):
|
||||
return parse_xlsx(content)
|
||||
return parse_csv(content)
|
||||
|
||||
|
||||
def _flat_rows(rows: list[dict]) -> tuple[list[str], list[list[str]]]:
|
||||
metric_names: list[str] = []
|
||||
for row in rows:
|
||||
for key in row["metrics"]:
|
||||
if key not in metric_names:
|
||||
metric_names.append(key)
|
||||
headers = ["小区", "时间", *metric_names]
|
||||
body = []
|
||||
for row in rows:
|
||||
moment = row["observed_at"]
|
||||
if isinstance(moment, datetime):
|
||||
text = moment.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
||||
else:
|
||||
text = str(moment)
|
||||
body.append([row["cell_key"], text, *[str(row["metrics"].get(name, "")) for name in metric_names]])
|
||||
return headers, body
|
||||
|
||||
|
||||
def write_csv(rows: list[dict]) -> bytes:
|
||||
headers, body = _flat_rows(rows)
|
||||
buffer = io.StringIO()
|
||||
writer = csv.writer(buffer)
|
||||
writer.writerow(headers)
|
||||
writer.writerows(body)
|
||||
return buffer.getvalue().encode("utf-8-sig")
|
||||
|
||||
|
||||
def write_xlsx(rows: list[dict]) -> bytes:
|
||||
headers, body = _flat_rows(rows)
|
||||
book = Workbook()
|
||||
sheet = book.active
|
||||
sheet.append(headers)
|
||||
for line in body:
|
||||
sheet.append(line)
|
||||
buffer = io.BytesIO()
|
||||
book.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def write_xls(rows: list[dict]) -> bytes:
|
||||
headers, body = _flat_rows(rows)
|
||||
book = xlwt.Workbook()
|
||||
sheet = book.add_sheet("结果")
|
||||
for column, name in enumerate(headers):
|
||||
sheet.write(0, column, name)
|
||||
for row_index, line in enumerate(body, start=1):
|
||||
for column, value in enumerate(line):
|
||||
sheet.write(row_index, column, value)
|
||||
buffer = io.BytesIO()
|
||||
book.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def write_table(file_format: str, rows: list[dict]) -> tuple[str, bytes]:
|
||||
if file_format == "xlsx":
|
||||
return "result.xlsx", write_xlsx(rows)
|
||||
if file_format == "xls":
|
||||
return "result.xls", write_xls(rows)
|
||||
if file_format == "csv":
|
||||
return "result.csv", write_csv(rows)
|
||||
raise ValueError("结果文件只能是 xlsx、xls 或 csv")
|
||||
@@ -0,0 +1,51 @@
|
||||
"""从 FTP/SFTP 或已登录的大数据平台取回表格。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from ftplib import FTP
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import paramiko
|
||||
|
||||
from app.nqi.client import NqiClient
|
||||
|
||||
|
||||
def fetch_ftp(config: dict) -> tuple[str, bytes]:
|
||||
protocol = str(config.get("protocol") or "sftp")
|
||||
host = str(config.get("host") or "")
|
||||
path = str(config.get("path") or "")
|
||||
username = str(config.get("username") or "")
|
||||
password = str(config.get("password") or "")
|
||||
port = int(config.get("port") or (21 if protocol == "ftp" else 22))
|
||||
if not host or not path:
|
||||
raise ValueError("请填写主机和路径")
|
||||
if protocol == "ftp":
|
||||
ftp = FTP()
|
||||
ftp.connect(host, port, timeout=30)
|
||||
ftp.login(username, password)
|
||||
buffer = io.BytesIO()
|
||||
ftp.retrbinary(f"RETR {path}", buffer.write)
|
||||
ftp.quit()
|
||||
return path.rsplit("/", 1)[-1], buffer.getvalue()
|
||||
transport = paramiko.Transport((host, port))
|
||||
transport.connect(username=username, password=password)
|
||||
sftp = paramiko.SFTPClient.from_transport(transport)
|
||||
if sftp is None:
|
||||
transport.close()
|
||||
raise ValueError("无法连接 SFTP")
|
||||
buffer = io.BytesIO()
|
||||
sftp.getfo(path, buffer)
|
||||
sftp.close()
|
||||
transport.close()
|
||||
return path.rsplit("/", 1)[-1], buffer.getvalue()
|
||||
|
||||
|
||||
async def fetch_nqi(client: NqiClient, config: dict) -> tuple[str, bytes]:
|
||||
address = str(config.get("url") or "").strip()
|
||||
if not address:
|
||||
raise ValueError("未配置 NQI 采集地址")
|
||||
parsed = urlparse(address)
|
||||
if parsed.scheme not in {"http", "https"}:
|
||||
raise ValueError("NQI 采集地址需要是 http 或 https")
|
||||
return await client.fetch_bytes(address)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""运行配置。秘密只从环境变量或 data 目录读取,不写进代码。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA_DIR = BACKEND_ROOT / "data"
|
||||
RESULT_DIR = DATA_DIR / "results"
|
||||
|
||||
|
||||
def database_url() -> str:
|
||||
return os.environ.get("DECOM_DATABASE_URL", f"sqlite+pysqlite:///{(DATA_DIR / 'decom.db').as_posix()}")
|
||||
|
||||
|
||||
def postgres_conninfo() -> str | None:
|
||||
url = database_url()
|
||||
if url.startswith("postgresql+psycopg://"):
|
||||
return "postgresql://" + url.removeprefix("postgresql+psycopg://")
|
||||
if url.startswith("postgresql://"):
|
||||
return url
|
||||
return None
|
||||
|
||||
|
||||
def inline_worker() -> bool:
|
||||
return os.environ.get("DECOM_INLINE_WORKER", "1") == "1"
|
||||
|
||||
|
||||
def jwt_secret() -> str:
|
||||
configured = os.environ.get("DECOM_JWT_SECRET", "").strip()
|
||||
if configured:
|
||||
return configured
|
||||
path = DATA_DIR / "jwt.secret"
|
||||
if path.is_file():
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
value = secrets.token_hex(32)
|
||||
path.write_text(value, encoding="utf-8")
|
||||
return value
|
||||
|
||||
|
||||
def admin_username() -> str:
|
||||
return os.environ.get("DECOM_ADMIN_USERNAME", "").strip()
|
||||
|
||||
|
||||
def admin_password() -> str:
|
||||
return os.environ.get("DECOM_ADMIN_PASSWORD", "")
|
||||
@@ -0,0 +1,56 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from app.config import database_url
|
||||
|
||||
_engine = None
|
||||
SessionLocal = sessionmaker(expire_on_commit=False)
|
||||
|
||||
|
||||
def engine():
|
||||
global _engine
|
||||
if _engine is None:
|
||||
url = database_url()
|
||||
connect_args = {"check_same_thread": False} if url.startswith("sqlite") else {}
|
||||
_engine = create_engine(url, connect_args=connect_args)
|
||||
SessionLocal.configure(bind=_engine)
|
||||
return _engine
|
||||
|
||||
|
||||
def reset_engine() -> None:
|
||||
global _engine
|
||||
if _engine is not None:
|
||||
_engine.dispose()
|
||||
_engine = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def session_scope() -> Iterator[Session]:
|
||||
engine()
|
||||
session = SessionLocal()
|
||||
try:
|
||||
yield session
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def get_session() -> Iterator[Session]:
|
||||
engine()
|
||||
session = SessionLocal()
|
||||
try:
|
||||
yield session
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
@@ -0,0 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.api.http import router
|
||||
from app.bootstrap import init_db
|
||||
from app.runtime import start_background
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
WEB_DIST = Path(__file__).resolve().parents[2] / "web" / "dist"
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_application: FastAPI):
|
||||
init_db()
|
||||
start_background()
|
||||
yield
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
application = FastAPI(title="DecomEval", lifespan=lifespan)
|
||||
application.include_router(router)
|
||||
|
||||
if (WEB_DIST / "index.html").is_file():
|
||||
application.mount("/assets", StaticFiles(directory=WEB_DIST / "assets"), name="assets")
|
||||
|
||||
@application.get("/{path:path}")
|
||||
def pages(path: str) -> FileResponse:
|
||||
target = WEB_DIST / path
|
||||
if path and target.is_file():
|
||||
return FileResponse(target)
|
||||
return FileResponse(WEB_DIST / "index.html")
|
||||
|
||||
return application
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1,86 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import JSON, Boolean, DateTime, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
__tablename__ = "app_setting"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
login_mode: Mapped[str] = mapped_column(String(16), default="local")
|
||||
credential_refresh_seconds: Mapped[int] = mapped_column(Integer, default=300)
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "app_user"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(200))
|
||||
role: Mapped[str] = mapped_column(String(16), default="user")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
|
||||
|
||||
class NqiAccount(Base):
|
||||
__tablename__ = "nqi_account"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
login_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_name: Mapped[str] = mapped_column(String(128), default="")
|
||||
city_name: Mapped[str] = mapped_column(String(64), default="")
|
||||
org_name: Mapped[str] = mapped_column(String(128), default="")
|
||||
cookies: Mapped[list] = mapped_column(JSON, default=list)
|
||||
role: Mapped[str] = mapped_column(String(16), default="user")
|
||||
session_open: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
credential_valid: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
saved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
|
||||
|
||||
class CellData(Base):
|
||||
__tablename__ = "CellData"
|
||||
__table_args__ = (UniqueConstraint("cell_key", "observed_at", "source", name="uq_cell_time_source"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
cell_key: Mapped[str] = mapped_column(String(128), index=True)
|
||||
observed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
|
||||
source: Mapped[str] = mapped_column(String(16))
|
||||
metrics: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
|
||||
|
||||
class CollectionSource(Base):
|
||||
__tablename__ = "collection_source"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128))
|
||||
kind: Mapped[str] = mapped_column(String(16))
|
||||
period_days: Mapped[int] = mapped_column(Integer, default=1)
|
||||
config: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
next_run_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
last_error: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class ExportTask(Base):
|
||||
__tablename__ = "export_task"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
owner_kind: Mapped[str] = mapped_column(String(16))
|
||||
owner_id: Mapped[str] = mapped_column(String(64), index=True)
|
||||
status: Mapped[str] = mapped_column(String(16), default="queued", index=True)
|
||||
file_format: Mapped[str] = mapped_column(String(8))
|
||||
params: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
result_name: Mapped[str] = mapped_column(String(255), default="")
|
||||
error: Mapped[str] = mapped_column(Text, default="")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
@@ -0,0 +1,460 @@
|
||||
"""门户登录。登录、短信和凭证续期与已验证的 NqiTools 相同。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
import httpx
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
|
||||
from app.nqi.constants import (
|
||||
CAS_CAPTCHA,
|
||||
CAS_CONFIG,
|
||||
CAS_LOGIN,
|
||||
CAS_PASSWORD_CHECK,
|
||||
CAS_SMS,
|
||||
CAS_USER,
|
||||
GIS_API,
|
||||
ORIGIN,
|
||||
PORTAL_ONLINE,
|
||||
PORTAL_SERVICE,
|
||||
USER_AGENT,
|
||||
)
|
||||
from app.nqi.sign import build_sign
|
||||
|
||||
_EXECUTION = re.compile(r'name="execution"\s+value="([^"]+)"', re.I)
|
||||
_PUBLIC_KEY = re.compile(r'setPublicKey\("([^"]+)"\)')
|
||||
_GENERIC_LOGIN_FAILURE = "登录未成功,请检查验证码或短信验证码"
|
||||
|
||||
|
||||
class NqiError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NqiAuthError(NqiError):
|
||||
pass
|
||||
|
||||
|
||||
class NqiNetworkError(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)
|
||||
encrypted = key.encrypt(text.encode("utf-8"), padding.PKCS1v15())
|
||||
return base64.b64encode(encrypted).decode("ascii")
|
||||
|
||||
|
||||
def login_page_url(url: str) -> str:
|
||||
if "service=" in url:
|
||||
return url
|
||||
return f"{CAS_LOGIN}?service={quote(PORTAL_SERVICE, safe='')}"
|
||||
|
||||
|
||||
def sms_notice(payload: dict) -> str:
|
||||
if payload.get("success") is False:
|
||||
raise NqiError(str(payload.get("msg") or "短信发送失败"))
|
||||
nested = payload.get("data")
|
||||
if isinstance(nested, str):
|
||||
try:
|
||||
nested = json.loads(nested)
|
||||
except json.JSONDecodeError:
|
||||
nested = None
|
||||
if isinstance(nested, dict):
|
||||
code = str(nested.get("Code") or "")
|
||||
content = str(nested.get("Content") or "")
|
||||
if code and code != "0000":
|
||||
raise NqiError(content or "短信发送失败")
|
||||
if content:
|
||||
return content
|
||||
return "短信发送已受理"
|
||||
|
||||
|
||||
def needs_captcha(message: str) -> bool:
|
||||
if not message or message == _GENERIC_LOGIN_FAILURE:
|
||||
return False
|
||||
text = message.replace("短信验证码", "")
|
||||
if "验证码" in text:
|
||||
return True
|
||||
lowered = text.lower()
|
||||
return "captcha" in lowered and "sms" not in lowered
|
||||
|
||||
|
||||
@dataclass
|
||||
class LoginChallenge:
|
||||
execution: str
|
||||
public_key: str
|
||||
captcha_png: bytes
|
||||
page_url: str
|
||||
captcha_type: str = "image/jpeg"
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
captcha: str = ""
|
||||
config_ready: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class NqiClient:
|
||||
client: httpx.AsyncClient = field(init=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._inflight = 0
|
||||
self._idle = asyncio.Event()
|
||||
self._idle.set()
|
||||
self.client = httpx.AsyncClient(
|
||||
headers={
|
||||
"User-Agent": USER_AGENT,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9",
|
||||
},
|
||||
timeout=httpx.Timeout(45.0, connect=15.0),
|
||||
follow_redirects=True,
|
||||
trust_env=False,
|
||||
)
|
||||
raw_send = self.client.send
|
||||
|
||||
async def send(request, *args, **kwargs):
|
||||
self._inflight += 1
|
||||
self._idle.clear()
|
||||
try:
|
||||
return await raw_send(request, *args, **kwargs)
|
||||
finally:
|
||||
self._inflight = max(0, self._inflight - 1)
|
||||
if self._inflight == 0:
|
||||
self._idle.set()
|
||||
|
||||
self.client.send = send
|
||||
|
||||
async def aclose(self) -> None:
|
||||
await self.client.aclose()
|
||||
|
||||
async def wait_idle(self, timeout: float = 5.0) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
if self._inflight == 0:
|
||||
await asyncio.sleep(0)
|
||||
if self._inflight == 0:
|
||||
return
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return
|
||||
try:
|
||||
await asyncio.wait_for(self._idle.wait(), min(0.2, remaining))
|
||||
except TimeoutError:
|
||||
continue
|
||||
|
||||
def export_cookies(self) -> list[dict[str, str]]:
|
||||
exported: list[dict[str, str]] = []
|
||||
for cookie in self.client.cookies.jar:
|
||||
exported.append(
|
||||
{
|
||||
"name": cookie.name,
|
||||
"value": cookie.value,
|
||||
"domain": cookie.domain or "",
|
||||
"path": cookie.path or "/",
|
||||
}
|
||||
)
|
||||
return exported
|
||||
|
||||
def import_cookies(self, cookies: list[dict]) -> None:
|
||||
for cookie in cookies:
|
||||
if not cookie.get("name"):
|
||||
continue
|
||||
self.client.cookies.set(
|
||||
cookie["name"],
|
||||
cookie.get("value", ""),
|
||||
domain=cookie.get("domain") or "",
|
||||
path=cookie.get("path") or "/",
|
||||
)
|
||||
|
||||
def ticket(self) -> str:
|
||||
for name in ("CASTGC", "TGC"):
|
||||
value = self.client.cookies.get(name)
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
def _ajax_headers(self, challenge: LoginChallenge) -> dict[str, str]:
|
||||
return {
|
||||
"Accept": "*/*",
|
||||
"Referer": challenge.page_url,
|
||||
"Origin": ORIGIN,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
}
|
||||
|
||||
async def open_login(self) -> LoginChallenge:
|
||||
response = await self._request("GET", CAS_LOGIN, check_auth=False, params={"service": PORTAL_SERVICE})
|
||||
html = response.text
|
||||
execution = _EXECUTION.search(html)
|
||||
public_key = _PUBLIC_KEY.search(html)
|
||||
if not execution or not public_key:
|
||||
raise NqiError("登录页没有返回加密参数,请稍后重试")
|
||||
page_url = login_page_url(str(response.url))
|
||||
captcha = await self._request("GET", CAS_CAPTCHA, check_auth=False, headers={"Referer": page_url})
|
||||
if captcha.status_code != 200 or not captcha.content:
|
||||
raise NqiError("验证码获取失败")
|
||||
return LoginChallenge(
|
||||
execution=execution.group(1),
|
||||
public_key=public_key.group(1),
|
||||
captcha_png=captcha.content,
|
||||
page_url=page_url,
|
||||
captcha_type=_media_type(captcha),
|
||||
)
|
||||
|
||||
async def refresh_captcha(self, challenge: LoginChallenge) -> bytes:
|
||||
response = await self._request(
|
||||
"GET",
|
||||
CAS_CAPTCHA,
|
||||
check_auth=False,
|
||||
params={"id": "refresh"},
|
||||
headers={"Referer": challenge.page_url},
|
||||
)
|
||||
if response.status_code != 200 or not response.content:
|
||||
raise NqiError("验证码刷新失败")
|
||||
challenge.captcha_png = response.content
|
||||
challenge.captcha_type = _media_type(response)
|
||||
return response.content
|
||||
|
||||
async def prepare_login(self, challenge: LoginChallenge, username: str, password: str, captcha: str) -> str:
|
||||
challenge.username = username
|
||||
challenge.password = password
|
||||
challenge.captcha = captcha.strip()
|
||||
payload = {
|
||||
"loginId": rsa_encrypt(challenge.public_key, username),
|
||||
"password": rsa_encrypt(challenge.public_key, password),
|
||||
"captcha": challenge.captcha,
|
||||
}
|
||||
response = await self._request(
|
||||
"POST",
|
||||
CAS_CONFIG,
|
||||
check_auth=False,
|
||||
json=payload,
|
||||
headers=self._ajax_headers(challenge),
|
||||
)
|
||||
data = _json_or_error(response, "登录校验失败")
|
||||
code = str(data.get("code", ""))
|
||||
if code not in {"0", "1"}:
|
||||
message = data.get("message") or data.get("msg") or "账号、密码或验证码不正确"
|
||||
raise NqiError(str(message))
|
||||
challenge.config_ready = True
|
||||
return code
|
||||
|
||||
async def send_sms(self, challenge: LoginChallenge) -> str:
|
||||
if not challenge.username or not challenge.password:
|
||||
raise NqiError("请先填写账号和密码")
|
||||
payload = {
|
||||
"loginId": rsa_encrypt(challenge.public_key, challenge.username),
|
||||
"password": rsa_encrypt(challenge.public_key, challenge.password),
|
||||
}
|
||||
response = await self._request(
|
||||
"POST",
|
||||
CAS_SMS,
|
||||
check_auth=False,
|
||||
json=payload,
|
||||
headers=self._ajax_headers(challenge),
|
||||
timeout=httpx.Timeout(120.0, connect=15.0),
|
||||
)
|
||||
data = _json_or_error(response, "短信发送失败")
|
||||
return sms_notice(data)
|
||||
|
||||
async def submit_login(self, challenge: LoginChallenge, sms_code: str = "") -> dict:
|
||||
if not challenge.config_ready:
|
||||
raise NqiError("请先完成验证码校验")
|
||||
form = [
|
||||
("password", rsa_encrypt(challenge.public_key, challenge.password)),
|
||||
("username", rsa_encrypt(challenge.public_key, challenge.username)),
|
||||
("msgCode", sms_code.strip()),
|
||||
("captcha", challenge.captcha),
|
||||
("uuid", ""),
|
||||
("execution", challenge.execution),
|
||||
("_eventId", "submit"),
|
||||
("geolocation", ""),
|
||||
]
|
||||
response = await self._request(
|
||||
"POST",
|
||||
challenge.page_url,
|
||||
check_auth=False,
|
||||
content=urlencode(form).encode("utf-8"),
|
||||
headers={
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Referer": challenge.page_url,
|
||||
"Origin": ORIGIN,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
},
|
||||
)
|
||||
if not self.ticket():
|
||||
message = _login_failure_message(response)
|
||||
found = _EXECUTION.search(response.text or "")
|
||||
if found:
|
||||
challenge.execution = found.group(1)
|
||||
if needs_captcha(message):
|
||||
challenge.config_ready = False
|
||||
raise NqiError(message)
|
||||
return await self.current_user()
|
||||
|
||||
async def _cas_user_payload(self) -> dict:
|
||||
ticket = self.ticket()
|
||||
headers = {"Referer": f"{ORIGIN}/pro-portal/"}
|
||||
if ticket:
|
||||
headers["tgc"] = ticket
|
||||
response = await self._request("GET", CAS_USER, headers=headers)
|
||||
data = _json_or_error(response, "读取登录用户失败")
|
||||
if not data.get("loginId") and not data.get("userName"):
|
||||
raise NqiAuthError("登录已失效,请重新登录")
|
||||
return data
|
||||
|
||||
async def current_user(self) -> dict:
|
||||
return _public_user(await self._cas_user_payload())
|
||||
|
||||
async def touch_session(self) -> dict:
|
||||
data = await self._cas_user_payload()
|
||||
await self._touch_password()
|
||||
await self._touch_online()
|
||||
role_id = str(data.get("roleId") or "")
|
||||
if role_id:
|
||||
try:
|
||||
await self._signed_get(f"{GIS_API}/base/v2/roleCityMapping/cities", {"roleCodes": role_id})
|
||||
except NqiError:
|
||||
pass
|
||||
return _public_user(data)
|
||||
|
||||
async def _touch_password(self) -> None:
|
||||
headers = {
|
||||
"Referer": f"{ORIGIN}/pro-portal/",
|
||||
"Origin": ORIGIN,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
ticket = self.ticket()
|
||||
if ticket:
|
||||
headers["tgc"] = ticket
|
||||
await self._request(
|
||||
"POST",
|
||||
CAS_PASSWORD_CHECK,
|
||||
json={},
|
||||
headers=headers,
|
||||
timeout=httpx.Timeout(20.0, connect=10.0),
|
||||
)
|
||||
|
||||
async def _touch_online(self) -> None:
|
||||
try:
|
||||
await self._request(
|
||||
"GET",
|
||||
PORTAL_ONLINE,
|
||||
headers={"Referer": f"{ORIGIN}/pro-portal/"},
|
||||
timeout=httpx.Timeout(20.0, connect=10.0),
|
||||
follow_redirects=False,
|
||||
)
|
||||
except NqiAuthError:
|
||||
raise
|
||||
except NqiError:
|
||||
return
|
||||
|
||||
async def fetch_bytes(self, url: str) -> tuple[str, bytes]:
|
||||
response = await self._request("GET", url, headers={"Referer": f"{ORIGIN}/pro-portal/"})
|
||||
if response.status_code >= 400:
|
||||
raise NqiError("采集地址没有返回数据")
|
||||
name = url.rsplit("/", 1)[-1] or "nqi.csv"
|
||||
return name, response.content
|
||||
|
||||
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._request("GET", url, params=params, headers=headers)
|
||||
return _api_payload(response)
|
||||
|
||||
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 NqiNetworkError("平台响应超时,请稍后重试") from exc
|
||||
except httpx.RequestError as exc:
|
||||
raise NqiNetworkError("连接失败,请稍后重试") 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
|
||||
|
||||
|
||||
def _public_user(data: dict) -> dict:
|
||||
return {
|
||||
"loginId": data.get("loginId") or "",
|
||||
"userName": data.get("userName") or "",
|
||||
"cityName": data.get("cityName") or "",
|
||||
"orgName": data.get("orgName") or "",
|
||||
}
|
||||
|
||||
|
||||
def _login_failure_message(response: httpx.Response) -> str:
|
||||
content_type = response.headers.get("content-type", "")
|
||||
if "json" in content_type:
|
||||
try:
|
||||
data = response.json()
|
||||
except json.JSONDecodeError:
|
||||
data = None
|
||||
if isinstance(data, dict):
|
||||
message = data.get("message") or data.get("msg")
|
||||
if message:
|
||||
return str(message)
|
||||
for pattern in (
|
||||
r'id="errMsg"[^>]*>(.*?)</',
|
||||
r'class="[^"]*errors[^"]*"[^>]*>(.*?)</',
|
||||
r'id="msg"[^>]*>(.*?)</',
|
||||
):
|
||||
match = re.search(pattern, response.text or "", re.I | re.S)
|
||||
if not match:
|
||||
continue
|
||||
detail = re.sub(r"<[^>]+>", "", match.group(1))
|
||||
detail = re.sub(r"\s+", " ", detail).strip()
|
||||
if detail:
|
||||
return detail
|
||||
return _GENERIC_LOGIN_FAILURE
|
||||
|
||||
|
||||
def _media_type(response: httpx.Response) -> str:
|
||||
raw = response.headers.get("content-type", "image/jpeg").split(";", 1)[0].strip()
|
||||
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 NqiAuthError("登录已失效,请重新登录")
|
||||
if response.status_code >= 500:
|
||||
raise NqiNetworkError("平台暂时不可用,请稍后重试")
|
||||
try:
|
||||
data = response.json()
|
||||
except json.JSONDecodeError as exc:
|
||||
raise NqiError(fallback) from exc
|
||||
if not isinstance(data, dict):
|
||||
raise NqiError(fallback)
|
||||
return data
|
||||
|
||||
|
||||
def _api_payload(response: httpx.Response) -> dict:
|
||||
data = _json_or_error(response, "平台接口没有返回数据")
|
||||
code = data.get("code")
|
||||
if code not in (0, "0", None):
|
||||
raise NqiError(str(data.get("msg") or data.get("message") or "平台接口返回失败"))
|
||||
return data
|
||||
@@ -0,0 +1,23 @@
|
||||
"""平台地址与门户页面公开的签名参数。与已验证的 NqiTools 保持一致。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
ORIGIN = "https://nqi.gmcc.net:20443"
|
||||
CAS_LOGIN = f"{ORIGIN}/cas/login"
|
||||
CAS_CONFIG = f"{ORIGIN}/cas/getConfig"
|
||||
CAS_SMS = f"{ORIGIN}/cas/sendCode1"
|
||||
CAS_CAPTCHA = f"{ORIGIN}/cas/captcha.jpg"
|
||||
PORTAL_SERVICE = f"{ORIGIN}/pro-portal/"
|
||||
CAS_USER = f"{ORIGIN}/pro-portalv2/api/cas/getCasUser"
|
||||
CAS_PASSWORD_CHECK = f"{ORIGIN}/pro-portalv2/api/user/checkUserPasswordUpdated"
|
||||
PORTAL_ONLINE = f"{ORIGIN}/pro-portal/pure/LogEnter!getOnLineCount.action"
|
||||
GIS_API = f"{ORIGIN}/pro-gis-tenant/gmcc-wyzc/api"
|
||||
|
||||
APP_KEY = "1e395dc741b64ce1913cf411e6c08384"
|
||||
APP_SECRET = "2d6f5e13b9d54c99bea58f46c2a45ddb"
|
||||
SIGN_VERSION = "1.0.0"
|
||||
|
||||
USER_AGENT = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""登录过程只放在内存里,超时后丢掉密码。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from app.nqi.client import LoginChallenge, NqiClient
|
||||
|
||||
FLOW_TTL_SECONDS = 10 * 60
|
||||
flows: dict[str, tuple[NqiClient, LoginChallenge, str]] = {}
|
||||
|
||||
|
||||
async def purge(now: float | None = None) -> None:
|
||||
moment = time.monotonic() if now is None else now
|
||||
expired: list[str] = []
|
||||
for session_id, (client, challenge, _purpose) in list(flows.items()):
|
||||
created = getattr(challenge, "created_at", None)
|
||||
if created is None or moment - float(created) < FLOW_TTL_SECONDS:
|
||||
continue
|
||||
expired.append(session_id)
|
||||
for session_id in expired:
|
||||
client, challenge, _purpose = flows.pop(session_id)
|
||||
challenge.password = ""
|
||||
await client.aclose()
|
||||
|
||||
|
||||
def remember(client: NqiClient, challenge: LoginChallenge, purpose: str) -> str:
|
||||
session_id = uuid.uuid4().hex
|
||||
challenge.created_at = time.monotonic()
|
||||
flows[session_id] = (client, challenge, purpose)
|
||||
return session_id
|
||||
|
||||
|
||||
def take(session_id: str) -> tuple[NqiClient, LoginChallenge, str] | None:
|
||||
return flows.get(session_id)
|
||||
|
||||
|
||||
def drop(session_id: str) -> None:
|
||||
flows.pop(session_id, None)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""复现门户脚本里的请求签名。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from app.nqi.constants import APP_KEY, APP_SECRET, SIGN_VERSION
|
||||
|
||||
_SKIP = {"sign", "SIG", "UPPER_SIG"}
|
||||
|
||||
|
||||
def encode_uri_component(value: str) -> str:
|
||||
return quote(value, safe="-_.!~*'()")
|
||||
|
||||
|
||||
def build_sign(
|
||||
params: dict | None = None,
|
||||
*,
|
||||
encode: bool = True,
|
||||
timestamp: str | None = None,
|
||||
nonce: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
stamp = timestamp if timestamp is not None else str(int(time.time()))
|
||||
nonce_str = nonce if nonce is not None else uuid.uuid4().hex
|
||||
payload: dict[str, str] = {}
|
||||
for key, value in (params or {}).items():
|
||||
text = "" if value is None else str(value)
|
||||
payload[str(key)] = text if text == "" or not encode else encode_uri_component(text)
|
||||
payload["timestamp"] = stamp
|
||||
payload["nonceStr"] = nonce_str
|
||||
payload["version"] = SIGN_VERSION
|
||||
raw = "".join(f"{key}{payload[key]}" for key in sorted(payload) if key not in _SKIP)
|
||||
sign = hashlib.md5((raw + APP_SECRET).encode("utf-8")).hexdigest().upper()
|
||||
return {
|
||||
"sign": sign,
|
||||
"timestamp": stamp,
|
||||
"nonceStr": nonce_str,
|
||||
"version": SIGN_VERSION,
|
||||
"appKey": APP_KEY,
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"""凭证刷新和采集周期。用户任务由队列或本进程线程执行。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db import session_scope
|
||||
from app.models import AppSetting
|
||||
from app.tasks.runner import refresh_accounts, scan_sources
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
_started = False
|
||||
|
||||
|
||||
def start_background() -> None:
|
||||
global _started
|
||||
if _started:
|
||||
return
|
||||
_started = True
|
||||
threading.Thread(target=_refresh_loop, name="decom-refresh", daemon=True).start()
|
||||
threading.Thread(target=_collect_loop, name="decom-collect", daemon=True).start()
|
||||
|
||||
|
||||
def _refresh_loop() -> None:
|
||||
while True:
|
||||
seconds = 300
|
||||
try:
|
||||
with session_scope() as session:
|
||||
setting = session.get(AppSetting, 1)
|
||||
if setting is not None:
|
||||
seconds = setting.credential_refresh_seconds
|
||||
asyncio.run(refresh_accounts())
|
||||
except Exception as exc:
|
||||
logger.info("凭证刷新未完成: %s", exc)
|
||||
time.sleep(max(60, seconds))
|
||||
|
||||
|
||||
def _collect_loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
scan_sources()
|
||||
except Exception as exc:
|
||||
logger.info("采集调度未完成: %s", exc)
|
||||
time.sleep(60)
|
||||
@@ -0,0 +1,59 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from app.config import jwt_secret
|
||||
|
||||
ITERATIONS = 200_000
|
||||
TOKEN_TTL = 12 * 60 * 60
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
salt = os.urandom(16)
|
||||
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, ITERATIONS)
|
||||
return f"{salt.hex()}${digest.hex()}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
salt_hex, digest_hex = stored.split("$", 1)
|
||||
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), ITERATIONS)
|
||||
return hmac.compare_digest(digest.hex(), digest_hex)
|
||||
|
||||
|
||||
def _encode(data: dict[str, Any]) -> str:
|
||||
raw = json.dumps(data, separators=(",", ":")).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode(raw: str) -> dict[str, Any]:
|
||||
padded = raw + "=" * (-len(raw) % 4)
|
||||
return json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
|
||||
|
||||
|
||||
def issue_token(payload: dict[str, Any]) -> str:
|
||||
body = {**payload, "exp": int(time.time()) + TOKEN_TTL}
|
||||
raw = _encode(body)
|
||||
signature = hmac.new(jwt_secret().encode("utf-8"), raw.encode("ascii"), hashlib.sha256).hexdigest()
|
||||
return f"{raw}.{signature}"
|
||||
|
||||
|
||||
def read_token(token: str) -> dict[str, Any] | None:
|
||||
raw, _, signature = token.partition(".")
|
||||
if not raw or not signature:
|
||||
return None
|
||||
expected = hmac.new(jwt_secret().encode("utf-8"), raw.encode("ascii"), hashlib.sha256).hexdigest()
|
||||
if not hmac.compare_digest(expected, signature):
|
||||
return None
|
||||
try:
|
||||
body = _decode(raw)
|
||||
except (ValueError, json.JSONDecodeError):
|
||||
return None
|
||||
if int(body.get("exp") or 0) < int(time.time()):
|
||||
return None
|
||||
return body
|
||||
@@ -0,0 +1,32 @@
|
||||
"""PostgreSQL 上的 Procrastinate 队列。SQLite 或本进程模式不走这里。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import procrastinate
|
||||
|
||||
from app.config import postgres_conninfo
|
||||
from app.tasks.runner import execute_collection, execute_export
|
||||
|
||||
conninfo = postgres_conninfo() or "postgresql://invalid"
|
||||
queue = procrastinate.App(connector=procrastinate.PsycopgConnector(conninfo=conninfo))
|
||||
|
||||
|
||||
@queue.task(name="decom_export", queue="decom")
|
||||
def decom_export(task_id: int) -> None:
|
||||
execute_export(task_id)
|
||||
|
||||
|
||||
@queue.task(name="decom_collect", queue="decom")
|
||||
def decom_collect(source_id: int) -> None:
|
||||
execute_collection(source_id)
|
||||
|
||||
|
||||
def defer(name: str, **kwargs) -> None:
|
||||
job = decom_export if name == "decom_export" else decom_collect
|
||||
job.defer(**kwargs)
|
||||
|
||||
|
||||
def serve() -> None:
|
||||
with queue.open():
|
||||
queue.schema_manager.apply_schema()
|
||||
queue.run_worker(queues=["decom"], concurrency=4)
|
||||
@@ -0,0 +1,252 @@
|
||||
"""用户任务只读库里已有的数据,再写成表格。采集另走自己的队列。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.collect.io import parse_upload, write_table
|
||||
from app.collect.remote import fetch_ftp, fetch_nqi
|
||||
from app.config import RESULT_DIR, inline_worker, postgres_conninfo
|
||||
from app.db import session_scope
|
||||
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
_pool = threading.Semaphore(4)
|
||||
|
||||
|
||||
def check_period(days: int) -> int:
|
||||
if days < 1 or days > 31:
|
||||
raise ValueError("周期最短一天,最长一个月")
|
||||
return days
|
||||
|
||||
|
||||
def check_refresh(seconds: int) -> int:
|
||||
if seconds < 60 or seconds > 24 * 60 * 60:
|
||||
raise ValueError("刷新间隔需要在 1 分钟到 1 天之间")
|
||||
return seconds
|
||||
|
||||
|
||||
def upsert_rows(session, source: str, rows: list[dict]) -> int:
|
||||
count = 0
|
||||
for row in rows:
|
||||
existing = session.scalar(
|
||||
select(CellData).where(
|
||||
CellData.cell_key == row["cell_key"],
|
||||
CellData.observed_at == row["observed_at"],
|
||||
CellData.source == source,
|
||||
)
|
||||
)
|
||||
if existing is None:
|
||||
session.add(
|
||||
CellData(
|
||||
cell_key=row["cell_key"],
|
||||
observed_at=row["observed_at"],
|
||||
source=source,
|
||||
metrics=row["metrics"],
|
||||
)
|
||||
)
|
||||
count += 1
|
||||
else:
|
||||
existing.metrics = row["metrics"]
|
||||
return count
|
||||
|
||||
|
||||
def query_cells(session, params: dict) -> list[dict]:
|
||||
statement = select(CellData).order_by(CellData.observed_at, CellData.cell_key)
|
||||
cell_key = str(params.get("cellKey") or "").strip()
|
||||
if cell_key:
|
||||
statement = statement.where(CellData.cell_key == cell_key)
|
||||
start = _optional_time(params.get("start"))
|
||||
end = _optional_time(params.get("end"))
|
||||
if start is not None:
|
||||
statement = statement.where(CellData.observed_at >= start)
|
||||
if end is not None:
|
||||
statement = statement.where(CellData.observed_at <= end)
|
||||
rows = session.scalars(statement).all()
|
||||
return [
|
||||
{"cell_key": row.cell_key, "observed_at": row.observed_at, "metrics": row.metrics or {}}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def _optional_time(value) -> datetime | None:
|
||||
if not value:
|
||||
return None
|
||||
text = str(value).replace("/", "-").replace("T", " ")
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def execute_export(task_id: int) -> None:
|
||||
with _pool:
|
||||
with session_scope() as session:
|
||||
task = session.get(ExportTask, task_id)
|
||||
if task is None or task.status not in {"queued", "running"}:
|
||||
return
|
||||
task.status = "running"
|
||||
params = dict(task.params or {})
|
||||
file_format = task.file_format
|
||||
try:
|
||||
with session_scope() as session:
|
||||
rows = query_cells(session, params)
|
||||
name, content = write_table(file_format, rows)
|
||||
RESULT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
path = RESULT_DIR / f"{task_id}-{name}"
|
||||
path.write_bytes(content)
|
||||
with session_scope() as session:
|
||||
task = session.get(ExportTask, task_id)
|
||||
if task is None:
|
||||
return
|
||||
task.status = "done"
|
||||
task.result_name = path.name
|
||||
task.finished_at = utcnow()
|
||||
except Exception as exc:
|
||||
logger.info("导出失败: %s", exc)
|
||||
with session_scope() as session:
|
||||
task = session.get(ExportTask, task_id)
|
||||
if task is None:
|
||||
return
|
||||
task.status = "failed"
|
||||
task.error = str(exc) or "导出失败"
|
||||
task.finished_at = utcnow()
|
||||
|
||||
|
||||
def execute_collection(source_id: int) -> None:
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is None or not source.enabled:
|
||||
return
|
||||
kind = source.kind
|
||||
config = dict(source.config or {})
|
||||
account = None
|
||||
if kind == "nqi":
|
||||
account = session.scalar(
|
||||
select(NqiAccount).where(NqiAccount.credential_valid.is_(True)).order_by(NqiAccount.saved_at.desc())
|
||||
)
|
||||
cookies = list(account.cookies or []) if account is not None else []
|
||||
else:
|
||||
cookies = []
|
||||
try:
|
||||
if kind == "ftp":
|
||||
name, content = fetch_ftp(config)
|
||||
elif kind == "nqi":
|
||||
if not cookies:
|
||||
raise ValueError("账号池里没有可用凭证")
|
||||
name, content = _fetch_nqi_sync(cookies, config)
|
||||
else:
|
||||
raise ValueError("未知的采集来源")
|
||||
rows = parse_upload(name, content)
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is None:
|
||||
return
|
||||
upsert_rows(session, kind, rows)
|
||||
source.last_error = ""
|
||||
except Exception as exc:
|
||||
logger.info("采集失败: %s", exc)
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is not None:
|
||||
source.last_error = str(exc) or "采集失败"
|
||||
|
||||
|
||||
def _fetch_nqi_sync(cookies: list, config: dict) -> tuple[str, bytes]:
|
||||
import asyncio
|
||||
|
||||
async def run() -> tuple[str, bytes]:
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(cookies)
|
||||
try:
|
||||
await client.current_user()
|
||||
except NqiAuthError as exc:
|
||||
raise ValueError("账号池凭证已失效") from exc
|
||||
return await fetch_nqi(client, config)
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
return asyncio.run(run)
|
||||
|
||||
|
||||
def enqueue_export(task_id: int) -> None:
|
||||
if _defer("decom_export", task_id=task_id):
|
||||
return
|
||||
threading.Thread(target=execute_export, args=(task_id,), daemon=True).start()
|
||||
|
||||
|
||||
def enqueue_collection(source_id: int) -> None:
|
||||
if _defer("decom_collect", source_id=source_id):
|
||||
return
|
||||
threading.Thread(target=execute_collection, args=(source_id,), daemon=True).start()
|
||||
|
||||
|
||||
def _defer(name: str, **kwargs) -> bool:
|
||||
if inline_worker() or not postgres_conninfo():
|
||||
return False
|
||||
try:
|
||||
from app.tasks.queue import defer
|
||||
|
||||
defer(name, **kwargs)
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.info("排队未投递,改为本进程执行: %s", exc)
|
||||
return False
|
||||
|
||||
|
||||
def scan_sources() -> None:
|
||||
now = utcnow()
|
||||
due_ids: list[int] = []
|
||||
with session_scope() as session:
|
||||
sources = session.scalars(select(CollectionSource).where(CollectionSource.enabled.is_(True))).all()
|
||||
for source in sources:
|
||||
if source.next_run_at is not None and source.next_run_at > now:
|
||||
continue
|
||||
source.next_run_at = now + timedelta(days=source.period_days)
|
||||
due_ids.append(source.id)
|
||||
for source_id in due_ids:
|
||||
enqueue_collection(source_id)
|
||||
|
||||
|
||||
async def refresh_accounts() -> None:
|
||||
with session_scope() as session:
|
||||
accounts = session.scalars(select(NqiAccount)).all()
|
||||
snapshots = [(item.id, list(item.cookies or [])) for item in accounts]
|
||||
for account_id, cookies in snapshots:
|
||||
if not cookies:
|
||||
continue
|
||||
outcome = await _touch(cookies)
|
||||
with session_scope() as session:
|
||||
account = session.get(NqiAccount, account_id)
|
||||
if account is None or outcome is None:
|
||||
continue
|
||||
valid, user, refreshed = outcome
|
||||
account.credential_valid = valid
|
||||
if valid and user is not None:
|
||||
account.user_name = user.get("userName") or account.user_name
|
||||
account.city_name = user.get("cityName") or account.city_name
|
||||
account.org_name = user.get("orgName") or account.org_name
|
||||
account.cookies = refreshed
|
||||
account.saved_at = utcnow()
|
||||
|
||||
|
||||
async def _touch(cookies: list):
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(cookies)
|
||||
user = await client.touch_session()
|
||||
return True, user, client.export_cookies()
|
||||
except NqiAuthError:
|
||||
return False, None, cookies
|
||||
except (NqiError, OSError):
|
||||
return None
|
||||
finally:
|
||||
await client.aclose()
|
||||
@@ -0,0 +1,13 @@
|
||||
fastapi
|
||||
uvicorn
|
||||
sqlalchemy>=2
|
||||
alembic
|
||||
psycopg[binary]
|
||||
procrastinate
|
||||
httpx
|
||||
cryptography
|
||||
python-multipart
|
||||
openpyxl
|
||||
xlwt
|
||||
paramiko
|
||||
pytest
|
||||
@@ -0,0 +1,91 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ["DECOM_DATABASE_URL"] = "sqlite+pysqlite:///" + (Path(__file__).resolve().parents[1] / "data" / "test.db").as_posix()
|
||||
os.environ["DECOM_INLINE_WORKER"] = "1"
|
||||
os.environ["DECOM_ADMIN_USERNAME"] = "admin"
|
||||
os.environ["DECOM_ADMIN_PASSWORD"] = "admin-pass"
|
||||
os.environ["DECOM_JWT_SECRET"] = "test-secret"
|
||||
|
||||
from app.collect.io import parse_csv, write_csv # noqa: E402
|
||||
from app.db import reset_engine # noqa: E402
|
||||
from app.main import create_app # noqa: E402
|
||||
from app.nqi.client import needs_captcha, rsa_encrypt # noqa: E402
|
||||
from app.tasks.runner import check_period # noqa: E402
|
||||
|
||||
PUBLIC_KEY = (
|
||||
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+"
|
||||
"chOQA8aQ8xCR/+aHnROaN/ZU5Vmd2Zz7g6cAacR9BSm60+iSCYtvEGJKl0WqvbPGJkc8tedjNF1QqgWqkkuE6Udgw2OkEKJCxDg6PrAniR7Cc0io9G8bW4P8JDJjSbbafvMPDDFbVVUWJxxwIDAQAB"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client():
|
||||
database = Path(os.environ["DECOM_DATABASE_URL"].removeprefix("sqlite+pysqlite:///"))
|
||||
if database.exists():
|
||||
database.unlink()
|
||||
reset_engine()
|
||||
application = create_app()
|
||||
with TestClient(application) as test_client:
|
||||
yield test_client
|
||||
reset_engine()
|
||||
if database.exists():
|
||||
database.unlink()
|
||||
|
||||
|
||||
def test_period_bounds():
|
||||
assert check_period(1) == 1
|
||||
assert check_period(31) == 31
|
||||
with pytest.raises(ValueError):
|
||||
check_period(0)
|
||||
with pytest.raises(ValueError):
|
||||
check_period(32)
|
||||
|
||||
|
||||
def test_csv_roundtrip_and_gbk():
|
||||
content = "小区,时间,拆除前\nGZ-1,2026-01-02 03:04:05,-91\n".encode("gbk")
|
||||
rows = parse_csv(content)
|
||||
assert rows[0]["cell_key"] == "GZ-1"
|
||||
assert rows[0]["metrics"]["拆除前"] == "-91"
|
||||
text = write_csv(rows).decode("utf-8-sig")
|
||||
assert "GZ-1" in text
|
||||
|
||||
|
||||
def test_needs_captcha_ignores_sms():
|
||||
assert needs_captcha("图形验证码错误") is True
|
||||
assert needs_captcha("短信验证码错误") is False
|
||||
rsa_encrypt(PUBLIC_KEY, "user")
|
||||
|
||||
|
||||
def test_local_login_task_and_admin(client: TestClient):
|
||||
denied = client.post("/api/auth/local", json={"username": "admin", "password": "wrong"})
|
||||
assert denied.status_code == 400
|
||||
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
|
||||
assert logged.status_code == 200
|
||||
token = logged.json()["token"]
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
blocked = client.get("/api/tasks", headers=headers)
|
||||
assert blocked.status_code == 403
|
||||
created = client.post("/api/admin/users", json={"username": "user", "password": "user-pass", "role": "user"}, headers=headers)
|
||||
assert created.status_code == 200
|
||||
user = client.post("/api/auth/local", json={"username": "user", "password": "user-pass"})
|
||||
user_headers = {"Authorization": f"Bearer {user.json()['token']}"}
|
||||
task = client.post("/api/tasks", json={"format": "csv", "cellKey": ""}, headers=user_headers)
|
||||
assert task.status_code == 200
|
||||
assert task.json()["task"]["status"] == "queued"
|
||||
task_id = task.json()["task"]["id"]
|
||||
for _ in range(20):
|
||||
listing = client.get("/api/tasks", headers=user_headers).json()["tasks"]
|
||||
if listing[0]["status"] == "done":
|
||||
break
|
||||
time.sleep(0.1)
|
||||
assert listing[0]["status"] == "done"
|
||||
downloaded = client.get(f"/api/tasks/{task_id}/file", headers=user_headers)
|
||||
assert downloaded.status_code == 200
|
||||
assert "小区" in downloaded.content.decode("utf-8-sig")
|
||||
@@ -0,0 +1,25 @@
|
||||
"""执行排队的导出和采集。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.bootstrap import init_db
|
||||
from app.config import postgres_conninfo
|
||||
from app.runtime import start_background
|
||||
|
||||
|
||||
def main() -> None:
|
||||
init_db()
|
||||
start_background()
|
||||
if postgres_conninfo():
|
||||
from app.tasks.queue import serve
|
||||
|
||||
serve()
|
||||
return
|
||||
import time
|
||||
|
||||
while True:
|
||||
time.sleep(3600)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user