361 lines
12 KiB
Python
361 lines
12 KiB
Python
"""栅格下载接口。工单、回单等功能各自放在 features 下,不写进这里。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import re
|
|
import shutil
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Body, File, Form, HTTPException, UploadFile
|
|
|
|
from app.features.download.fields import IDENTITY, NETWORKS, cell_columns, columns_for, grid_spec, meta_groups
|
|
from app.features.download.ids import parse_upload
|
|
from app.features.download.jobs import _write_ids, app_settings, ensure_output_dir, run_download, store_app_settings
|
|
from app.features.download.relocate import current_dir, prepare, resume_moved
|
|
from app.features.download.journal import explain_os_error
|
|
from app.platform.client import NqiError
|
|
from app.platform.constants import CITIES
|
|
from app.shared.files import RECORDS
|
|
from app.shared.paths import DOWNLOAD_ROOT
|
|
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 _spawn(job) -> None:
|
|
async def runner() -> None:
|
|
await run_download(job)
|
|
|
|
task = asyncio.create_task(runner())
|
|
job.task = task
|
|
|
|
def _done(finished: asyncio.Task) -> None:
|
|
if not finished.cancelled():
|
|
error = finished.exception()
|
|
if error:
|
|
logger.exception("下载任务异常", exc_info=error)
|
|
fill_slots()
|
|
|
|
task.add_done_callback(_done)
|
|
|
|
|
|
def fill_slots() -> None:
|
|
if state.expired or state.client is None or state.user is None:
|
|
return
|
|
while state.jobs.running_count() < state.jobs.max_concurrent:
|
|
waiting = state.jobs.queued_jobs()
|
|
if not waiting:
|
|
return
|
|
kind = state.jobs.place(waiting[0])
|
|
if kind == "wait":
|
|
return
|
|
if kind == "run":
|
|
_spawn(waiting[0])
|
|
|
|
|
|
@router.get("/data-dir")
|
|
async def read_data_dir() -> dict:
|
|
state.require_client()
|
|
return current_dir()
|
|
|
|
|
|
@router.post("/data-dir/prepare")
|
|
async def prepare_data_dir(body: Any = Body(default=None)) -> dict:
|
|
state.require_client()
|
|
if not isinstance(body, dict):
|
|
raise _bad("参数格式不正确")
|
|
try:
|
|
return await prepare(str(body.get("path") or ""))
|
|
except NqiError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
|
|
|
|
@router.post("/data-dir/resume")
|
|
async def resume_data_dir() -> dict:
|
|
state.require_client()
|
|
try:
|
|
return await resume_moved()
|
|
except NqiError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
|
|
|
|
@router.get("/settings/app")
|
|
async def read_app_settings() -> dict:
|
|
return app_settings()
|
|
|
|
|
|
@router.put("/settings/app")
|
|
async def write_app_settings(body: Any = Body(default=None)) -> dict:
|
|
if not isinstance(body, dict):
|
|
raise _bad("参数格式不正确")
|
|
try:
|
|
return store_app_settings(bool(body.get("showTray")), bool(body.get("closeToTray")))
|
|
except NqiError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
|
|
|
|
@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")],
|
|
},
|
|
},
|
|
"defaultOutputDir": str(DOWNLOAD_ROOT),
|
|
}
|
|
|
|
|
|
@router.get("/settings")
|
|
async def download_settings() -> dict:
|
|
state.require_client()
|
|
return {"maxConcurrentJobs": state.jobs.max_concurrent}
|
|
|
|
|
|
@router.put("/settings")
|
|
async def update_download_settings(body: Any = Body(default=None)) -> dict:
|
|
state.require_client()
|
|
if not isinstance(body, dict):
|
|
raise _bad("参数格式不正确")
|
|
try:
|
|
value = int(body.get("maxConcurrentJobs"))
|
|
except (TypeError, ValueError) as exc:
|
|
raise _bad("同时任务数不正确") from exc
|
|
try:
|
|
limit = state.jobs.set_limit(value)
|
|
except NqiError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
fill_slots()
|
|
return {"maxConcurrentJobs": limit}
|
|
|
|
|
|
@router.get("/active")
|
|
async def active_downloads() -> dict:
|
|
state.require_client()
|
|
return {"count": state.jobs.running_count()}
|
|
|
|
|
|
@router.get("/jobs")
|
|
async def list_jobs() -> dict:
|
|
state.require_client()
|
|
fill_slots()
|
|
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 | None = File(None),
|
|
network: str = Form(...),
|
|
city_code: str = Form(...),
|
|
month: str = Form(...),
|
|
groups: str = Form("[]"),
|
|
concurrency: int = Form(8),
|
|
output_dir: str = Form(""),
|
|
grid_size: str = Form("GRID20"),
|
|
) -> 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, grid_size)
|
|
size_name, _id_label, _id_field = grid_spec(grid_size)
|
|
except ValueError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
workers = min(32, max(1, int(concurrency)))
|
|
label = "5G" if network == "NR" else "4G"
|
|
target: Path | None = None
|
|
if output_dir.strip():
|
|
folder = Path(output_dir.strip())
|
|
try:
|
|
ensure_output_dir(folder)
|
|
except NqiError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
target = folder / f"栅格_{label}_{size_name}_{city['name']}_{month}.csv"
|
|
whole_city = file is None or not file.filename
|
|
grid_ids: list[str] = []
|
|
duplicates = 0
|
|
if not whole_city:
|
|
suffix = Path(file.filename or "").suffix.lower()
|
|
if suffix != ".csv":
|
|
raise _bad("区域表只支持 CSV")
|
|
raw = await file.read()
|
|
if not raw:
|
|
raise _bad("区域表是空的")
|
|
if len(raw) > 20 * 1024 * 1024:
|
|
raise _bad("区域表不能超过 20MB")
|
|
try:
|
|
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,
|
|
grid_size=grid_size,
|
|
whole_city=whole_city,
|
|
)
|
|
except NqiError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
if not whole_city:
|
|
# 读区域表期间不允许删除,免得删掉目录后又被写进 source.csv 和 ids.txt。
|
|
job.building = True
|
|
source = job.directory / "source.csv"
|
|
try:
|
|
grid_ids, duplicates = await asyncio.to_thread(_save_and_parse, source, raw, grid_size)
|
|
if grid_ids:
|
|
await asyncio.to_thread(_write_ids, job.directory, grid_ids)
|
|
except ValueError as exc:
|
|
await _discard_created_job(job)
|
|
raise _bad(str(exc)) from exc
|
|
except NqiError as exc:
|
|
await _discard_created_job(job)
|
|
raise _bad(str(exc)) from exc
|
|
except OSError as exc:
|
|
await _discard_created_job(job)
|
|
raise _bad(explain_os_error(exc) or f"读取区域表失败:{exc}") from exc
|
|
except Exception as exc:
|
|
await _discard_created_job(job)
|
|
raise _bad(explain_os_error(exc) or f"读取区域表失败:{exc}") from exc
|
|
finally:
|
|
job.building = False
|
|
if not grid_ids:
|
|
await _discard_created_job(job)
|
|
raise _bad("区域表里没有栅格 ID")
|
|
job.keep_ids(grid_ids)
|
|
job.duplicate_count = duplicates
|
|
if duplicates:
|
|
job.message = f"已去掉 {duplicates} 个重复栅格"
|
|
elif whole_city:
|
|
job.message = "准备下载整个地市"
|
|
job.status = "queued"
|
|
job.save()
|
|
fill_slots()
|
|
if job.status == "queued":
|
|
job.message = "等待中"
|
|
job.save()
|
|
# 返回前确认任务记录已经落盘,程序随后被关掉也不会丢任务。
|
|
await job.flush_record()
|
|
return job.snapshot()
|
|
|
|
|
|
def _save_and_parse(source: Path, raw: bytes, grid_size: str) -> tuple[list[str], int]:
|
|
source.write_bytes(raw)
|
|
return parse_upload(source, grid_size)
|
|
|
|
|
|
@router.delete("/jobs/{job_id}")
|
|
async def delete_job(job_id: str, files: bool = False) -> dict:
|
|
state.require_client()
|
|
try:
|
|
await state.jobs.delete(job_id, files=files)
|
|
except NqiError as exc:
|
|
status = 404 if str(exc) == "任务不存在" else 400
|
|
raise _bad(str(exc), status) from exc
|
|
fill_slots()
|
|
return {"ok": True}
|
|
|
|
|
|
async def _discard_created_job(job) -> None:
|
|
state.jobs.jobs.pop(job.id, None)
|
|
# 等记录线程放下这个目录再删,免得删完又被写回一个 job.json。
|
|
await asyncio.wrap_future(RECORDS.drop(job.directory))
|
|
await asyncio.to_thread(_remove_created, job.directory, job.csv_path.parent)
|
|
|
|
|
|
def _remove_created(data: Path, output: Path) -> None:
|
|
shutil.rmtree(data, ignore_errors=True)
|
|
try:
|
|
same = output.resolve() == data.resolve()
|
|
except OSError:
|
|
same = False
|
|
if not same and output.exists():
|
|
shutil.rmtree(output, ignore_errors=True)
|
|
|
|
|
|
@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.status == "done":
|
|
raise _bad("这个任务已经完成")
|
|
if job.status == "creating":
|
|
raise _bad("任务还在创建")
|
|
if job.status == "running" and job.is_active() and not job.closing:
|
|
raise _bad("这个任务正在下载")
|
|
if job.status != "queued":
|
|
job.status = "queued"
|
|
job.message = "等待中"
|
|
job.save()
|
|
fill_slots()
|
|
return job.snapshot()
|
|
|
|
|
|
@router.put("/jobs/{job_id}/concurrency")
|
|
async def update_concurrency(job_id: str, body: dict) -> dict:
|
|
state.require_client()
|
|
if not isinstance(body, dict):
|
|
raise _bad("并发格式不正确")
|
|
try:
|
|
value = int(body.get("concurrency"))
|
|
except (TypeError, ValueError) as exc:
|
|
raise _bad("并发需要是 1 到 32 的整数") from exc
|
|
try:
|
|
job = state.jobs.get(job_id)
|
|
state.jobs.set_concurrency(job, value)
|
|
except NqiError as exc:
|
|
raise _bad(str(exc), 404 if str(exc) == "任务不存在" else 400) from exc
|
|
return job.snapshot()
|
|
|
|
|
|
@router.post("/jobs/{job_id}/pause")
|
|
async def pause_job(job_id: str) -> dict:
|
|
state.require_client()
|
|
try:
|
|
job = state.jobs.get(job_id)
|
|
state.jobs.pause(job)
|
|
except NqiError as exc:
|
|
raise _bad(str(exc), 404 if str(exc) == "任务不存在" else 400) from exc
|
|
fill_slots()
|
|
return job.snapshot()
|