493 lines
19 KiB
Python
493 lines
19 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import os
|
|
|
|
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 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.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
|
|
|
|
router = APIRouter(prefix="/api")
|
|
|
|
|
|
@router.get("/install/status")
|
|
def install_status() -> dict:
|
|
return {
|
|
"installed": installed(),
|
|
"defaults": {
|
|
"host": os.environ.get("DECOM_DB_HOST", "127.0.0.1"),
|
|
"port": int(os.environ.get("DECOM_DB_PORT", "5432")),
|
|
"database": os.environ.get("DECOM_DB_NAME", "decom"),
|
|
"username": os.environ.get("DECOM_DB_USER", "postgres"),
|
|
},
|
|
}
|
|
|
|
|
|
@router.post("/install")
|
|
def install(body: dict) -> dict:
|
|
try:
|
|
perform_install(body)
|
|
except InstallError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
return {"ok": True}
|
|
|
|
|
|
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, worker_concurrency=4)
|
|
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,
|
|
"workerConcurrency": setting.worker_concurrency,
|
|
}
|
|
|
|
|
|
@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
|
|
if "workerConcurrency" in body:
|
|
try:
|
|
setting.worker_concurrency = check_concurrency(int(body.get("workerConcurrency")))
|
|
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,
|
|
"workerConcurrency": setting.worker_concurrency,
|
|
}
|
|
|
|
|
|
@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()
|