"""栅格下载接口。工单、回单等功能各自放在 features 下,不写进这里。""" from __future__ import annotations import asyncio import json import logging import re import shutil from pathlib import Path from fastapi import APIRouter, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse, StreamingResponse from app.features.download.fields import IDENTITY, NETWORKS, cell_columns, columns_for, meta_groups from app.features.download.ids import parse_upload from app.features.download.jobs import run_download from app.platform.client import NqiError from app.platform.constants import CITIES from app.shared.state import state logger = logging.getLogger("nqi.download") router = APIRouter(prefix="/api/download", tags=["download"]) MONTH_RE = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$") def _bad(message: str, status: int = 400) -> HTTPException: return HTTPException(status_code=status, detail=message) def _sse(payload: dict) -> str: return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" def start_job(job_id: str) -> None: job = state.jobs.get(job_id) client = state.require_client() if job.is_active(): raise _bad("这个任务正在下载") job.cancel_event = asyncio.Event() job.status = "queued" job.save() async def runner() -> None: await run_download(job, client) task = asyncio.create_task(runner()) job.task = task def _done(finished: asyncio.Task) -> None: if finished.cancelled(): return error = finished.exception() if error: logger.exception("下载任务异常", exc_info=error) task.add_done_callback(_done) @router.get("/meta") async def meta() -> dict: return { "networks": list(NETWORKS), "cities": CITIES, "groups": {"NR": meta_groups("NR"), "LTE": meta_groups("LTE")}, "fixed": { "grid": [label for label, _field in IDENTITY], "cell": { "NR": [column.label for column in cell_columns("NR")], "LTE": [column.label for column in cell_columns("LTE")], }, }, } @router.get("/jobs") async def list_jobs() -> dict: state.require_client() return {"jobs": state.jobs.list_jobs()} @router.get("/jobs/{job_id}") async def get_job(job_id: str) -> dict: state.require_client() try: job = state.jobs.get(job_id) except NqiError as exc: raise _bad(str(exc), 404) from exc return job.snapshot() @router.post("/jobs") async def create_job( file: UploadFile = File(...), network: str = Form(...), city_code: str = Form(...), month: str = Form(...), groups: str = Form("[]"), concurrency: int = Form(8), output_dir: str = Form(""), ) -> dict: state.require_client() if network not in {"NR", "LTE"}: raise _bad("网络只支持 4G 或 5G") city = next((item for item in CITIES if item["code"] == city_code), None) if city is None: raise _bad("请选择地市") if not MONTH_RE.fullmatch(month): raise _bad("月份格式应为 YYYY-MM") try: selected = json.loads(groups) except json.JSONDecodeError as exc: raise _bad("下载项目格式不正确") from exc if not isinstance(selected, list) or any(not isinstance(item, str) for item in selected): raise _bad("下载项目格式不正确") try: columns_for(network, selected) except ValueError as exc: raise _bad(str(exc)) from exc workers = min(32, max(1, int(concurrency))) suffix = Path(file.filename or "grids.csv").suffix.lower() if suffix not in {".csv", ".txt", ".xlsx"}: raise _bad("区域表只支持 CSV、TXT 或 XLSX") raw = await file.read() if not raw: raise _bad("区域表是空的") if len(raw) > 20 * 1024 * 1024: raise _bad("区域表不能超过 20MB") target: Path | None = None if output_dir.strip(): folder = Path(output_dir.strip()) folder.mkdir(parents=True, exist_ok=True) label = "5G" if network == "NR" else "4G" target = folder / f"栅格_{label}_{city['name']}_{month}.csv" job = state.jobs.create( network=network, city_code=city["code"], city_name=city["name"], month=month, groups=selected, concurrency=workers, grid_ids=[], csv_path=target, ) source = job.directory / f"source{suffix}" source.write_bytes(raw) try: grid_ids = parse_upload(source) except Exception as exc: shutil.rmtree(job.directory, ignore_errors=True) state.jobs.jobs.pop(job.id, None) raise _bad(f"读取区域表失败:{exc}") from exc if not grid_ids: shutil.rmtree(job.directory, ignore_errors=True) state.jobs.jobs.pop(job.id, None) raise _bad("区域表里没有栅格 ID") job.grid_ids = grid_ids job.save() start_job(job.id) return job.snapshot() @router.post("/jobs/{job_id}/cancel") async def cancel_job(job_id: str) -> dict: state.require_client() try: job = state.jobs.get(job_id) except NqiError as exc: raise _bad(str(exc), 404) from exc if not job.is_active(): raise _bad("这个任务没有在下载") job.cancel_event.set() job.message = "正在停止" return job.snapshot() @router.post("/jobs/{job_id}/resume") async def resume_job(job_id: str) -> dict: state.require_client() try: job = state.jobs.get(job_id) except NqiError as exc: raise _bad(str(exc), 404) from exc if job.is_active(): raise _bad("这个任务正在下载") if job.status == "done": raise _bad("这个任务已经完成") start_job(job.id) return job.snapshot() @router.get("/jobs/{job_id}/events") async def job_events(job_id: str) -> StreamingResponse: state.require_client() try: job = state.jobs.get(job_id) except NqiError as exc: raise _bad(str(exc), 404) from exc queue: asyncio.Queue = asyncio.Queue() job.subscribers.append(queue) async def stream(): try: yield _sse({"type": "snapshot", **job.snapshot()}) if job.status in {"done", "done_with_errors", "cancelled", "error"} and not job.is_active(): return while True: event = await queue.get() yield _sse(event) if event.get("type") in {"done", "error", "cancelled"}: return finally: if queue in job.subscribers: job.subscribers.remove(queue) return StreamingResponse(stream(), media_type="text/event-stream") @router.get("/jobs/{job_id}/file") async def job_file(job_id: str) -> FileResponse: state.require_client() try: job = state.jobs.get(job_id) except NqiError as exc: raise _bad(str(exc), 404) from exc if not job.csv_path.exists(): raise _bad("文件还没有生成", 404) return FileResponse(job.csv_path, filename=job.csv_path.name)