feat: 实现已确认的登录、采集和任务导出
This commit is contained in:
@@ -3,5 +3,10 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
.venv/
|
.venv/
|
||||||
|
data/
|
||||||
|
web/node_modules/
|
||||||
|
web/dist/
|
||||||
node_modules/
|
node_modules/
|
||||||
dist/
|
dist/
|
||||||
|
.env
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和
|
|||||||
|
|
||||||
## Brand Commitments
|
## Brand Commitments
|
||||||
|
|
||||||
产品名是 DecomEval。界面风格是石墨工作台:默认深色底板、细缝、蓝色主按钮。选中导航只有一条浅色左边线,可切日间。不使用运营商标志。
|
产品名是 DecomEval。界面风格是石墨工作台:深色底板、细缝、蓝色主按钮。选中导航只有一条浅色左边线。日夜间默认跟随系统,也可以手动选择深色、浅色或跟随系统。不使用运营商标志。
|
||||||
|
|
||||||
## Evidence on Hand
|
## Evidence on Hand
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
# DecomEval
|
# DecomEval
|
||||||
|
|
||||||
占位
|
拆站评估。数据先采集入库,用户提交任务后从库中导出 xlsx、xls 或 csv。
|
||||||
|
|
||||||
|
```text
|
||||||
|
cd backend
|
||||||
|
.venv\Scripts\python -m uvicorn app.main:app --host 127.0.0.1 --port 8000
|
||||||
|
.venv\Scripts\python -m worker.main
|
||||||
|
cd ..\web
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
PostgreSQL 使用 `DECOM_DATABASE_URL=postgresql+psycopg://用户:密码@主机:5432/decom`。未设置时使用本机 SQLite。首次启动用 `DECOM_ADMIN_USERNAME` 和 `DECOM_ADMIN_PASSWORD` 创建管理员。生产环境同时运行接口和 `worker.main`,并设置 `DECOM_INLINE_WORKER=0`。
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>DecomEval</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+1377
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "decomeval-web",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vue-tsc --noEmit && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"naive-ui": "^2.43.2",
|
||||||
|
"vue": "^3.5.13",
|
||||||
|
"vue-router": "^4.5.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-vue": "^6.0.7",
|
||||||
|
"typescript": "~6.0.3",
|
||||||
|
"vite": "^8.0.16",
|
||||||
|
"vue-tsc": "^3.3.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, watch } from "vue";
|
||||||
|
import { darkTheme, dateZhCN, NConfigProvider, zhCN } from "naive-ui";
|
||||||
|
import type { GlobalThemeOverrides } from "naive-ui";
|
||||||
|
import { isDark } from "./shared/theme";
|
||||||
|
|
||||||
|
const palette = computed(() => isDark.value
|
||||||
|
? { bg: "#0D1117", panel: "#161A22", ink: "#E6EDF3", muted: "#9AA4AE", line: "#262C36", accent: "#79C0FF", sidebar: "#0D1117", danger: "#F85149" }
|
||||||
|
: { bg: "#F6F8FA", panel: "#FFFFFF", ink: "#0D1117", muted: "#57606A", line: "#D0D7DE", accent: "#0969DA", sidebar: "#FFFFFF", danger: "#CF222E" });
|
||||||
|
|
||||||
|
watch(palette, (value) => {
|
||||||
|
const root = document.documentElement;
|
||||||
|
root.style.setProperty("--bg", value.bg);
|
||||||
|
root.style.setProperty("--panel", value.panel);
|
||||||
|
root.style.setProperty("--ink", value.ink);
|
||||||
|
root.style.setProperty("--muted", value.muted);
|
||||||
|
root.style.setProperty("--line", value.line);
|
||||||
|
root.style.setProperty("--accent", value.accent);
|
||||||
|
root.style.setProperty("--sidebar", value.sidebar);
|
||||||
|
root.style.setProperty("--danger", value.danger);
|
||||||
|
root.style.setProperty("--accent-soft", isDark.value ? "rgba(121, 192, 255, 0.16)" : "rgba(9, 105, 218, 0.12)");
|
||||||
|
root.dataset.theme = isDark.value ? "dark" : "light";
|
||||||
|
}, { immediate: true });
|
||||||
|
|
||||||
|
const overrides = computed<GlobalThemeOverrides>(() => ({
|
||||||
|
common: {
|
||||||
|
primaryColor: "#1F6FEB",
|
||||||
|
primaryColorHover: "#388BFD",
|
||||||
|
primaryColorPressed: "#1158C7",
|
||||||
|
primaryColorSuppl: "#1F6FEB",
|
||||||
|
bodyColor: palette.value.bg,
|
||||||
|
cardColor: palette.value.panel,
|
||||||
|
textColor2: palette.value.ink,
|
||||||
|
borderColor: palette.value.line,
|
||||||
|
fontFamily: '"Segoe UI", "Microsoft YaHei", sans-serif',
|
||||||
|
borderRadius: "3px",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<n-config-provider :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="overrides">
|
||||||
|
<router-view />
|
||||||
|
</n-config-provider>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from "vue";
|
||||||
|
import { NButton, NDataTable, NModal, NSelect } from "naive-ui";
|
||||||
|
import Shell from "../../shell/Shell.vue";
|
||||||
|
import LoginView from "../auth/LoginView.vue";
|
||||||
|
import { api } from "../../shared/http";
|
||||||
|
|
||||||
|
interface Account { id: number; loginId: string; userName: string; cityName: string; role: string; sessionOpen: boolean; credentialValid: boolean }
|
||||||
|
const accounts = ref<Account[]>([]);
|
||||||
|
const show = ref(false);
|
||||||
|
const columns = [
|
||||||
|
{ title: "账号", key: "loginId" },
|
||||||
|
{ title: "姓名", key: "userName" },
|
||||||
|
{ title: "地市", key: "cityName" },
|
||||||
|
{ title: "凭证", key: "validLabel" },
|
||||||
|
{ title: "登录", key: "openLabel" },
|
||||||
|
];
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
const result = await api<{ accounts: Account[] }>("/api/admin/pool");
|
||||||
|
accounts.value = result.accounts.map((item) => ({
|
||||||
|
...item,
|
||||||
|
validLabel: item.credentialValid ? "有效" : "失效",
|
||||||
|
openLabel: item.sessionOpen ? "未退出" : "已退出",
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setRole(id: number, role: string) {
|
||||||
|
await api(`/api/admin/pool/${id}/role`, { method: "PUT", body: JSON.stringify({ role }) });
|
||||||
|
await load();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: number) {
|
||||||
|
await api(`/api/admin/pool/${id}`, { method: "DELETE" });
|
||||||
|
await load();
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Shell>
|
||||||
|
<header class="topbar">
|
||||||
|
<h1>账号池</h1>
|
||||||
|
<n-button type="primary" @click="show = true">添加账号</n-button>
|
||||||
|
</header>
|
||||||
|
<div class="content">
|
||||||
|
<n-data-table :columns="columns" :data="accounts" :bordered="false" />
|
||||||
|
<div v-for="account in accounts" :key="account.id" class="row-actions" style="margin-top: 8px">
|
||||||
|
<span>{{ account.loginId }}</span>
|
||||||
|
<n-select :value="account.role" size="small" style="width: 120px" :options="[{ label: '用户', value: 'user' }, { label: '管理员', value: 'admin' }]" @update:value="(value) => setRole(account.id, value)" />
|
||||||
|
<n-button size="small" @click="remove(account.id)">删除</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<n-modal v-model:show="show" preset="card" title="添加账号" style="width: 520px">
|
||||||
|
<LoginView purpose="pool" @done="show = false; load()" />
|
||||||
|
</n-modal>
|
||||||
|
</Shell>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from "vue";
|
||||||
|
import { NButton, NInputNumber, NRadio, NRadioGroup, NTooltip } from "naive-ui";
|
||||||
|
import Shell from "../../shell/Shell.vue";
|
||||||
|
import { api } from "../../shared/http";
|
||||||
|
|
||||||
|
const mode = ref("local");
|
||||||
|
const seconds = ref(300);
|
||||||
|
const message = ref("");
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
const result = await api<{ loginMode: string; credentialRefreshSeconds: number }>("/api/admin/settings");
|
||||||
|
mode.value = result.loginMode;
|
||||||
|
seconds.value = result.credentialRefreshSeconds;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
message.value = "";
|
||||||
|
try {
|
||||||
|
await api("/api/admin/settings", {
|
||||||
|
method: "PUT",
|
||||||
|
body: JSON.stringify({ loginMode: mode.value, credentialRefreshSeconds: seconds.value }),
|
||||||
|
});
|
||||||
|
message.value = "已保存";
|
||||||
|
} catch (error) {
|
||||||
|
message.value = error instanceof Error ? error.message : "保存失败";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Shell>
|
||||||
|
<header class="topbar">
|
||||||
|
<h1>登录方式 <n-tooltip><template #trigger><span class="hint">?</span></template>同时只启用一种登录方式</n-tooltip></h1>
|
||||||
|
<n-button type="primary" @click="save">保存</n-button>
|
||||||
|
</header>
|
||||||
|
<div class="content">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label>方式</label>
|
||||||
|
<n-radio-group v-model:value="mode">
|
||||||
|
<n-radio value="local">自有账号</n-radio>
|
||||||
|
<n-radio value="nqi">大数据平台账号</n-radio>
|
||||||
|
</n-radio-group>
|
||||||
|
<label>刷新间隔</label>
|
||||||
|
<n-input-number v-model:value="seconds" :min="60" :max="86400" />
|
||||||
|
</div>
|
||||||
|
<p>{{ message }}</p>
|
||||||
|
</div>
|
||||||
|
</Shell>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from "vue";
|
||||||
|
import { NButton, NDataTable, NInput, NInputNumber, NModal, NSelect, NSwitch, NTooltip } from "naive-ui";
|
||||||
|
import Shell from "../../shell/Shell.vue";
|
||||||
|
import { api } from "../../shared/http";
|
||||||
|
|
||||||
|
interface Source {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
kind: string;
|
||||||
|
periodDays: number;
|
||||||
|
enabled: boolean;
|
||||||
|
lastError: string;
|
||||||
|
config: Record<string, string | number | boolean>;
|
||||||
|
}
|
||||||
|
const sources = ref<Source[]>([]);
|
||||||
|
const show = ref(false);
|
||||||
|
const editing = ref<Source | null>(null);
|
||||||
|
const name = ref("");
|
||||||
|
const kind = ref("ftp");
|
||||||
|
const periodDays = ref(1);
|
||||||
|
const enabled = ref(true);
|
||||||
|
const host = ref("");
|
||||||
|
const port = ref(22);
|
||||||
|
const protocol = ref("sftp");
|
||||||
|
const username = ref("");
|
||||||
|
const password = ref("");
|
||||||
|
const path = ref("");
|
||||||
|
const url = ref("");
|
||||||
|
const errorText = ref("");
|
||||||
|
const columns = [
|
||||||
|
{ title: "名称", key: "name" },
|
||||||
|
{ title: "来源", key: "kindLabel" },
|
||||||
|
{ title: "周期(天)", key: "periodDays" },
|
||||||
|
{ title: "状态", key: "stateLabel" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function reset(source?: Source) {
|
||||||
|
editing.value = source || null;
|
||||||
|
name.value = source?.name || "";
|
||||||
|
kind.value = source?.kind || "ftp";
|
||||||
|
periodDays.value = source?.periodDays || 1;
|
||||||
|
enabled.value = source?.enabled ?? true;
|
||||||
|
host.value = String(source?.config.host || "");
|
||||||
|
port.value = Number(source?.config.port || 22);
|
||||||
|
protocol.value = String(source?.config.protocol || "sftp");
|
||||||
|
username.value = String(source?.config.username || "");
|
||||||
|
password.value = "";
|
||||||
|
path.value = String(source?.config.path || "");
|
||||||
|
url.value = String(source?.config.url || "");
|
||||||
|
errorText.value = "";
|
||||||
|
show.value = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
const result = await api<{ sources: Source[] }>("/api/admin/sources");
|
||||||
|
sources.value = result.sources.map((item) => ({
|
||||||
|
...item,
|
||||||
|
kindLabel: item.kind === "nqi" ? "NQI" : "FTP/SFTP",
|
||||||
|
stateLabel: item.lastError || (item.enabled ? "启用" : "停用"),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
errorText.value = "";
|
||||||
|
const config = kind.value === "nqi"
|
||||||
|
? { url: url.value }
|
||||||
|
: { protocol: protocol.value, host: host.value, port: port.value, username: username.value, password: password.value, path: path.value };
|
||||||
|
const body = { name: name.value, kind: kind.value, periodDays: periodDays.value, enabled: enabled.value, config };
|
||||||
|
try {
|
||||||
|
if (editing.value) {
|
||||||
|
await api(`/api/admin/sources/${editing.value.id}`, { method: "PUT", body: JSON.stringify(body) });
|
||||||
|
} else {
|
||||||
|
await api("/api/admin/sources", { method: "POST", body: JSON.stringify(body) });
|
||||||
|
}
|
||||||
|
show.value = false;
|
||||||
|
await load();
|
||||||
|
} catch (error) {
|
||||||
|
errorText.value = error instanceof Error ? error.message : "保存失败";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: number) {
|
||||||
|
await api(`/api/admin/sources/${id}`, { method: "DELETE" });
|
||||||
|
await load();
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Shell>
|
||||||
|
<header class="topbar">
|
||||||
|
<h1>采集 <n-tooltip><template #trigger><span class="hint">?</span></template>周期最短一天,最长一个月</n-tooltip></h1>
|
||||||
|
<n-button type="primary" @click="reset()">添加采集</n-button>
|
||||||
|
</header>
|
||||||
|
<div class="content">
|
||||||
|
<n-data-table :columns="columns" :data="sources" :bordered="false" />
|
||||||
|
<div v-for="source in sources" :key="source.id" class="row-actions" style="margin-top: 8px">
|
||||||
|
<n-button size="small" @click="reset(source)">编辑</n-button>
|
||||||
|
<n-button size="small" @click="remove(source.id)">删除</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<n-modal v-model:show="show" preset="dialog" title="采集" positive-text="保存" negative-text="取消" @positive-click="save">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label>名称</label>
|
||||||
|
<n-input v-model:value="name" />
|
||||||
|
<label>来源</label>
|
||||||
|
<n-select v-model:value="kind" :options="[{ label: 'FTP/SFTP', value: 'ftp' }, { label: 'NQI', value: 'nqi' }]" />
|
||||||
|
<label>周期(天)</label>
|
||||||
|
<n-input-number v-model:value="periodDays" :min="1" :max="31" />
|
||||||
|
<label>启用</label>
|
||||||
|
<n-switch v-model:value="enabled" />
|
||||||
|
<template v-if="kind === 'ftp'">
|
||||||
|
<label>协议</label>
|
||||||
|
<n-select v-model:value="protocol" :options="[{ label: 'SFTP', value: 'sftp' }, { label: 'FTP', value: 'ftp' }]" />
|
||||||
|
<label>主机</label>
|
||||||
|
<n-input v-model:value="host" />
|
||||||
|
<label>端口</label>
|
||||||
|
<n-input-number v-model:value="port" />
|
||||||
|
<label>账号</label>
|
||||||
|
<n-input v-model:value="username" />
|
||||||
|
<label>密码</label>
|
||||||
|
<n-input v-model:value="password" type="password" />
|
||||||
|
<label>路径</label>
|
||||||
|
<n-input v-model:value="path" />
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<label>地址</label>
|
||||||
|
<n-input v-model:value="url" />
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<p v-if="errorText" style="color: var(--danger)">{{ errorText }}</p>
|
||||||
|
</n-modal>
|
||||||
|
</Shell>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from "vue";
|
||||||
|
import { NButton, NDataTable, NInput, NModal, NSelect } from "naive-ui";
|
||||||
|
import Shell from "../../shell/Shell.vue";
|
||||||
|
import { api } from "../../shared/http";
|
||||||
|
|
||||||
|
interface User { id: number; username: string; role: string }
|
||||||
|
const users = ref<User[]>([]);
|
||||||
|
const show = ref(false);
|
||||||
|
const username = ref("");
|
||||||
|
const password = ref("");
|
||||||
|
const role = ref("user");
|
||||||
|
const errorText = ref("");
|
||||||
|
const columns = [
|
||||||
|
{ title: "账号", key: "username" },
|
||||||
|
{ title: "角色", key: "roleLabel" },
|
||||||
|
];
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
const result = await api<{ users: User[] }>("/api/admin/users");
|
||||||
|
users.value = result.users.map((item) => ({ ...item, roleLabel: item.role === "admin" ? "管理员" : "用户" }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function create() {
|
||||||
|
errorText.value = "";
|
||||||
|
try {
|
||||||
|
await api("/api/admin/users", { method: "POST", body: JSON.stringify({ username: username.value, password: password.value, role: role.value }) });
|
||||||
|
show.value = false;
|
||||||
|
username.value = "";
|
||||||
|
password.value = "";
|
||||||
|
await load();
|
||||||
|
} catch (error) {
|
||||||
|
errorText.value = error instanceof Error ? error.message : "添加失败";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: number) {
|
||||||
|
await api(`/api/admin/users/${id}`, { method: "DELETE" });
|
||||||
|
await load();
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Shell>
|
||||||
|
<header class="topbar">
|
||||||
|
<h1>用户</h1>
|
||||||
|
<n-button type="primary" @click="show = true">添加用户</n-button>
|
||||||
|
</header>
|
||||||
|
<div class="content">
|
||||||
|
<n-data-table :columns="columns" :data="users" :bordered="false" />
|
||||||
|
<div v-for="user in users" :key="user.id" class="row-actions" style="margin-top: 8px">
|
||||||
|
<span>{{ user.username }}</span>
|
||||||
|
<n-button size="small" @click="remove(user.id)">删除</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<n-modal v-model:show="show" preset="dialog" title="添加用户" positive-text="保存" negative-text="取消" @positive-click="create">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label>账号</label>
|
||||||
|
<n-input v-model:value="username" />
|
||||||
|
<label>密码</label>
|
||||||
|
<n-input v-model:value="password" type="password" />
|
||||||
|
<label>角色</label>
|
||||||
|
<n-select v-model:value="role" :options="[{ label: '用户', value: 'user' }, { label: '管理员', value: 'admin' }]" />
|
||||||
|
</div>
|
||||||
|
<p v-if="errorText" style="color: var(--danger)">{{ errorText }}</p>
|
||||||
|
</n-modal>
|
||||||
|
</Shell>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from "vue";
|
||||||
|
import { useRouter } from "vue-router";
|
||||||
|
import { NAlert, NButton, NInput } from "naive-ui";
|
||||||
|
import { api, saveSession } from "../../shared/http";
|
||||||
|
import { setThemeChoice, themeChoice, type ThemeChoice } from "../../shared/theme";
|
||||||
|
|
||||||
|
const props = defineProps<{ purpose?: "login" | "pool" }>();
|
||||||
|
const emit = defineEmits<{ done: [] }>();
|
||||||
|
const router = useRouter();
|
||||||
|
const mode = ref("local");
|
||||||
|
const username = ref("");
|
||||||
|
const password = ref("");
|
||||||
|
const captcha = ref("");
|
||||||
|
const captchaUrl = ref("");
|
||||||
|
const sessionId = ref("");
|
||||||
|
const smsCode = ref("");
|
||||||
|
const smsRequired = ref(false);
|
||||||
|
const errorText = ref("");
|
||||||
|
const busy = ref(false);
|
||||||
|
const themes = [
|
||||||
|
{ label: "跟随系统", value: "system" },
|
||||||
|
{ label: "深色", value: "dark" },
|
||||||
|
{ label: "浅色", value: "light" },
|
||||||
|
];
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
if (props.purpose === "pool") {
|
||||||
|
mode.value = "nqi";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = await api<{ mode: string }>("/api/auth/mode");
|
||||||
|
mode.value = result.mode;
|
||||||
|
});
|
||||||
|
|
||||||
|
function fail(error: unknown) {
|
||||||
|
errorText.value = error instanceof Error ? error.message : "登录失败";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function enterLocal() {
|
||||||
|
busy.value = true;
|
||||||
|
errorText.value = "";
|
||||||
|
try {
|
||||||
|
const result = await api<{ token: string; user: { role: string; name: string } }>("/api/auth/local", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ username: username.value, password: password.value }),
|
||||||
|
});
|
||||||
|
saveSession(result.token, result.user);
|
||||||
|
router.push(result.user.role === "admin" ? "/admin/settings" : "/tasks");
|
||||||
|
} catch (error) {
|
||||||
|
fail(error);
|
||||||
|
} finally {
|
||||||
|
busy.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startNqi() {
|
||||||
|
busy.value = true;
|
||||||
|
errorText.value = "";
|
||||||
|
try {
|
||||||
|
const result = await api<{ status: string; token?: string; user?: { role: string; name: string }; sessionId?: string; captcha?: string }>("/api/auth/nqi/start", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ username: username.value, purpose: props.purpose || "login" }),
|
||||||
|
});
|
||||||
|
if (result.status === "ok" && result.token && result.user) {
|
||||||
|
saveSession(result.token, result.user);
|
||||||
|
router.push(result.user.role === "admin" ? "/admin/settings" : "/tasks");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sessionId.value = result.sessionId || "";
|
||||||
|
captchaUrl.value = result.captcha || "";
|
||||||
|
} catch (error) {
|
||||||
|
fail(error);
|
||||||
|
} finally {
|
||||||
|
busy.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshCaptcha() {
|
||||||
|
const result = await api<{ captcha: string }>("/api/auth/nqi/captcha", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ sessionId: sessionId.value }),
|
||||||
|
});
|
||||||
|
captchaUrl.value = result.captcha;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendSms() {
|
||||||
|
busy.value = true;
|
||||||
|
errorText.value = "";
|
||||||
|
try {
|
||||||
|
await api("/api/auth/nqi/sms", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ sessionId: sessionId.value, username: username.value, password: password.value, captcha: captcha.value }),
|
||||||
|
});
|
||||||
|
smsRequired.value = true;
|
||||||
|
} catch (error) {
|
||||||
|
fail(error);
|
||||||
|
} finally {
|
||||||
|
busy.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function finishNqi() {
|
||||||
|
busy.value = true;
|
||||||
|
errorText.value = "";
|
||||||
|
try {
|
||||||
|
const result = await api<{ status: string; token?: string; user?: { role: string; name: string } }>("/api/auth/nqi/finish", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
sessionId: sessionId.value,
|
||||||
|
username: username.value,
|
||||||
|
password: password.value,
|
||||||
|
captcha: captcha.value,
|
||||||
|
smsCode: smsCode.value,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (result.status === "sms_required") {
|
||||||
|
smsRequired.value = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (props.purpose === "pool") {
|
||||||
|
emit("done");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result.token && result.user) {
|
||||||
|
saveSession(result.token, result.user);
|
||||||
|
router.push(result.user.role === "admin" ? "/admin/settings" : "/tasks");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
fail(error);
|
||||||
|
} finally {
|
||||||
|
busy.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function chooseTheme(value: ThemeChoice) {
|
||||||
|
setThemeChoice(value);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div :class="purpose === 'pool' ? '' : 'gate'">
|
||||||
|
<div class="gate-card">
|
||||||
|
<h1 style="margin: 0 0 16px; font-size: 20px; display: flex; justify-content: space-between; align-items: center;">
|
||||||
|
<span>{{ purpose === "pool" ? "添加账号" : "DecomEval" }}</span>
|
||||||
|
<select v-if="purpose !== 'pool'" :value="themeChoice" @change="chooseTheme(($event.target as HTMLSelectElement).value as ThemeChoice)">
|
||||||
|
<option value="system">跟随系统</option>
|
||||||
|
<option value="dark">深色</option>
|
||||||
|
<option value="light">浅色</option>
|
||||||
|
</select>
|
||||||
|
</h1>
|
||||||
|
<n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
|
||||||
|
<div class="form-grid">
|
||||||
|
<label>账号</label>
|
||||||
|
<n-input v-model:value="username" />
|
||||||
|
<label>密码</label>
|
||||||
|
<n-input v-model:value="password" type="password" />
|
||||||
|
<template v-if="mode === 'nqi' && captchaUrl">
|
||||||
|
<label>验证码</label>
|
||||||
|
<div>
|
||||||
|
<n-input v-model:value="captcha" />
|
||||||
|
<img class="captcha" :src="captchaUrl" alt="验证码" @click="refreshCaptcha" />
|
||||||
|
</div>
|
||||||
|
<template v-if="smsRequired">
|
||||||
|
<label>短信验证码</label>
|
||||||
|
<n-input v-model:value="smsCode" />
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<div style="margin-top: 16px; display: flex; justify-content: flex-end; gap: 8px;">
|
||||||
|
<n-button v-if="mode === 'local'" type="primary" :loading="busy" @click="enterLocal">登录</n-button>
|
||||||
|
<template v-else>
|
||||||
|
<n-button v-if="!captchaUrl" type="primary" :loading="busy" @click="startNqi">继续</n-button>
|
||||||
|
<n-button v-if="captchaUrl" :loading="busy" @click="sendSms">发送短信验证码</n-button>
|
||||||
|
<n-button v-if="captchaUrl" type="primary" :loading="busy" @click="finishNqi">登录</n-button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from "vue";
|
||||||
|
import { NButton, NDataTable, NInput, NModal, NSelect, NTooltip } from "naive-ui";
|
||||||
|
import Shell from "../../shell/Shell.vue";
|
||||||
|
import { api, token } from "../../shared/http";
|
||||||
|
|
||||||
|
interface Task { id: number; status: string; format: string; cellKey: string; error: string }
|
||||||
|
const tasks = ref<Task[]>([]);
|
||||||
|
const show = ref(false);
|
||||||
|
const format = ref("xlsx");
|
||||||
|
const cellKey = ref("");
|
||||||
|
const start = ref("");
|
||||||
|
const end = ref("");
|
||||||
|
const errorText = ref("");
|
||||||
|
const formats = [{ label: "xlsx", value: "xlsx" }, { label: "xls", value: "xls" }, { label: "csv", value: "csv" }];
|
||||||
|
const columns = [
|
||||||
|
{ title: "小区", key: "cellKey" },
|
||||||
|
{ title: "格式", key: "format" },
|
||||||
|
{ title: "状态", key: "statusLabel" },
|
||||||
|
{ title: "结果", key: "action" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function statusLabel(status: string) {
|
||||||
|
if (status === "queued") return "排队";
|
||||||
|
if (status === "running") return "进行中";
|
||||||
|
if (status === "done") return "可下载";
|
||||||
|
return "失败";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
const result = await api<{ tasks: Task[] }>("/api/tasks");
|
||||||
|
tasks.value = result.tasks.map((item) => ({ ...item, statusLabel: statusLabel(item.status) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
errorText.value = "";
|
||||||
|
try {
|
||||||
|
await api("/api/tasks", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ format: format.value, cellKey: cellKey.value, start: start.value, end: end.value }),
|
||||||
|
});
|
||||||
|
show.value = false;
|
||||||
|
await load();
|
||||||
|
} catch (error) {
|
||||||
|
errorText.value = error instanceof Error ? error.message : "提交失败";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function download(row: Task) {
|
||||||
|
const response = await fetch(`/api/tasks/${row.id}/file`, { headers: { Authorization: `Bearer ${token()}` } });
|
||||||
|
const blob = await response.blob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = url;
|
||||||
|
link.download = `结果.${row.format}`;
|
||||||
|
link.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Shell>
|
||||||
|
<header class="topbar">
|
||||||
|
<h1>任务 <n-tooltip><template #trigger><span class="hint">?</span></template>按已入库的数据生成结果文件</n-tooltip></h1>
|
||||||
|
<n-button type="primary" @click="show = true">提交任务</n-button>
|
||||||
|
</header>
|
||||||
|
<div class="content">
|
||||||
|
<n-data-table :columns="columns" :data="tasks" :bordered="false">
|
||||||
|
<template #empty>还没有任务</template>
|
||||||
|
</n-data-table>
|
||||||
|
<div v-for="row in tasks.filter((item) => item.status === 'done')" :key="row.id" class="row-actions" style="margin-top: 8px">
|
||||||
|
<n-button size="small" @click="download(row)">下载 {{ row.cellKey || "全部" }}.{{ row.format }}</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<n-modal v-model:show="show" preset="dialog" title="提交任务" positive-text="提交" negative-text="取消" @positive-click="submit">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label>格式</label>
|
||||||
|
<n-select v-model:value="format" :options="formats" />
|
||||||
|
<label>小区</label>
|
||||||
|
<n-input v-model:value="cellKey" placeholder="留空则导出全部" />
|
||||||
|
<label>开始</label>
|
||||||
|
<n-input v-model:value="start" placeholder="YYYY-MM-DD" />
|
||||||
|
<label>结束</label>
|
||||||
|
<n-input v-model:value="end" placeholder="YYYY-MM-DD" />
|
||||||
|
</div>
|
||||||
|
<p v-if="errorText" style="color: var(--danger)">{{ errorText }}</p>
|
||||||
|
</n-modal>
|
||||||
|
</Shell>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { createApp } from "vue";
|
||||||
|
import { createRouter, createWebHistory } from "vue-router";
|
||||||
|
import App from "./App.vue";
|
||||||
|
import LoginView from "./features/auth/LoginView.vue";
|
||||||
|
import TasksView from "./features/user/TasksView.vue";
|
||||||
|
import SettingsView from "./features/admin/SettingsView.vue";
|
||||||
|
import UsersView from "./features/admin/UsersView.vue";
|
||||||
|
import PoolView from "./features/admin/PoolView.vue";
|
||||||
|
import SourcesView from "./features/admin/SourcesView.vue";
|
||||||
|
import { token } from "./shared/http";
|
||||||
|
import "./styles.css";
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(),
|
||||||
|
routes: [
|
||||||
|
{ path: "/login", component: LoginView },
|
||||||
|
{ path: "/", redirect: "/tasks" },
|
||||||
|
{ path: "/tasks", component: TasksView, meta: { role: "user" } },
|
||||||
|
{ path: "/admin/settings", component: SettingsView, meta: { role: "admin" } },
|
||||||
|
{ path: "/admin/users", component: UsersView, meta: { role: "admin" } },
|
||||||
|
{ path: "/admin/pool", component: PoolView, meta: { role: "admin" } },
|
||||||
|
{ path: "/admin/sources", component: SourcesView, meta: { role: "admin" } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
router.beforeEach((to) => {
|
||||||
|
if (to.path === "/login") return token() ? "/" : true;
|
||||||
|
if (!token()) return "/login";
|
||||||
|
const role = sessionStorage.getItem("decom-role");
|
||||||
|
if (to.meta.role === "admin" && role !== "admin") return "/tasks";
|
||||||
|
if (to.meta.role === "user" && role === "admin") return "/admin/settings";
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
createApp(App).use(router).mount("#app");
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
export class ApiError extends Error {
|
||||||
|
status: number;
|
||||||
|
|
||||||
|
constructor(status: number, message: string) {
|
||||||
|
super(message);
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function token() {
|
||||||
|
return sessionStorage.getItem("decom-token") || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setToken(value: string) {
|
||||||
|
if (value) sessionStorage.setItem("decom-token", value);
|
||||||
|
else sessionStorage.removeItem("decom-token");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveSession(tokenValue: string, user: { role: string; name: string }) {
|
||||||
|
setToken(tokenValue);
|
||||||
|
sessionStorage.setItem("decom-role", user.role);
|
||||||
|
sessionStorage.setItem("decom-name", user.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearSession() {
|
||||||
|
setToken("");
|
||||||
|
sessionStorage.removeItem("decom-role");
|
||||||
|
sessionStorage.removeItem("decom-name");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||||
|
const headers = new Headers(options.headers);
|
||||||
|
if (!(options.body instanceof FormData) && options.body && !headers.has("Content-Type")) {
|
||||||
|
headers.set("Content-Type", "application/json");
|
||||||
|
}
|
||||||
|
const current = token();
|
||||||
|
if (current) headers.set("Authorization", `Bearer ${current}`);
|
||||||
|
const response = await fetch(path, { ...options, headers });
|
||||||
|
if (response.status === 401) {
|
||||||
|
setToken("");
|
||||||
|
sessionStorage.removeItem("decom-role");
|
||||||
|
sessionStorage.removeItem("decom-name");
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
let message = "请求失败";
|
||||||
|
try {
|
||||||
|
const payload = await response.json();
|
||||||
|
message = payload.detail || message;
|
||||||
|
} catch {
|
||||||
|
message = response.statusText || message;
|
||||||
|
}
|
||||||
|
throw new ApiError(response.status, message);
|
||||||
|
}
|
||||||
|
if (response.headers.get("content-type")?.includes("application/json")) {
|
||||||
|
return response.json() as Promise<T>;
|
||||||
|
}
|
||||||
|
return response as unknown as T;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { computed, ref } from "vue";
|
||||||
|
|
||||||
|
export type ThemeChoice = "system" | "dark" | "light";
|
||||||
|
|
||||||
|
const STORAGE_KEY = "decom-theme";
|
||||||
|
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
||||||
|
const stored = localStorage.getItem(STORAGE_KEY);
|
||||||
|
export const themeChoice = ref<ThemeChoice>(stored === "dark" || stored === "light" || stored === "system" ? stored : "system");
|
||||||
|
const systemDark = ref(media.matches);
|
||||||
|
|
||||||
|
media.addEventListener("change", () => {
|
||||||
|
systemDark.value = media.matches;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const isDark = computed(() => {
|
||||||
|
if (themeChoice.value === "dark") return true;
|
||||||
|
if (themeChoice.value === "light") return false;
|
||||||
|
return systemDark.value;
|
||||||
|
});
|
||||||
|
|
||||||
|
export function setThemeChoice(choice: ThemeChoice) {
|
||||||
|
themeChoice.value = choice;
|
||||||
|
localStorage.setItem(STORAGE_KEY, choice);
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useRoute, useRouter } from "vue-router";
|
||||||
|
import { NSelect } from "naive-ui";
|
||||||
|
import { api, clearSession, token } from "../shared/http";
|
||||||
|
import { setThemeChoice, themeChoice, type ThemeChoice } from "../shared/theme";
|
||||||
|
|
||||||
|
const route = useRoute();
|
||||||
|
const router = useRouter();
|
||||||
|
const role = sessionStorage.getItem("decom-role");
|
||||||
|
const name = sessionStorage.getItem("decom-name") || "";
|
||||||
|
const items = role === "admin"
|
||||||
|
? [
|
||||||
|
{ label: "登录方式", path: "/admin/settings" },
|
||||||
|
{ label: "用户", path: "/admin/users" },
|
||||||
|
{ label: "账号池", path: "/admin/pool" },
|
||||||
|
{ label: "采集", path: "/admin/sources" },
|
||||||
|
]
|
||||||
|
: [{ label: "任务", path: "/tasks" }];
|
||||||
|
const themes = [
|
||||||
|
{ label: "跟随系统", value: "system" },
|
||||||
|
{ label: "深色", value: "dark" },
|
||||||
|
{ label: "浅色", value: "light" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function chooseTheme(value: ThemeChoice) {
|
||||||
|
setThemeChoice(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
if (token()) {
|
||||||
|
try {
|
||||||
|
await api("/api/auth/logout", { method: "POST" });
|
||||||
|
} catch {
|
||||||
|
/* 本地会话仍会清掉 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
clearSession();
|
||||||
|
router.push("/login");
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="shell">
|
||||||
|
<aside class="sider">
|
||||||
|
<div class="brand">DecomEval</div>
|
||||||
|
<nav class="nav">
|
||||||
|
<button v-for="item in items" :key="item.path" :class="{ on: route.path === item.path }" @click="router.push(item.path)">{{ item.label }}</button>
|
||||||
|
</nav>
|
||||||
|
<div class="sider-foot">
|
||||||
|
<div class="who">{{ name }}</div>
|
||||||
|
<n-select :value="themeChoice" :options="themes" size="small" @update:value="chooseTheme" />
|
||||||
|
<button class="text-button" @click="logout">退出</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
<section class="main"><slot /></section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
:root {
|
||||||
|
color: var(--ink);
|
||||||
|
background: var(--bg);
|
||||||
|
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
html, body, #app { margin: 0; height: 100%; }
|
||||||
|
body { background: var(--bg); }
|
||||||
|
button, input, select { font: inherit; }
|
||||||
|
::selection { background: var(--accent-soft); }
|
||||||
|
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
|
||||||
|
.shell { display: flex; height: 100%; min-height: 0; }
|
||||||
|
.sider {
|
||||||
|
width: 216px;
|
||||||
|
flex: none;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background: var(--sidebar);
|
||||||
|
border-right: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.brand {
|
||||||
|
height: 56px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0 16px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.nav { padding-top: 8px; }
|
||||||
|
.nav button, .text-button {
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--muted);
|
||||||
|
border: 0;
|
||||||
|
padding: 10px 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.nav button.on { color: var(--ink); box-shadow: inset 2px 0 0 var(--accent); }
|
||||||
|
.sider-foot {
|
||||||
|
margin-top: auto;
|
||||||
|
padding: 12px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.who { color: var(--muted); font-size: 12px; }
|
||||||
|
.main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||||
|
.topbar {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 2;
|
||||||
|
height: 56px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0 16px;
|
||||||
|
background: var(--bg);
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.topbar h1 { margin: 0; font-size: 18px; display: flex; align-items: center; gap: 6px; }
|
||||||
|
.content { padding: 16px; overflow: auto; }
|
||||||
|
.panel { background: var(--panel); border: 1px solid var(--line); }
|
||||||
|
.filters, .form-grid { display: grid; grid-template-columns: 96px minmax(0, 280px); gap: 8px 12px; align-items: center; }
|
||||||
|
.hint {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 50%;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 14px;
|
||||||
|
text-align: center;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
.gate {
|
||||||
|
min-height: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 32px 16px;
|
||||||
|
}
|
||||||
|
.gate-card { width: min(440px, 100%); background: var(--panel); border: 1px solid var(--line); padding: 28px; }
|
||||||
|
.captcha { height: 40px; cursor: pointer; }
|
||||||
|
.row-actions { display: flex; gap: 8px; }
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"strict": true,
|
||||||
|
"jsx": "preserve",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"lib": ["ES2022", "DOM"],
|
||||||
|
"skipLibCheck": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
import vue from "@vitejs/plugin-vue";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
"/api": "http://127.0.0.1:8000",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user