feat: 完善登录保持、栅格下载和任务调度
This commit is contained in:
@@ -122,6 +122,18 @@ _LTE_GROUPS: dict[str, tuple[str, tuple[tuple[str, str], ...]]] = {
|
||||
|
||||
GROUP_ORDER = ("rsrp", "dlsinr", "worse", "cover", "weak", "samples")
|
||||
|
||||
GRID_SIZES = {
|
||||
"GRID20": ("20米", "20米栅格ID", "grid20_id"),
|
||||
"GRID50": ("50米", "50米栅格ID", "grid50_id"),
|
||||
}
|
||||
|
||||
|
||||
def grid_spec(grid_size: str) -> tuple[str, str, str]:
|
||||
try:
|
||||
return GRID_SIZES[grid_size]
|
||||
except KeyError as exc:
|
||||
raise ValueError("栅格只支持 20米或50米") from exc
|
||||
|
||||
|
||||
def group_table(network: str) -> dict[str, tuple[str, tuple[tuple[str, str], ...]]]:
|
||||
if network == "LTE":
|
||||
@@ -145,13 +157,19 @@ def cell_columns(network: str) -> list[Column]:
|
||||
]
|
||||
|
||||
|
||||
def columns_for(network: str, groups: list[str] | None) -> list[Column]:
|
||||
def columns_for(network: str, groups: list[str] | None, grid_size: str = "GRID20") -> list[Column]:
|
||||
table = group_table(network)
|
||||
_label, id_label, id_field = grid_spec(grid_size)
|
||||
selected = [item for item in GROUP_ORDER if groups is None or item in groups]
|
||||
unknown = [item for item in (groups or []) if item not in table]
|
||||
if unknown:
|
||||
raise ValueError("未知的下载项目: " + "、".join(unknown))
|
||||
columns = [Column(label, field, "grid") for label, field in IDENTITY]
|
||||
columns = []
|
||||
for label, field in IDENTITY:
|
||||
if field == "grid20_id":
|
||||
columns.append(Column(id_label, id_field, "grid"))
|
||||
else:
|
||||
columns.append(Column(label, field, "grid"))
|
||||
seen = {column.field for column in columns}
|
||||
for key in selected:
|
||||
for label, field in table[key][1]:
|
||||
|
||||
@@ -10,9 +10,12 @@ _HEADER_KEYS = {
|
||||
"栅格id",
|
||||
"20米栅格id",
|
||||
"grid20_id",
|
||||
"grid50_id",
|
||||
"grid_id",
|
||||
"栅格",
|
||||
"栅格编号",
|
||||
"20米栅格id",
|
||||
"50米栅格id",
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +23,8 @@ def normalize_id(value) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
text = str(value).strip().strip("\ufeff")
|
||||
text = text.translate(str.maketrans("0123456789", "0123456789"))
|
||||
text = "".join(text.split())
|
||||
if text.endswith(".0") and text[:-2].isdigit():
|
||||
text = text[:-2]
|
||||
if not text or not text.isdigit():
|
||||
@@ -31,16 +36,16 @@ def _header_index(header: list[str]) -> int | None:
|
||||
for index, name in enumerate(header):
|
||||
key = name.strip().lower().replace(" ", "").replace("_", "")
|
||||
raw = name.strip().lower().replace(" ", "")
|
||||
if raw in _HEADER_KEYS or key in {"栅格id", "20米栅格id", "grid20id", "gridid"}:
|
||||
if raw in _HEADER_KEYS or key in {"栅格id", "20米栅格id", "50米栅格id", "grid20id", "grid50id", "gridid"}:
|
||||
return index
|
||||
if "栅格" in name and "id" in raw:
|
||||
return index
|
||||
return None
|
||||
|
||||
|
||||
def parse_table(rows: list[list]) -> list[str]:
|
||||
def parse_table(rows: list[list]) -> tuple[list[str], int]:
|
||||
if not rows:
|
||||
return []
|
||||
return [], 0
|
||||
header = ["" if cell is None else str(cell).strip() for cell in rows[0]]
|
||||
column = _header_index(header)
|
||||
start = 0
|
||||
@@ -52,15 +57,19 @@ def parse_table(rows: list[list]) -> list[str]:
|
||||
start = 1
|
||||
found: list[str] = []
|
||||
seen: set[str] = set()
|
||||
duplicates = 0
|
||||
for row in rows[start:]:
|
||||
if column >= len(row):
|
||||
continue
|
||||
grid_id = normalize_id(row[column])
|
||||
if not grid_id or grid_id in seen:
|
||||
if not grid_id:
|
||||
continue
|
||||
if grid_id in seen:
|
||||
duplicates += 1
|
||||
continue
|
||||
seen.add(grid_id)
|
||||
found.append(grid_id)
|
||||
return found
|
||||
return found, duplicates
|
||||
|
||||
|
||||
def _decode_csv(raw: bytes) -> str:
|
||||
@@ -73,23 +82,12 @@ def _decode_csv(raw: bytes) -> str:
|
||||
|
||||
|
||||
def parse_upload(path: Path) -> list[str]:
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".xlsx":
|
||||
from openpyxl import load_workbook
|
||||
|
||||
book = load_workbook(path, read_only=True, data_only=True)
|
||||
try:
|
||||
sheet = book.active
|
||||
rows = [list(row) for row in sheet.iter_rows(values_only=True)]
|
||||
finally:
|
||||
book.close()
|
||||
return parse_table(rows)
|
||||
if suffix not in {".csv", ".txt", ""}:
|
||||
raise ValueError("区域表只支持 CSV、TXT 或 XLSX")
|
||||
if path.suffix.lower() != ".csv":
|
||||
raise ValueError("区域表只支持 CSV")
|
||||
text = _decode_csv(path.read_bytes())
|
||||
sample = text[:4096]
|
||||
try:
|
||||
dialect = csv.Sniffer().sniff(sample, delimiters=",\t;|")
|
||||
dialect = csv.Sniffer().sniff(sample, delimiters=",\t;")
|
||||
except csv.Error:
|
||||
dialect = csv.excel
|
||||
reader = csv.reader(io.StringIO(text), dialect)
|
||||
|
||||
@@ -4,7 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
import re
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -13,9 +15,11 @@ from app.platform.client import NqiClient, NqiError
|
||||
from app.features.download.fields import columns_for
|
||||
from app.features.download.journal import CsvJournal
|
||||
from app.features.download.rows import build_rows
|
||||
from app.shared.paths import DOWNLOAD_DIR
|
||||
from app.shared.paths import DATA_ROOT, DOWNLOAD_DIR
|
||||
|
||||
DATA_DIR = DOWNLOAD_DIR
|
||||
SETTINGS_PATH = DATA_ROOT / "settings.json"
|
||||
_JOB_ID = re.compile(r"^(?:\d{14}(?:_\d+)?|[0-9a-f]{32})$")
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -31,18 +35,28 @@ class DownloadJob:
|
||||
grid_ids: list[str]
|
||||
csv_path: Path
|
||||
created_at: str
|
||||
grid_size: str = "GRID20"
|
||||
whole_city: bool = False
|
||||
id_field: str = "grid20_id"
|
||||
status: str = "queued"
|
||||
message: str = ""
|
||||
completed: int = 0
|
||||
failed: int = 0
|
||||
written_rows: int = 0
|
||||
duplicate_count: int = 0
|
||||
discovered: int = 0
|
||||
listing_done: bool = True
|
||||
last_flush: float = 0.0
|
||||
failures: list[dict[str, str]] = field(default_factory=list)
|
||||
subscribers: list[asyncio.Queue] = field(default_factory=list)
|
||||
task: asyncio.Task | None = None
|
||||
cancel_event: asyncio.Event = field(default_factory=asyncio.Event)
|
||||
run_event: asyncio.Event = field(default_factory=lambda: _set_event())
|
||||
|
||||
@property
|
||||
def total(self) -> int:
|
||||
if self.whole_city:
|
||||
return self.discovered
|
||||
return len(self.grid_ids)
|
||||
|
||||
def is_active(self) -> bool:
|
||||
@@ -57,8 +71,13 @@ class DownloadJob:
|
||||
"cityCode": self.city_code,
|
||||
"cityName": self.city_name,
|
||||
"month": self.month,
|
||||
"gridSize": self.grid_size,
|
||||
"wholeCity": self.whole_city,
|
||||
"listingDone": self.listing_done,
|
||||
"concurrency": self.concurrency,
|
||||
"total": self.total,
|
||||
"discovered": self.discovered,
|
||||
"duplicateCount": self.duplicate_count,
|
||||
"completed": self.completed,
|
||||
"failed": self.failed,
|
||||
"writtenRows": self.written_rows,
|
||||
@@ -75,9 +94,13 @@ class DownloadJob:
|
||||
"cityCode": self.city_code,
|
||||
"cityName": self.city_name,
|
||||
"month": self.month,
|
||||
"gridSize": self.grid_size,
|
||||
"wholeCity": self.whole_city,
|
||||
"groups": self.groups,
|
||||
"concurrency": self.concurrency,
|
||||
"gridIds": self.grid_ids,
|
||||
"gridIds": [] if self.whole_city else self.grid_ids,
|
||||
"discovered": self.discovered,
|
||||
"listingDone": self.listing_done,
|
||||
"csvPath": str(self.csv_path),
|
||||
"createdAt": self.created_at,
|
||||
"status": self.status,
|
||||
@@ -85,6 +108,7 @@ class DownloadJob:
|
||||
"completed": self.completed,
|
||||
"failed": self.failed,
|
||||
"writtenRows": self.written_rows,
|
||||
"duplicateCount": self.duplicate_count,
|
||||
"failures": self.failures[-50:],
|
||||
}
|
||||
(self.directory / "job.json").write_text(
|
||||
@@ -98,9 +122,137 @@ class DownloadJob:
|
||||
await subscriber.put(event)
|
||||
|
||||
|
||||
def _set_event() -> asyncio.Event:
|
||||
event = asyncio.Event()
|
||||
event.set()
|
||||
return event
|
||||
|
||||
|
||||
def _new_job_id() -> str:
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
stamp = datetime.now().strftime("%Y%m%d%H%M%S")
|
||||
number = 1
|
||||
while True:
|
||||
candidate = stamp if number == 1 else f"{stamp}_{number}"
|
||||
try:
|
||||
(DATA_DIR / candidate).mkdir()
|
||||
except FileExistsError:
|
||||
number += 1
|
||||
continue
|
||||
return candidate
|
||||
|
||||
|
||||
def load_task_limit() -> int:
|
||||
try:
|
||||
data = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
|
||||
return min(8, max(1, int(data.get("maxConcurrentJobs") or 2)))
|
||||
except (OSError, json.JSONDecodeError, TypeError, ValueError):
|
||||
return 2
|
||||
|
||||
|
||||
def store_task_limit(value: int) -> int:
|
||||
limit = min(8, max(1, int(value)))
|
||||
SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
SETTINGS_PATH.write_text(
|
||||
json.dumps({"maxConcurrentJobs": limit}, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return limit
|
||||
|
||||
|
||||
class JobManager:
|
||||
def __init__(self) -> None:
|
||||
self.jobs: dict[str, DownloadJob] = {}
|
||||
self.max_concurrent = load_task_limit()
|
||||
|
||||
def running_count(self) -> int:
|
||||
total = 0
|
||||
for job in self.jobs.values():
|
||||
if job.status != "running":
|
||||
continue
|
||||
if job.task is not None and job.task.done():
|
||||
continue
|
||||
total += 1
|
||||
return total
|
||||
|
||||
def hydrate(self) -> None:
|
||||
"""进程重启后,把仍在等待的任务装回内存,空位出现时可以继续排。"""
|
||||
if not DATA_DIR.exists():
|
||||
return
|
||||
for directory in DATA_DIR.iterdir():
|
||||
if not directory.is_dir() or _JOB_ID.fullmatch(directory.name) is None:
|
||||
continue
|
||||
if directory.name in self.jobs:
|
||||
continue
|
||||
path = directory / "job.json"
|
||||
if not path.exists():
|
||||
continue
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
continue
|
||||
if data.get("status") != "queued" or data.get("id") != directory.name:
|
||||
continue
|
||||
try:
|
||||
self.jobs[directory.name] = self._load(directory.name)
|
||||
except NqiError:
|
||||
continue
|
||||
|
||||
def queued_jobs(self) -> list[DownloadJob]:
|
||||
waiting = [job for job in self.jobs.values() if job.status == "queued"]
|
||||
waiting.sort(key=lambda job: (job.created_at, job.id))
|
||||
return waiting
|
||||
|
||||
def place(self, job: DownloadJob) -> str:
|
||||
"""有空位就执行,否则等待。活跃任务只恢复,不另起一次。"""
|
||||
if job.status == "done":
|
||||
raise NqiError("这个任务已经完成")
|
||||
if job.status == "running" and job.is_active():
|
||||
raise NqiError("这个任务正在下载")
|
||||
if self.running_count() >= self.max_concurrent:
|
||||
job.status = "queued"
|
||||
job.message = "等待中"
|
||||
job.save()
|
||||
return "wait"
|
||||
job.run_event.set()
|
||||
job.status = "running"
|
||||
if job.is_active():
|
||||
if job.message in {"", "等待中", "已暂停"}:
|
||||
job.message = "下载中"
|
||||
job.save()
|
||||
return "resume"
|
||||
job.cancel_event = asyncio.Event()
|
||||
job.message = "准备中"
|
||||
job.save()
|
||||
return "run"
|
||||
|
||||
def pause(self, job: DownloadJob) -> None:
|
||||
if job.cancel_event.is_set():
|
||||
raise NqiError("任务正在停止")
|
||||
if job.status != "running" or not job.is_active():
|
||||
raise NqiError("这个任务没有在下载")
|
||||
job.run_event.clear()
|
||||
job.status = "paused"
|
||||
job.message = "已暂停"
|
||||
job.save()
|
||||
|
||||
def request_stop(self, job: DownloadJob) -> None:
|
||||
if not job.is_active():
|
||||
if job.status == "done":
|
||||
raise NqiError("这个任务已经完成")
|
||||
job.status = "cancelled"
|
||||
job.message = "已取消"
|
||||
job.save()
|
||||
return
|
||||
job.cancel_event.set()
|
||||
job.run_event.set()
|
||||
job.status = "running"
|
||||
job.message = "正在停止"
|
||||
job.save()
|
||||
|
||||
def set_limit(self, value: int) -> int:
|
||||
self.max_concurrent = store_task_limit(value)
|
||||
return self.max_concurrent
|
||||
|
||||
def create(
|
||||
self,
|
||||
@@ -113,11 +265,18 @@ class JobManager:
|
||||
concurrency: int,
|
||||
grid_ids: list[str],
|
||||
csv_path: Path | None,
|
||||
grid_size: str = "GRID20",
|
||||
whole_city: bool = False,
|
||||
) -> DownloadJob:
|
||||
job_id = uuid.uuid4().hex
|
||||
job_id = _new_job_id()
|
||||
directory = DATA_DIR / job_id
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
target = csv_path or directory / f"栅格_{'5G' if network == 'NR' else '4G'}_{city_name}_{month}.csv"
|
||||
size_name = "50米" if grid_size == "GRID50" else "20米"
|
||||
filename = f"栅格_{'5G' if network == 'NR' else '4G'}_{size_name}_{city_name}_{month}.csv"
|
||||
if csv_path is None:
|
||||
target = directory / filename
|
||||
else:
|
||||
target = csv_path.parent / job_id / csv_path.name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
job = DownloadJob(
|
||||
id=job_id,
|
||||
@@ -131,6 +290,8 @@ class JobManager:
|
||||
grid_ids=grid_ids,
|
||||
csv_path=target,
|
||||
created_at=datetime.now().isoformat(timespec="seconds"),
|
||||
grid_size=grid_size,
|
||||
whole_city=whole_city,
|
||||
)
|
||||
job.save()
|
||||
self.jobs[job_id] = job
|
||||
@@ -158,18 +319,21 @@ class JobManager:
|
||||
job_id = data.get("id")
|
||||
if job_id in self.jobs:
|
||||
job = self.jobs[job_id]
|
||||
if job.status in {"running", "paused"} and not job.is_active():
|
||||
job.status = "cancelled"
|
||||
job.message = "已中断"
|
||||
snap = job.snapshot()
|
||||
if snap["status"] == "running" and not job.is_active():
|
||||
snap["status"] = "cancelled"
|
||||
snap["message"] = "已中断"
|
||||
items.append(snap)
|
||||
continue
|
||||
status = data.get("status") or "queued"
|
||||
message = data.get("message") or ""
|
||||
if status == "running":
|
||||
if status in {"running", "paused"}:
|
||||
status = "cancelled"
|
||||
message = "已中断"
|
||||
finished, written = _progress_stats(directory)
|
||||
whole = bool(data.get("wholeCity"))
|
||||
discovered = int(data.get("discovered") or 0)
|
||||
stored_ids = data.get("gridIds") or []
|
||||
items.append(
|
||||
{
|
||||
"id": job_id,
|
||||
@@ -179,8 +343,13 @@ class JobManager:
|
||||
"cityCode": data.get("cityCode"),
|
||||
"cityName": data.get("cityName"),
|
||||
"month": data.get("month"),
|
||||
"gridSize": data.get("gridSize") or "GRID20",
|
||||
"wholeCity": whole,
|
||||
"listingDone": bool(data.get("listingDone", not whole)),
|
||||
"concurrency": data.get("concurrency") or 4,
|
||||
"total": len(data.get("gridIds") or []),
|
||||
"total": (discovered or len(stored_ids)) if whole else len(stored_ids),
|
||||
"discovered": discovered,
|
||||
"duplicateCount": int(data.get("duplicateCount") or 0),
|
||||
"completed": finished or data.get("completed") or 0,
|
||||
"failed": data.get("failed") or 0,
|
||||
"writtenRows": written or data.get("writtenRows") or 0,
|
||||
@@ -193,7 +362,7 @@ class JobManager:
|
||||
return items[:20]
|
||||
|
||||
def _load(self, job_id: str) -> DownloadJob:
|
||||
if not re_fullmatch_hex(job_id):
|
||||
if not _JOB_ID.fullmatch(job_id):
|
||||
raise NqiError("任务不存在")
|
||||
path = DATA_DIR / job_id / "job.json"
|
||||
if not path.exists():
|
||||
@@ -206,9 +375,13 @@ class JobManager:
|
||||
city_code=data["cityCode"],
|
||||
city_name=data["cityName"],
|
||||
month=data["month"],
|
||||
grid_size=data.get("gridSize") or "GRID20",
|
||||
whole_city=bool(data.get("wholeCity")),
|
||||
groups=list(data.get("groups") or []),
|
||||
concurrency=int(data.get("concurrency") or 4),
|
||||
grid_ids=[str(item) for item in data.get("gridIds") or []],
|
||||
grid_ids=[] if data.get("wholeCity") else [str(item) for item in data.get("gridIds") or []],
|
||||
discovered=int(data.get("discovered") or 0),
|
||||
listing_done=bool(data.get("listingDone", not data.get("wholeCity"))),
|
||||
csv_path=Path(data["csvPath"]),
|
||||
created_at=data.get("createdAt") or "",
|
||||
status=data.get("status") or "queued",
|
||||
@@ -216,6 +389,7 @@ class JobManager:
|
||||
completed=int(data.get("completed") or 0),
|
||||
failed=int(data.get("failed") or 0),
|
||||
written_rows=int(data.get("writtenRows") or 0),
|
||||
duplicate_count=int(data.get("duplicateCount") or 0),
|
||||
failures=list(data.get("failures") or []),
|
||||
)
|
||||
|
||||
@@ -239,35 +413,130 @@ def _progress_stats(directory: Path) -> tuple[int, int]:
|
||||
return finished, written
|
||||
|
||||
|
||||
def re_fullmatch_hex(value: str) -> bool:
|
||||
return len(value) == 32 and all(char in "0123456789abcdef" for char in value)
|
||||
def _note_progress(job: DownloadJob) -> None:
|
||||
if job.cancel_event.is_set():
|
||||
job.message = "正在停止"
|
||||
return
|
||||
if job.status == "paused":
|
||||
job.message = "已暂停"
|
||||
return
|
||||
if job.status == "running":
|
||||
job.message = _describe(job)
|
||||
|
||||
|
||||
def _describe(job: DownloadJob) -> str:
|
||||
if job.whole_city and not job.listing_done:
|
||||
return f"已完成 {job.completed},已读取 {job.discovered},失败 {job.failed}"
|
||||
return f"已完成 {job.completed}/{job.total},失败 {job.failed}"
|
||||
|
||||
|
||||
async def _wait_job(job: DownloadJob) -> bool:
|
||||
while not job.run_event.is_set():
|
||||
if job.cancel_event.is_set():
|
||||
return False
|
||||
try:
|
||||
await asyncio.wait_for(job.run_event.wait(), timeout=0.3)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
return not job.cancel_event.is_set()
|
||||
|
||||
|
||||
async def _publish(job: DownloadJob, force: bool = False) -> None:
|
||||
now = time.monotonic()
|
||||
if not force and now - job.last_flush < 0.5:
|
||||
return
|
||||
job.last_flush = now
|
||||
job.save()
|
||||
await job.emit("progress")
|
||||
|
||||
|
||||
async def _iterate(ids: list[str]) -> AsyncIterator[str]:
|
||||
for grid_id in ids:
|
||||
yield grid_id
|
||||
|
||||
|
||||
async def run_download(job: DownloadJob, client: NqiClient) -> None:
|
||||
columns = columns_for(job.network, job.groups)
|
||||
columns = columns_for(job.network, job.groups, job.grid_size)
|
||||
journal = CsvJournal(job.csv_path, job.directory / "progress.jsonl", [column.label for column in columns])
|
||||
job.status = "running"
|
||||
job.message = "准备中"
|
||||
if job.status != "paused":
|
||||
job.status = "running"
|
||||
job.message = "准备中"
|
||||
job.save()
|
||||
await job.emit("progress")
|
||||
try:
|
||||
layer = await client.layer_code(city_code=job.city_code, month=job.month, network=job.network)
|
||||
layer = await client.layer_code(
|
||||
city_code=job.city_code,
|
||||
month=job.month,
|
||||
network=job.network,
|
||||
grid_size=job.grid_size,
|
||||
)
|
||||
if job.cancel_event.is_set():
|
||||
job.status = "cancelled"
|
||||
job.message = "已停止"
|
||||
job.save()
|
||||
await job.emit("cancelled")
|
||||
return
|
||||
service_code = layer["serviceCode"]
|
||||
job.id_field = str(layer.get("originRelatedField") or job.id_field)
|
||||
journal.open()
|
||||
job.completed = len(journal.completed)
|
||||
job.written_rows = journal.written_rows
|
||||
job.failures = []
|
||||
job.failed = 0
|
||||
pending = [grid_id for grid_id in job.grid_ids if grid_id not in journal.completed]
|
||||
job.message = "下载中"
|
||||
await job.emit("progress")
|
||||
if job.whole_city:
|
||||
job.listing_done = False
|
||||
job.discovered = len(journal.completed)
|
||||
if job.status != "paused":
|
||||
job.message = "正在读取并下载"
|
||||
await job.emit("progress")
|
||||
|
||||
async def report(count: int) -> None:
|
||||
job.discovered = count
|
||||
_note_progress(job)
|
||||
await _publish(job)
|
||||
|
||||
async def city_ids() -> AsyncIterator[str]:
|
||||
async for grid_id in client.iter_grid_ids(
|
||||
service_code,
|
||||
job.id_field,
|
||||
job.cancel_event,
|
||||
report,
|
||||
journal.completed,
|
||||
job.run_event,
|
||||
):
|
||||
yield grid_id
|
||||
job.listing_done = True
|
||||
_note_progress(job)
|
||||
await _publish(job, force=True)
|
||||
|
||||
await _pump(job, client, journal, columns, service_code, city_ids())
|
||||
return
|
||||
pending: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for grid_id in job.grid_ids:
|
||||
if grid_id in seen or grid_id in journal.completed:
|
||||
continue
|
||||
seen.add(grid_id)
|
||||
pending.append(grid_id)
|
||||
job.grid_ids = list(dict.fromkeys(job.grid_ids))
|
||||
job.discovered = len(job.grid_ids)
|
||||
job.listing_done = True
|
||||
if not pending:
|
||||
if job.cancel_event.is_set():
|
||||
job.status = "cancelled"
|
||||
job.message = "已停止"
|
||||
job.save()
|
||||
await job.emit("cancelled")
|
||||
return
|
||||
job.status = "done"
|
||||
job.message = "已完成"
|
||||
job.save()
|
||||
await job.emit("done")
|
||||
return
|
||||
await _pump(job, client, journal, columns, service_code, pending)
|
||||
if job.status != "paused":
|
||||
job.message = _describe(job)
|
||||
await job.emit("progress")
|
||||
await _pump(job, client, journal, columns, service_code, _iterate(pending))
|
||||
except asyncio.CancelledError:
|
||||
job.status = "cancelled"
|
||||
job.message = "已停止"
|
||||
@@ -283,17 +552,41 @@ async def run_download(job: DownloadJob, client: NqiClient) -> None:
|
||||
journal.close()
|
||||
|
||||
|
||||
async def _pump(job, client, journal, columns, service_code: str, pending: list[str]) -> None:
|
||||
ids: asyncio.Queue[str] = asyncio.Queue()
|
||||
results: asyncio.Queue = asyncio.Queue()
|
||||
for grid_id in pending:
|
||||
ids.put_nowait(grid_id)
|
||||
async def _pump(job: DownloadJob, client, journal, columns, service_code: str, source: AsyncIterator[str]) -> None:
|
||||
ids: asyncio.Queue[str | None] = asyncio.Queue(maxsize=max(64, job.concurrency * 8))
|
||||
results: asyncio.Queue = asyncio.Queue(maxsize=max(8, job.concurrency * 2))
|
||||
produce_done = asyncio.Event()
|
||||
workers = max(1, job.concurrency)
|
||||
|
||||
async def produce() -> None:
|
||||
try:
|
||||
async for grid_id in source:
|
||||
if job.cancel_event.is_set():
|
||||
return
|
||||
while not job.cancel_event.is_set():
|
||||
try:
|
||||
await asyncio.wait_for(ids.put(grid_id), timeout=0.3)
|
||||
break
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
except NqiError as exc:
|
||||
if job.cancel_event.is_set() or str(exc) == "已停止":
|
||||
return
|
||||
raise
|
||||
finally:
|
||||
produce_done.set()
|
||||
|
||||
async def worker() -> None:
|
||||
while not job.cancel_event.is_set():
|
||||
if not await _wait_job(job):
|
||||
return
|
||||
try:
|
||||
grid_id = ids.get_nowait()
|
||||
except asyncio.QueueEmpty:
|
||||
grid_id = await asyncio.wait_for(ids.get(), timeout=0.3)
|
||||
except asyncio.TimeoutError:
|
||||
if produce_done.is_set() and ids.empty():
|
||||
return
|
||||
continue
|
||||
if grid_id is None or not await _wait_job(job):
|
||||
return
|
||||
error = ""
|
||||
rows = None
|
||||
@@ -301,7 +594,7 @@ async def _pump(job, client, journal, columns, service_code: str, pending: list[
|
||||
if job.cancel_event.is_set():
|
||||
return
|
||||
try:
|
||||
properties = await client.grid_feature(service_code, grid_id)
|
||||
properties = await client.grid_feature(service_code, grid_id, job.id_field)
|
||||
cells = await client.cell_rows(service_code, grid_id, job.network)
|
||||
rows = build_rows(grid_id, properties, cells, columns)
|
||||
error = ""
|
||||
@@ -322,21 +615,22 @@ async def _pump(job, client, journal, columns, service_code: str, pending: list[
|
||||
return
|
||||
kind, grid_id, payload = item
|
||||
if kind == "ok":
|
||||
written = journal.write_rows(grid_id, payload)
|
||||
journal.write_rows(grid_id, payload)
|
||||
job.completed += 1
|
||||
job.written_rows = journal.written_rows
|
||||
if written == 0:
|
||||
job.written_rows = journal.written_rows
|
||||
else:
|
||||
job.failed += 1
|
||||
job.failures.append({"id": grid_id, "message": payload})
|
||||
job.message = f"已完成 {job.completed}/{job.total},失败 {job.failed}"
|
||||
job.save()
|
||||
await job.emit("progress")
|
||||
if len(job.failures) > 50:
|
||||
del job.failures[:-50]
|
||||
_note_progress(job)
|
||||
await _publish(job)
|
||||
|
||||
async def finish_workers() -> None:
|
||||
await asyncio.gather(*(worker() for _ in range(job.concurrency)))
|
||||
await results.put(None)
|
||||
try:
|
||||
await asyncio.gather(produce(), *(worker() for _ in range(workers)))
|
||||
finally:
|
||||
await results.put(None)
|
||||
|
||||
closer = asyncio.create_task(finish_workers())
|
||||
try:
|
||||
@@ -345,7 +639,9 @@ async def _pump(job, client, journal, columns, service_code: str, pending: list[
|
||||
finally:
|
||||
if not closer.done():
|
||||
closer.cancel()
|
||||
unfinished = job.completed + job.failed < job.total
|
||||
if job.whole_city and not job.cancel_event.is_set() and job.discovered == 0 and job.completed == 0:
|
||||
raise NqiError("这个地市没有栅格")
|
||||
unfinished = job.completed + job.failed < job.total or (job.whole_city and not job.listing_done)
|
||||
if job.cancel_event.is_set() and unfinished:
|
||||
job.status = "cancelled"
|
||||
job.message = "已停止"
|
||||
|
||||
@@ -12,7 +12,7 @@ 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.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 run_download
|
||||
from app.platform.client import NqiError
|
||||
@@ -32,15 +32,7 @@ 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()
|
||||
|
||||
def _spawn(job, client) -> None:
|
||||
async def runner() -> None:
|
||||
await run_download(job, client)
|
||||
|
||||
@@ -48,15 +40,31 @@ def start_job(job_id: str) -> None:
|
||||
job.task = task
|
||||
|
||||
def _done(finished: asyncio.Task) -> None:
|
||||
if finished.cancelled():
|
||||
return
|
||||
error = finished.exception()
|
||||
if error:
|
||||
logger.exception("下载任务异常", exc_info=error)
|
||||
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:
|
||||
client = state.client
|
||||
if client is None:
|
||||
return
|
||||
state.jobs.hydrate()
|
||||
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], client)
|
||||
|
||||
|
||||
@router.get("/meta")
|
||||
async def meta() -> dict:
|
||||
return {
|
||||
@@ -73,9 +81,28 @@ async def meta() -> dict:
|
||||
}
|
||||
|
||||
|
||||
@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: dict) -> dict:
|
||||
state.require_client()
|
||||
try:
|
||||
value = int(body.get("maxConcurrentJobs"))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad("同时任务数不正确") from exc
|
||||
limit = state.jobs.set_limit(value)
|
||||
fill_slots()
|
||||
return {"maxConcurrentJobs": limit}
|
||||
|
||||
|
||||
@router.get("/jobs")
|
||||
async def list_jobs() -> dict:
|
||||
state.require_client()
|
||||
fill_slots()
|
||||
return {"jobs": state.jobs.list_jobs()}
|
||||
|
||||
|
||||
@@ -91,13 +118,14 @@ async def get_job(job_id: str) -> dict:
|
||||
|
||||
@router.post("/jobs")
|
||||
async def create_job(
|
||||
file: UploadFile = File(...),
|
||||
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"}:
|
||||
@@ -114,24 +142,29 @@ async def create_job(
|
||||
if not isinstance(selected, list) or any(not isinstance(item, str) for item in selected):
|
||||
raise _bad("下载项目格式不正确")
|
||||
try:
|
||||
columns_for(network, selected)
|
||||
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)))
|
||||
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")
|
||||
label = "5G" if network == "NR" else "4G"
|
||||
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"
|
||||
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")
|
||||
job = state.jobs.create(
|
||||
network=network,
|
||||
city_code=city["code"],
|
||||
@@ -141,22 +174,34 @@ async def create_job(
|
||||
concurrency=workers,
|
||||
grid_ids=[],
|
||||
csv_path=target,
|
||||
grid_size=grid_size,
|
||||
whole_city=whole_city,
|
||||
)
|
||||
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")
|
||||
if not whole_city:
|
||||
source = job.directory / "source.csv"
|
||||
source.write_bytes(raw)
|
||||
try:
|
||||
grid_ids, duplicates = 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.duplicate_count = duplicates
|
||||
if duplicates:
|
||||
job.message = f"已去掉 {duplicates} 个重复栅格"
|
||||
elif whole_city:
|
||||
job.message = "准备下载整个地市"
|
||||
job.status = "queued"
|
||||
job.save()
|
||||
start_job(job.id)
|
||||
fill_slots()
|
||||
if job.status == "queued":
|
||||
job.message = "等待中"
|
||||
job.save()
|
||||
return job.snapshot()
|
||||
|
||||
|
||||
@@ -167,10 +212,10 @@ async def cancel_job(job_id: str) -> dict:
|
||||
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 = "正在停止"
|
||||
try:
|
||||
state.jobs.request_stop(job)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
return job.snapshot()
|
||||
|
||||
|
||||
@@ -181,11 +226,27 @@ async def resume_job(job_id: str) -> dict:
|
||||
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)
|
||||
if job.status == "running" and job.is_active():
|
||||
raise _bad("这个任务正在下载")
|
||||
if job.status != "queued":
|
||||
job.status = "queued"
|
||||
job.message = "等待中"
|
||||
job.save()
|
||||
fill_slots()
|
||||
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()
|
||||
|
||||
|
||||
|
||||
@@ -37,8 +37,9 @@ def build_rows(
|
||||
) -> list[list[str]]:
|
||||
"""一个栅格多小区时每个小区一行;没有小区时仍保留一行,小区列留空。"""
|
||||
props = dict(properties or {})
|
||||
if props.get("grid20_id") in (None, ""):
|
||||
props["grid20_id"] = grid_id
|
||||
for field in ("grid20_id", "grid50_id"):
|
||||
if props.get(field) in (None, ""):
|
||||
props[field] = grid_id
|
||||
records = cells or [None]
|
||||
rows: list[list[str]] = []
|
||||
for index, cell in enumerate(records, start=1):
|
||||
|
||||
+14
-6
@@ -1,12 +1,14 @@
|
||||
"""本机接口。只监听 127.0.0.1。功能路由按目录挂上。"""
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager, suppress
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.features.download.router import router as download_router
|
||||
from app.platform.auth import router as auth_router
|
||||
from app.platform.keepalive import session_keepalive
|
||||
from app.shared.state import state
|
||||
|
||||
ORIGINS = [
|
||||
@@ -20,11 +22,17 @@ ORIGINS = [
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
yield
|
||||
if state.client is not None:
|
||||
await state.client.aclose()
|
||||
for client, _challenge in state.flows.values():
|
||||
await client.aclose()
|
||||
keepalive = asyncio.create_task(session_keepalive())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
keepalive.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await keepalive
|
||||
if state.client is not None:
|
||||
await state.client.aclose()
|
||||
for client, _challenge in state.flows.values():
|
||||
await client.aclose()
|
||||
|
||||
|
||||
app = FastAPI(title="NqiTools", lifespan=lifespan)
|
||||
|
||||
@@ -9,6 +9,7 @@ import uuid
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from app.platform.client import NqiError
|
||||
from app.platform.sessions import available_accounts, remember, resume
|
||||
from app.shared.state import state
|
||||
|
||||
logger = logging.getLogger("nqi.auth")
|
||||
@@ -93,16 +94,17 @@ async def login(body: dict) -> dict:
|
||||
if not (challenge.config_ready and sms_code):
|
||||
code = await client.prepare_login(challenge, username, password, captcha)
|
||||
if code == "1" and not sms_code:
|
||||
return {"status": "sms_required", "message": "请获取并填写短信验证码"}
|
||||
return {"status": "sms_required"}
|
||||
user = await client.submit_login(challenge, sms_code)
|
||||
except NqiError as exc:
|
||||
try:
|
||||
await client.refresh_captcha(challenge)
|
||||
except NqiError:
|
||||
pass
|
||||
challenge.config_ready = False
|
||||
if not challenge.config_ready:
|
||||
try:
|
||||
await client.refresh_captcha(challenge)
|
||||
except NqiError:
|
||||
pass
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
challenge.password = ""
|
||||
remember(user, client.export_cookies())
|
||||
state.flows.pop(session_id, None)
|
||||
if state.client is not None and state.client is not client:
|
||||
await state.client.aclose()
|
||||
@@ -111,6 +113,27 @@ async def login(body: dict) -> dict:
|
||||
return {"status": "ok", "user": user}
|
||||
|
||||
|
||||
@router.get("/saved")
|
||||
async def saved() -> dict:
|
||||
return {"accounts": await available_accounts()}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume_saved(body: dict) -> dict:
|
||||
login_id = str(body.get("loginId") or "").strip()
|
||||
if not login_id:
|
||||
raise _bad("请选择账号")
|
||||
try:
|
||||
client, user = await resume(login_id)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
if state.client is not None and state.client is not client:
|
||||
await state.client.aclose()
|
||||
state.client = client
|
||||
state.user = user
|
||||
return {"status": "ok", "user": user}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def me() -> dict:
|
||||
state.require_client()
|
||||
|
||||
+365
-57
@@ -2,24 +2,30 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import calendar
|
||||
import json
|
||||
import re
|
||||
from collections import deque
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass, field
|
||||
from urllib.parse import urljoin
|
||||
from urllib.parse import quote, urlencode, urljoin
|
||||
|
||||
import httpx
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
|
||||
from app.features.download.ids import normalize_id
|
||||
from app.platform.constants import (
|
||||
APP_KEY,
|
||||
CAS_CAPTCHA,
|
||||
CAS_CONFIG,
|
||||
CAS_LOGIN,
|
||||
CAS_PASSWORD_CHECK,
|
||||
CAS_SMS,
|
||||
CAS_USER,
|
||||
PORTAL_ONLINE,
|
||||
GIS_API,
|
||||
GIS_PROD,
|
||||
ORIGIN,
|
||||
@@ -61,12 +67,48 @@ def _code(payload: dict) -> str:
|
||||
return str(payload.get("code", ""))
|
||||
|
||||
|
||||
def login_page_url(url: str) -> str:
|
||||
"""表单没有 action 时,浏览器会提交到带 service 的当前登录地址。"""
|
||||
if "service=" in url:
|
||||
return url
|
||||
return f"{CAS_LOGIN}?service={quote(PORTAL_SERVICE, safe='')}"
|
||||
|
||||
|
||||
def sms_notice(payload: dict) -> str:
|
||||
"""sendCode1 的 data 是一段再套了一层的 JSON。"""
|
||||
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 _transport_error(exc: Exception) -> None:
|
||||
if isinstance(exc, httpx.TimeoutException):
|
||||
raise NqiError("平台响应超时,请稍后重试") from exc
|
||||
if isinstance(exc, httpx.RequestError):
|
||||
raise NqiError("连接失败,请稍后重试") from exc
|
||||
raise exc
|
||||
|
||||
|
||||
@dataclass
|
||||
class LoginChallenge:
|
||||
execution: str
|
||||
public_key: str
|
||||
form_action: str
|
||||
captcha_png: bytes
|
||||
page_url: str
|
||||
captcha_type: str = "image/jpeg"
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
@@ -87,7 +129,8 @@ class NqiClient:
|
||||
},
|
||||
timeout=httpx.Timeout(45.0, connect=15.0),
|
||||
follow_redirects=True,
|
||||
trust_env=True,
|
||||
trust_env=False,
|
||||
limits=httpx.Limits(max_connections=200, max_keepalive_connections=40),
|
||||
)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
@@ -124,20 +167,35 @@ class NqiClient:
|
||||
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.client.get(CAS_LOGIN, params={"service": PORTAL_SERVICE})
|
||||
try:
|
||||
response = await self.client.get(CAS_LOGIN, params={"service": PORTAL_SERVICE})
|
||||
except (httpx.TimeoutException, httpx.RequestError) as exc:
|
||||
_transport_error(exc)
|
||||
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))
|
||||
action_match = _FORM_ACTION.search(html) or _FORM_ACTION_REV.search(html)
|
||||
action = action_match.group(1) if action_match and action_match.group(1) else str(response.url)
|
||||
action = action_match.group(1) if action_match and action_match.group(1) else page_url
|
||||
if action.startswith("/"):
|
||||
action = ORIGIN + action
|
||||
elif not action.startswith("http"):
|
||||
action = urljoin(str(response.url), action)
|
||||
captcha = await self.client.get(CAS_CAPTCHA, headers={"Referer": str(response.url)})
|
||||
action = urljoin(page_url, action)
|
||||
try:
|
||||
captcha = await self.client.get(CAS_CAPTCHA, headers={"Referer": page_url})
|
||||
except (httpx.TimeoutException, httpx.RequestError) as exc:
|
||||
_transport_error(exc)
|
||||
if captcha.status_code != 200 or not captcha.content:
|
||||
raise NqiError("验证码获取失败")
|
||||
return LoginChallenge(
|
||||
@@ -145,15 +203,19 @@ class NqiClient:
|
||||
public_key=public_key.group(1),
|
||||
form_action=action,
|
||||
captcha_png=captcha.content,
|
||||
page_url=page_url,
|
||||
captcha_type=_media_type(captcha),
|
||||
)
|
||||
|
||||
async def refresh_captcha(self, challenge: LoginChallenge) -> bytes:
|
||||
response = await self.client.get(
|
||||
CAS_CAPTCHA,
|
||||
params={"id": "refresh"},
|
||||
headers={"Referer": CAS_LOGIN},
|
||||
)
|
||||
try:
|
||||
response = await self.client.get(
|
||||
CAS_CAPTCHA,
|
||||
params={"id": "refresh"},
|
||||
headers={"Referer": challenge.page_url},
|
||||
)
|
||||
except (httpx.TimeoutException, httpx.RequestError) as exc:
|
||||
_transport_error(exc)
|
||||
if response.status_code != 200 or not response.content:
|
||||
raise NqiError("验证码刷新失败")
|
||||
challenge.captcha_png = response.content
|
||||
@@ -169,11 +231,14 @@ class NqiClient:
|
||||
"password": rsa_encrypt(challenge.public_key, password),
|
||||
"captcha": challenge.captcha,
|
||||
}
|
||||
response = await self.client.post(
|
||||
CAS_CONFIG,
|
||||
json=payload,
|
||||
headers={"Referer": CAS_LOGIN, "Origin": ORIGIN},
|
||||
)
|
||||
try:
|
||||
response = await self.client.post(
|
||||
CAS_CONFIG,
|
||||
json=payload,
|
||||
headers=self._ajax_headers(challenge),
|
||||
)
|
||||
except (httpx.TimeoutException, httpx.RequestError) as exc:
|
||||
_transport_error(exc)
|
||||
data = _json_or_error(response, "登录校验失败")
|
||||
code = _code(data)
|
||||
if code not in {"0", "1"}:
|
||||
@@ -189,45 +254,55 @@ class NqiClient:
|
||||
"loginId": rsa_encrypt(challenge.public_key, challenge.username),
|
||||
"password": rsa_encrypt(challenge.public_key, challenge.password),
|
||||
}
|
||||
response = await self.client.post(
|
||||
CAS_SMS,
|
||||
json=payload,
|
||||
headers={"Referer": CAS_LOGIN, "Origin": ORIGIN},
|
||||
)
|
||||
try:
|
||||
response = await self.client.post(
|
||||
CAS_SMS,
|
||||
json=payload,
|
||||
headers=self._ajax_headers(challenge),
|
||||
timeout=httpx.Timeout(120.0, connect=15.0),
|
||||
)
|
||||
except httpx.TimeoutException as exc:
|
||||
raise NqiError("短信发送超时,请稍后重试") from exc
|
||||
except httpx.RequestError as exc:
|
||||
_transport_error(exc)
|
||||
data = _json_or_error(response, "短信发送失败")
|
||||
if data.get("success") is False:
|
||||
raise NqiError(str(data.get("msg") or "短信发送失败"))
|
||||
return str(data.get("msg") or "短信已发送")
|
||||
return sms_notice(data)
|
||||
|
||||
async def submit_login(self, challenge: LoginChallenge, sms_code: str = "") -> dict:
|
||||
if not challenge.config_ready:
|
||||
raise NqiError("请先完成验证码校验")
|
||||
form = {
|
||||
"username": rsa_encrypt(challenge.public_key, challenge.username),
|
||||
"password": rsa_encrypt(challenge.public_key, challenge.password),
|
||||
"msgCode": sms_code.strip(),
|
||||
"captcha": challenge.captcha,
|
||||
"uuid": "",
|
||||
"execution": challenge.execution,
|
||||
"_eventId": "submit",
|
||||
"geolocation": "",
|
||||
}
|
||||
response = await self.client.post(
|
||||
challenge.form_action,
|
||||
data=form,
|
||||
headers={
|
||||
"Referer": CAS_LOGIN,
|
||||
"Origin": ORIGIN,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
)
|
||||
# 网页表单里 password 在 username 前面,提交地址是带 service 的登录页。
|
||||
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", ""),
|
||||
]
|
||||
try:
|
||||
response = await self.client.post(
|
||||
challenge.page_url,
|
||||
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",
|
||||
},
|
||||
)
|
||||
except httpx.TimeoutException as exc:
|
||||
raise NqiError("登录超时,请稍后重试") from exc
|
||||
except httpx.RequestError as exc:
|
||||
_transport_error(exc)
|
||||
if not self.ticket():
|
||||
message = _ERROR_TEXT.search(response.text)
|
||||
detail = re.sub(r"<[^>]+>", "", message.group(1)).strip() if message else ""
|
||||
raise NqiError(detail or "登录未成功,请检查验证码或短信验证码")
|
||||
raise NqiError(_login_failure_message(response))
|
||||
return await self.current_user()
|
||||
|
||||
async def current_user(self) -> dict:
|
||||
async def _cas_user_payload(self) -> dict:
|
||||
ticket = self.ticket()
|
||||
headers = {"Referer": f"{ORIGIN}/pro-portal/"}
|
||||
if ticket:
|
||||
@@ -236,19 +311,69 @@ class NqiClient:
|
||||
data = _json_or_error(response, "读取登录用户失败")
|
||||
if not data.get("loginId") and not data.get("userName"):
|
||||
raise NqiError("登录状态已失效")
|
||||
return {
|
||||
"loginId": data.get("loginId") or "",
|
||||
"userName": data.get("userName") or "",
|
||||
"cityName": data.get("cityName") or "",
|
||||
"orgName": data.get("orgName") or "",
|
||||
}
|
||||
return data
|
||||
|
||||
async def layer_code(self, *, city_code: str, month: str, network: str) -> dict:
|
||||
async def current_user(self) -> dict:
|
||||
return _public_user(await self._cas_user_payload())
|
||||
|
||||
async def touch_session(self) -> dict:
|
||||
"""访问门户和图层接口,滑动服务端的登录有效期。"""
|
||||
try:
|
||||
data = await self._cas_user_payload()
|
||||
except (httpx.TimeoutException, httpx.RequestError) as exc:
|
||||
_transport_error(exc)
|
||||
raise
|
||||
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
|
||||
try:
|
||||
response = await self.client.post(
|
||||
CAS_PASSWORD_CHECK,
|
||||
json={},
|
||||
headers=headers,
|
||||
timeout=httpx.Timeout(20.0, connect=10.0),
|
||||
)
|
||||
except (httpx.TimeoutException, httpx.RequestError) as exc:
|
||||
_transport_error(exc)
|
||||
if response.status_code in {401, 403}:
|
||||
raise NqiError("登录已失效,请重新登录")
|
||||
|
||||
async def _touch_online(self) -> None:
|
||||
try:
|
||||
await self.client.get(
|
||||
PORTAL_ONLINE,
|
||||
headers={"Referer": f"{ORIGIN}/pro-portal/"},
|
||||
timeout=httpx.Timeout(20.0, connect=10.0),
|
||||
follow_redirects=False,
|
||||
)
|
||||
except (httpx.TimeoutException, httpx.RequestError):
|
||||
return
|
||||
|
||||
async def layer_code(self, *, city_code: str, month: str, network: str, grid_size: str = "GRID20") -> dict:
|
||||
params = {
|
||||
"dataType": "GRID",
|
||||
"cityCode": city_code,
|
||||
"date": month_end(month),
|
||||
"gridSize": "GRID20",
|
||||
"gridSize": grid_size,
|
||||
"networkType": network,
|
||||
}
|
||||
payload = await self._signed_get(f"{GIS_API}/base/v2/zc/layerCode/get", params)
|
||||
@@ -262,7 +387,7 @@ class NqiClient:
|
||||
raise NqiError(f"{month} 暂无数据")
|
||||
return data
|
||||
|
||||
async def grid_feature(self, service_code: str, grid_id: str) -> dict | None:
|
||||
async def grid_feature(self, service_code: str, grid_id: str, id_field: str = "grid20_id") -> dict | None:
|
||||
params = {
|
||||
"maxFeatures": "5",
|
||||
"SERVICE": "Wfs",
|
||||
@@ -273,7 +398,7 @@ class NqiClient:
|
||||
"STYLES": "",
|
||||
"ak": APP_KEY,
|
||||
"sig": wfs_sig(service_code),
|
||||
"CQL_FILTER": f"grid20_id={grid_id}",
|
||||
"CQL_FILTER": f"{id_field}={grid_id}",
|
||||
}
|
||||
response = await self.client.get(
|
||||
f"{GIS_PROD}/api/{service_code}/wfs",
|
||||
@@ -296,6 +421,114 @@ class NqiClient:
|
||||
return None
|
||||
return features[0].get("properties") or {}
|
||||
|
||||
async def iter_grid_ids(
|
||||
self,
|
||||
service_code: str,
|
||||
id_field: str,
|
||||
cancel_event: asyncio.Event,
|
||||
progress,
|
||||
skip: set[str] | None = None,
|
||||
run_event: asyncio.Event | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""按图层范围分块产出编号。一块返回就交出,不等整层读完。"""
|
||||
bounds = await self._layer_bounds(service_code)
|
||||
seen: set[str] = set(skip or ())
|
||||
pending: deque[tuple[tuple[float, float, float, float], int]] = deque(
|
||||
(tile, 0) for tile in _tiles(*bounds, 0.05)
|
||||
)
|
||||
inflight: set[asyncio.Task] = set()
|
||||
|
||||
async def fetch(tile: tuple[float, float, float, float], depth: int):
|
||||
features, matched = await self._tile_features(service_code, id_field, tile)
|
||||
return tile, depth, features, matched
|
||||
|
||||
try:
|
||||
await progress(len(seen))
|
||||
while not cancel_event.is_set() and (pending or inflight):
|
||||
if not await _wait_turn(cancel_event, run_event):
|
||||
break
|
||||
while pending and len(inflight) < 3 and not cancel_event.is_set():
|
||||
if run_event is not None and not run_event.is_set():
|
||||
break
|
||||
tile, depth = pending.popleft()
|
||||
inflight.add(asyncio.create_task(fetch(tile, depth)))
|
||||
if not inflight:
|
||||
if run_event is not None and not run_event.is_set():
|
||||
continue
|
||||
break
|
||||
done, inflight = await asyncio.wait(inflight, timeout=0.5, return_when=asyncio.FIRST_COMPLETED)
|
||||
if not done:
|
||||
continue
|
||||
fresh: list[str] = []
|
||||
for task in done:
|
||||
tile, depth, features, matched = task.result()
|
||||
width = tile[2] - tile[0]
|
||||
if matched > len(features) and width > 0.02 and depth < 5:
|
||||
pending.extend((child, depth + 1) for child in _split_tile(tile))
|
||||
continue
|
||||
for feature in features:
|
||||
grid_id = normalize_id((feature.get("properties") or {}).get(id_field))
|
||||
if not grid_id or grid_id in seen:
|
||||
continue
|
||||
seen.add(grid_id)
|
||||
fresh.append(grid_id)
|
||||
await progress(len(seen))
|
||||
for grid_id in fresh:
|
||||
if not await _wait_turn(cancel_event, run_event):
|
||||
break
|
||||
yield grid_id
|
||||
if cancel_event.is_set():
|
||||
raise NqiError("已停止")
|
||||
finally:
|
||||
for task in inflight:
|
||||
task.cancel()
|
||||
if inflight:
|
||||
await asyncio.gather(*inflight, return_exceptions=True)
|
||||
|
||||
async def _layer_bounds(self, service_code: str) -> tuple[float, float, float, float]:
|
||||
response = await self.client.get(
|
||||
f"{GIS_PROD}/api/{service_code}/wfs",
|
||||
params={"SERVICE": "Wfs", "REQUEST": "GetCapabilities", "ak": APP_KEY, "sig": wfs_sig(service_code)},
|
||||
headers={"Referer": f"{ORIGIN}/pro-problem-warehouse-web/"},
|
||||
)
|
||||
if response.status_code != 200:
|
||||
raise NqiError("没有读到图层范围")
|
||||
match = re.search(
|
||||
r"LowerCorner>\s*([-\d.]+)\s+([-\d.]+).*?UpperCorner>\s*([-\d.]+)\s+([-\d.]+)",
|
||||
response.text,
|
||||
re.S,
|
||||
)
|
||||
if not match:
|
||||
raise NqiError("没有读到图层范围")
|
||||
west, south, east, north = (float(item) for item in match.groups())
|
||||
return west, south, east, north
|
||||
|
||||
async def _tile_features(self, service_code: str, id_field: str, tile: tuple[float, float, float, float]) -> tuple[list[dict], int]:
|
||||
west, south, east, north = tile
|
||||
ring = f"{west} {south},{east} {south},{east} {north},{west} {north},{west} {south}"
|
||||
response = await self.client.get(
|
||||
f"{GIS_PROD}/api/{service_code}/wfs",
|
||||
params={
|
||||
"SERVICE": "Wfs",
|
||||
"REQUEST": "Getfeature",
|
||||
"outputFormat": "application/json",
|
||||
"SRS": "EPSG:4326",
|
||||
"ak": APP_KEY,
|
||||
"sig": wfs_sig(service_code),
|
||||
"propertyName": id_field,
|
||||
"CQL_FILTER": f"INTERSECTS(the_geom,SRID=4326;POLYGON(({ring})))",
|
||||
},
|
||||
headers={"Referer": f"{ORIGIN}/pro-problem-warehouse-web/"},
|
||||
timeout=httpx.Timeout(40.0, connect=10.0),
|
||||
)
|
||||
if response.status_code != 200 or not response.text.lstrip().startswith("{"):
|
||||
raise NqiError("读取地市栅格失败")
|
||||
payload = response.json()
|
||||
features = list(payload.get("features") or [])
|
||||
matched = payload.get("numberMatched")
|
||||
total = int(matched) if isinstance(matched, int) else len(features)
|
||||
return features, total
|
||||
|
||||
async def cell_rows(self, service_code: str, grid_id: str, network: str) -> list[dict]:
|
||||
body = {
|
||||
"current": 1,
|
||||
@@ -334,6 +567,81 @@ class NqiClient:
|
||||
return _api_payload(response)
|
||||
|
||||
|
||||
async def _wait_turn(cancel_event: asyncio.Event, run_event: asyncio.Event | None) -> bool:
|
||||
"""暂停时停住。返回 False 表示任务已停止。"""
|
||||
if run_event is None:
|
||||
return not cancel_event.is_set()
|
||||
while not run_event.is_set():
|
||||
if cancel_event.is_set():
|
||||
return False
|
||||
try:
|
||||
await asyncio.wait_for(run_event.wait(), timeout=0.3)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
return not cancel_event.is_set()
|
||||
|
||||
|
||||
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 _tiles(west: float, south: float, east: float, north: float, step: float) -> list[tuple[float, float, float, float]]:
|
||||
tiles: list[tuple[float, float, float, float]] = []
|
||||
lat = south
|
||||
while lat < north - 1e-9:
|
||||
lon = west
|
||||
next_lat = min(lat + step, north)
|
||||
while lon < east - 1e-9:
|
||||
next_lon = min(lon + step, east)
|
||||
tiles.append((lon, lat, next_lon, next_lat))
|
||||
lon = next_lon
|
||||
lat = next_lat
|
||||
return tiles
|
||||
|
||||
|
||||
def _split_tile(tile: tuple[float, float, float, float]) -> list[tuple[float, float, float, float]]:
|
||||
west, south, east, north = tile
|
||||
mid_lon = (west + east) / 2
|
||||
mid_lat = (south + north) / 2
|
||||
return [
|
||||
(west, south, mid_lon, mid_lat),
|
||||
(mid_lon, south, east, mid_lat),
|
||||
(west, mid_lat, mid_lon, north),
|
||||
(mid_lon, mid_lat, east, north),
|
||||
]
|
||||
|
||||
|
||||
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 "登录未成功,请检查验证码或短信验证码"
|
||||
|
||||
|
||||
def _media_type(response: httpx.Response) -> str:
|
||||
raw = response.headers.get("content-type", "image/jpeg").split(";", 1)[0].strip()
|
||||
return raw or "image/jpeg"
|
||||
|
||||
@@ -12,6 +12,8 @@ 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_PROD = f"{ORIGIN}/pro-gis-tenant/gmcc-wyzc/prod-api"
|
||||
GIS_API = f"{ORIGIN}/pro-gis-tenant/gmcc-wyzc/api"
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""登录后定时访问门户接口,避免闲置导致凭证失效。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from app.platform.sessions import remember
|
||||
from app.shared.state import state
|
||||
|
||||
logger = logging.getLogger("nqi.auth")
|
||||
INTERVAL_SECONDS = 180
|
||||
|
||||
|
||||
async def refresh_saved_session() -> None:
|
||||
client = state.client
|
||||
if client is None or state.user is None:
|
||||
return
|
||||
refreshed = await client.touch_session()
|
||||
state.user = refreshed
|
||||
remember(refreshed, client.export_cookies())
|
||||
|
||||
|
||||
async def session_keepalive() -> None:
|
||||
while True:
|
||||
await asyncio.sleep(INTERVAL_SECONDS)
|
||||
try:
|
||||
await refresh_saved_session()
|
||||
except Exception as exc:
|
||||
logger.info("登录续期未完成: %s", exc)
|
||||
@@ -0,0 +1,116 @@
|
||||
"""本机保存的登录凭证。只存平台会话,不存密码。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
import httpx
|
||||
|
||||
from app.platform.client import NqiClient, NqiError
|
||||
from app.shared.paths import DATA_ROOT
|
||||
|
||||
STORE = DATA_ROOT / "sessions.json"
|
||||
|
||||
|
||||
def _read() -> list[dict]:
|
||||
if not STORE.is_file():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(STORE.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return []
|
||||
accounts = data.get("accounts") if isinstance(data, dict) else None
|
||||
if not isinstance(accounts, list):
|
||||
return []
|
||||
return [item for item in accounts if isinstance(item, dict) and item.get("loginId") and item.get("cookies")]
|
||||
|
||||
|
||||
def _write(accounts: list[dict]) -> None:
|
||||
STORE.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = json.dumps({"accounts": accounts}, ensure_ascii=False, indent=2)
|
||||
temporary = STORE.with_suffix(".json.tmp")
|
||||
temporary.write_text(payload, encoding="utf-8")
|
||||
temporary.replace(STORE)
|
||||
|
||||
|
||||
def remember(user: dict, cookies: list[dict]) -> None:
|
||||
login_id = str(user.get("loginId") or "").strip()
|
||||
if not login_id or not cookies:
|
||||
return
|
||||
accounts = [item for item in _read() if item.get("loginId") != login_id]
|
||||
accounts.insert(
|
||||
0,
|
||||
{
|
||||
"loginId": login_id,
|
||||
"userName": user.get("userName") or "",
|
||||
"cityName": user.get("cityName") or "",
|
||||
"orgName": user.get("orgName") or "",
|
||||
"savedAt": datetime.now().isoformat(timespec="seconds"),
|
||||
"cookies": cookies,
|
||||
},
|
||||
)
|
||||
_write(accounts)
|
||||
|
||||
|
||||
def forget(login_id: str) -> None:
|
||||
_write([item for item in _read() if item.get("loginId") != login_id])
|
||||
|
||||
|
||||
def public_view(item: dict) -> dict:
|
||||
return {
|
||||
"loginId": item.get("loginId") or "",
|
||||
"userName": item.get("userName") or "",
|
||||
"cityName": item.get("cityName") or "",
|
||||
"orgName": item.get("orgName") or "",
|
||||
}
|
||||
|
||||
|
||||
async def available_accounts() -> list[dict]:
|
||||
"""向平台确认每条凭证。失效的删掉,暂时连不上的先留着但不显示。"""
|
||||
kept: list[dict] = []
|
||||
visible: list[dict] = []
|
||||
for item in _read():
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(item.get("cookies") or [])
|
||||
user = await client.current_user()
|
||||
except NqiError:
|
||||
continue
|
||||
except (httpx.TimeoutException, httpx.RequestError):
|
||||
kept.append(item)
|
||||
continue
|
||||
else:
|
||||
item.update(
|
||||
{
|
||||
"loginId": user["loginId"] or item.get("loginId"),
|
||||
"userName": user["userName"],
|
||||
"cityName": user["cityName"],
|
||||
"orgName": user["orgName"],
|
||||
}
|
||||
)
|
||||
kept.append(item)
|
||||
visible.append(public_view(item))
|
||||
finally:
|
||||
await client.aclose()
|
||||
_write(kept)
|
||||
return visible
|
||||
|
||||
|
||||
async def resume(login_id: str) -> tuple[NqiClient, dict]:
|
||||
matched = next((item for item in _read() if item.get("loginId") == login_id), None)
|
||||
if matched is None:
|
||||
raise NqiError("这个账号的登录已失效")
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(matched.get("cookies") or [])
|
||||
user = await client.current_user()
|
||||
except NqiError:
|
||||
await client.aclose()
|
||||
forget(login_id)
|
||||
raise NqiError("这个账号的登录已失效")
|
||||
except (httpx.TimeoutException, httpx.RequestError):
|
||||
await client.aclose()
|
||||
raise NqiError("连接失败,请稍后重试")
|
||||
remember(user, client.export_cookies())
|
||||
return client, user
|
||||
@@ -7,7 +7,6 @@ dependencies = [
|
||||
"cryptography>=44",
|
||||
"fastapi>=0.115",
|
||||
"httpx>=0.28",
|
||||
"openpyxl>=3.1",
|
||||
"python-multipart>=0.0.20",
|
||||
"uvicorn>=0.34",
|
||||
]
|
||||
|
||||
@@ -31,8 +31,6 @@ def main() -> None:
|
||||
"--collect-all",
|
||||
"uvicorn",
|
||||
"--collect-all",
|
||||
"openpyxl",
|
||||
"--collect-all",
|
||||
"cryptography",
|
||||
"--collect-all",
|
||||
"certifi",
|
||||
|
||||
+437
-17
@@ -1,18 +1,23 @@
|
||||
import asyncio
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
from app.features.download.fields import columns_for
|
||||
from app.features.download.ids import parse_table, parse_upload
|
||||
from app.features.download import jobs as job_module
|
||||
from app.features.download.jobs import DownloadJob, JobManager, _pump
|
||||
from app.features.download.journal import CsvJournal
|
||||
from app.platform.constants import APP_SECRET
|
||||
from app.features.download.rows import build_rows
|
||||
from app.platform.sign import build_sign, wfs_sig
|
||||
from app.platform.client import month_end, rsa_encrypt
|
||||
from app.platform.client import NqiClient, NqiError, login_page_url, month_end, rsa_encrypt, sms_notice
|
||||
from app.platform import sessions
|
||||
from app.platform.keepalive import refresh_saved_session
|
||||
from app.shared.state import state
|
||||
|
||||
PUBLIC_KEY = (
|
||||
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+"
|
||||
@@ -38,6 +43,35 @@ def test_month_end():
|
||||
assert month_end("2026-02") == "20260228"
|
||||
|
||||
|
||||
def test_login_page_keeps_service_query():
|
||||
assert login_page_url("https://nqi.gmcc.net:20443/cas/login") == (
|
||||
"https://nqi.gmcc.net:20443/cas/login?service=https%3A%2F%2Fnqi.gmcc.net%3A20443%2Fpro-portal%2F"
|
||||
)
|
||||
kept = "https://nqi.gmcc.net:20443/cas/login?service=https%3A%2F%2Fnqi.gmcc.net%3A20443%2Fpro-portal%2F"
|
||||
assert login_page_url(kept) == kept
|
||||
|
||||
|
||||
def test_saved_login_replaces_same_account(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
|
||||
user = {"loginId": "a", "userName": "甲", "cityName": "江门", "orgName": ""}
|
||||
sessions.remember(user, [{"name": "TGC", "value": "old", "domain": "", "path": "/"}])
|
||||
sessions.remember(
|
||||
{"loginId": "b", "userName": "乙", "cityName": "广州", "orgName": ""},
|
||||
[{"name": "TGC", "value": "b", "domain": "", "path": "/"}],
|
||||
)
|
||||
sessions.remember(user, [{"name": "TGC", "value": "new", "domain": "", "path": "/"}])
|
||||
stored = sessions._read()
|
||||
assert [item["loginId"] for item in stored] == ["a", "b"]
|
||||
assert stored[0]["cookies"][0]["value"] == "new"
|
||||
sessions.forget("b")
|
||||
assert [item["loginId"] for item in sessions._read()] == ["a"]
|
||||
|
||||
|
||||
def test_sms_notice_reads_accepted_message():
|
||||
payload = {"msg": "success", "data": '{"Content":"短信发送已受理。","Code":"0000"}', "success": True}
|
||||
assert sms_notice(payload) == "短信发送已受理。"
|
||||
|
||||
|
||||
def test_rsa_block_size():
|
||||
encrypted = rsa_encrypt(PUBLIC_KEY, "demo")
|
||||
assert len(encrypted) == 172
|
||||
@@ -85,23 +119,29 @@ def test_missing_grid_still_writes_requested_id():
|
||||
assert rows[0][labels.index("小区ID")] == ""
|
||||
|
||||
|
||||
def test_parse_ids_from_header_and_duplicates():
|
||||
rows = parse_table([["20米栅格ID", "备注"], ["541927061", "a"], ["541927061", "b"], ["12", "c"], ["", ""]])
|
||||
def test_fifty_meter_column_name():
|
||||
labels = [column.label for column in columns_for("NR", ["rsrp"], "GRID50")]
|
||||
assert "50米栅格ID" in labels
|
||||
assert "20米栅格ID" not in labels
|
||||
rows, duplicates = parse_table(
|
||||
[["20米栅格ID", "备注"], ["541927061", "a"], ["541927061", "b"], [" 12 ", "c"], ["12", "d"], ["", ""]]
|
||||
)
|
||||
assert rows == ["541927061", "12"]
|
||||
assert duplicates == 2
|
||||
|
||||
|
||||
def test_parse_plain_lines_and_xlsx(tmp_path: Path):
|
||||
text = tmp_path / "ids.txt"
|
||||
text.write_text("541927061\n544536471\n", encoding="utf-8")
|
||||
assert parse_upload(text) == ["541927061", "544536471"]
|
||||
book = Workbook()
|
||||
sheet = book.active
|
||||
sheet.append(["栅格ID"])
|
||||
sheet.append([544536471])
|
||||
path = tmp_path / "ids.xlsx"
|
||||
book.save(path)
|
||||
book.close()
|
||||
assert parse_upload(path) == ["544536471"]
|
||||
def test_parse_csv_upload(tmp_path: Path):
|
||||
path = tmp_path / "ids.csv"
|
||||
path.write_bytes("20米栅格ID\n541927061\n544536471\n541927061\n".encode("utf-8-sig"))
|
||||
assert parse_upload(path) == (["541927061", "544536471"], 1)
|
||||
other = tmp_path / "ids.txt"
|
||||
other.write_text("541927061\n", encoding="utf-8")
|
||||
try:
|
||||
parse_upload(other)
|
||||
except ValueError as exc:
|
||||
assert "CSV" in str(exc)
|
||||
else:
|
||||
raise AssertionError("txt 不应被接受")
|
||||
|
||||
|
||||
def test_journal_discards_uncommitted_tail(tmp_path: Path):
|
||||
@@ -142,3 +182,383 @@ def test_journal_writes_do_not_interleave(tmp_path: Path):
|
||||
assert len(rows) == 41
|
||||
assert all(len(row) == 3 for row in rows)
|
||||
assert {row[0] for row in rows[1:]} == {"甲", "乙"}
|
||||
|
||||
|
||||
def test_grid_ids_yield_before_the_scan_finishes():
|
||||
asyncio.run(_grid_ids_yield_before_the_scan_finishes())
|
||||
|
||||
|
||||
async def _grid_ids_yield_before_the_scan_finishes():
|
||||
client = NqiClient()
|
||||
release = asyncio.Event()
|
||||
seen_tiles: list[float] = []
|
||||
|
||||
async def bounds(_self, _service_code):
|
||||
return (0.0, 0.0, 0.1, 0.05)
|
||||
|
||||
async def tile(_self, _service_code, _id_field, area):
|
||||
seen_tiles.append(area[0])
|
||||
if area[0] >= 0.01:
|
||||
await release.wait()
|
||||
grid_id = "1" if area[0] < 0.01 else "2"
|
||||
return [{"properties": {"grid20_id": grid_id}}], 1
|
||||
|
||||
client._layer_bounds = bounds.__get__(client, NqiClient)
|
||||
client._tile_features = tile.__get__(client, NqiClient)
|
||||
|
||||
async def progress(_count: int) -> None:
|
||||
return None
|
||||
|
||||
agen = client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), progress)
|
||||
try:
|
||||
first = await agen.__anext__()
|
||||
assert first == "1"
|
||||
assert not release.is_set()
|
||||
release.set()
|
||||
second = await agen.__anext__()
|
||||
assert second == "2"
|
||||
finally:
|
||||
await agen.aclose()
|
||||
await client.aclose()
|
||||
|
||||
|
||||
def test_grid_ids_skip_edges_already_seen():
|
||||
asyncio.run(_grid_ids_skip_edges_already_seen())
|
||||
|
||||
|
||||
async def _grid_ids_skip_edges_already_seen():
|
||||
client = NqiClient()
|
||||
|
||||
async def bounds(_self, _service_code):
|
||||
return (0.0, 0.0, 0.1, 0.05)
|
||||
|
||||
async def tile(_self, _service_code, _id_field, area):
|
||||
grid_id = "7" if area[0] < 0.01 else "8"
|
||||
return [{"properties": {"grid20_id": grid_id}}, {"properties": {"grid20_id": "7"}}], 2
|
||||
|
||||
client._layer_bounds = bounds.__get__(client, NqiClient)
|
||||
client._tile_features = tile.__get__(client, NqiClient)
|
||||
found: list[str] = []
|
||||
async for grid_id in client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), _noop, {"7"}):
|
||||
found.append(grid_id)
|
||||
await client.aclose()
|
||||
assert found == ["8"]
|
||||
|
||||
|
||||
async def _noop(_count: int) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def test_download_starts_before_remaining_ids_arrive(tmp_path: Path):
|
||||
asyncio.run(_download_starts_before_remaining_ids_arrive(tmp_path))
|
||||
|
||||
|
||||
async def _download_starts_before_remaining_ids_arrive(tmp_path: Path):
|
||||
started = asyncio.Event()
|
||||
order: list[str] = []
|
||||
|
||||
class Fake:
|
||||
async def grid_feature(self, _service_code, grid_id, _id_field):
|
||||
order.append(grid_id)
|
||||
if grid_id == "1":
|
||||
started.set()
|
||||
return {"grid20_id": grid_id}
|
||||
|
||||
async def cell_rows(self, _service_code, _grid_id, _network):
|
||||
return []
|
||||
|
||||
async def source():
|
||||
yield "1"
|
||||
await started.wait()
|
||||
order.append("rest")
|
||||
yield "2"
|
||||
|
||||
job = DownloadJob(
|
||||
id="a" * 32,
|
||||
directory=tmp_path,
|
||||
network="NR",
|
||||
city_code="JM",
|
||||
city_name="江门",
|
||||
month="2026-09",
|
||||
groups=["rsrp"],
|
||||
concurrency=2,
|
||||
grid_ids=["1", "2"],
|
||||
csv_path=tmp_path / "out.csv",
|
||||
created_at="",
|
||||
)
|
||||
columns = columns_for("NR", ["rsrp"])
|
||||
journal = CsvJournal(job.csv_path, tmp_path / "progress.jsonl", [column.label for column in columns])
|
||||
journal.open()
|
||||
await _pump(job, Fake(), journal, columns, "svc", source())
|
||||
journal.close()
|
||||
assert order.index("1") < order.index("rest")
|
||||
assert job.completed == 2
|
||||
assert job.status == "done"
|
||||
|
||||
|
||||
def test_touch_session_visits_portal_and_layer():
|
||||
asyncio.run(_touch_session_visits_portal_and_layer())
|
||||
|
||||
|
||||
async def _touch_session_visits_portal_and_layer():
|
||||
client = NqiClient()
|
||||
calls: list[tuple[str, str]] = []
|
||||
|
||||
class Response:
|
||||
def __init__(self, payload: dict, status_code: int = 200):
|
||||
self.status_code = status_code
|
||||
self._payload = payload
|
||||
self.headers = {"content-type": "application/json"}
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
async def get(url, headers=None, params=None, **_kwargs):
|
||||
calls.append(("GET", str(url)))
|
||||
if "roleCityMapping" in str(url):
|
||||
return Response({"code": 0, "data": []})
|
||||
if "getOnLineCount" in str(url):
|
||||
return Response({"count": 1})
|
||||
return Response({"loginId": "a", "userName": "甲", "cityName": "江门", "orgName": "江门", "roleId": "r1"})
|
||||
|
||||
async def post(url, json=None, headers=None, **_kwargs):
|
||||
calls.append(("POST", str(url)))
|
||||
return Response({})
|
||||
|
||||
client.client.get = get
|
||||
client.client.post = post
|
||||
try:
|
||||
user = await client.touch_session()
|
||||
finally:
|
||||
await client.aclose()
|
||||
assert user["loginId"] == "a"
|
||||
assert user["userName"] == "甲"
|
||||
joined = " ".join(url for _method, url in calls)
|
||||
assert "getCasUser" in joined
|
||||
assert "checkUserPasswordUpdated" in joined
|
||||
assert "getOnLineCount" in joined
|
||||
assert "roleCityMapping/cities" in joined
|
||||
|
||||
|
||||
def test_touch_session_rejects_expired_login():
|
||||
try:
|
||||
asyncio.run(_touch_session_rejects_expired_login())
|
||||
except NqiError as exc:
|
||||
assert "失效" in str(exc)
|
||||
else:
|
||||
raise AssertionError("失效登录应被拒绝")
|
||||
|
||||
|
||||
async def _touch_session_rejects_expired_login():
|
||||
client = NqiClient()
|
||||
|
||||
class Response:
|
||||
status_code = 200
|
||||
headers = {"content-type": "application/json"}
|
||||
|
||||
def json(self):
|
||||
return {"loginId": "a", "userName": "甲"}
|
||||
|
||||
class Denied:
|
||||
status_code = 401
|
||||
headers = {"content-type": "application/json"}
|
||||
|
||||
def json(self):
|
||||
return {}
|
||||
|
||||
async def get(url, headers=None, params=None, **_kwargs):
|
||||
return Response()
|
||||
|
||||
async def post(url, json=None, headers=None, **_kwargs):
|
||||
return Denied()
|
||||
|
||||
client.client.get = get
|
||||
client.client.post = post
|
||||
try:
|
||||
await client.touch_session()
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
|
||||
def test_refresh_saved_session_rewrites_cookie(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
|
||||
|
||||
class Fake:
|
||||
async def touch_session(self):
|
||||
return {"loginId": "a", "userName": "甲", "cityName": "江门", "orgName": ""}
|
||||
|
||||
def export_cookies(self):
|
||||
return [{"name": "TGC", "value": "kept", "domain": "", "path": "/"}]
|
||||
|
||||
state.client = Fake()
|
||||
state.user = {"loginId": "a", "userName": "旧", "cityName": "", "orgName": ""}
|
||||
try:
|
||||
asyncio.run(refresh_saved_session())
|
||||
assert state.user["userName"] == "甲"
|
||||
stored = sessions._read()
|
||||
finally:
|
||||
state.client = None
|
||||
state.user = None
|
||||
assert stored[0]["cookies"][0]["value"] == "kept"
|
||||
|
||||
|
||||
def test_task_folder_uses_second_timestamp(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
|
||||
|
||||
class Clock:
|
||||
@staticmethod
|
||||
def now():
|
||||
return datetime(2026, 9, 21, 12, 0, 9)
|
||||
|
||||
monkeypatch.setattr(job_module, "datetime", Clock)
|
||||
manager = JobManager()
|
||||
output = tmp_path / "save" / "栅格.csv"
|
||||
first = _make_job(manager, output)
|
||||
assert first.id == "20260921120009"
|
||||
assert first.directory == tmp_path / "jobs" / "20260921120009"
|
||||
assert first.csv_path == tmp_path / "save" / "20260921120009" / "栅格.csv"
|
||||
second = _make_job(manager, output)
|
||||
assert second.id == "20260921120009_2"
|
||||
assert second.directory != first.directory
|
||||
|
||||
|
||||
def test_only_the_task_limit_runs(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
|
||||
manager = JobManager()
|
||||
manager.max_concurrent = 1
|
||||
first = _make_job(manager, None)
|
||||
second = _make_job(manager, None)
|
||||
assert manager.place(first) == "run"
|
||||
assert manager.place(second) == "wait"
|
||||
assert second.status == "queued"
|
||||
assert second.message == "等待中"
|
||||
manager.request_stop(second)
|
||||
assert second.status == "cancelled"
|
||||
assert second.message == "已取消"
|
||||
|
||||
class Alive:
|
||||
def done(self):
|
||||
return False
|
||||
|
||||
first.task = Alive()
|
||||
manager.pause(first)
|
||||
assert first.status == "paused"
|
||||
assert manager.running_count() == 0
|
||||
third = _make_job(manager, None)
|
||||
assert manager.place(third) == "run"
|
||||
assert manager.place(first) == "wait"
|
||||
manager.jobs.clear()
|
||||
manager.hydrate()
|
||||
assert first.id in manager.jobs
|
||||
assert manager.jobs[first.id].status == "queued"
|
||||
assert third.id not in manager.jobs
|
||||
|
||||
|
||||
def test_reader_stays_idle_while_paused():
|
||||
asyncio.run(_reader_stays_idle_while_paused())
|
||||
|
||||
|
||||
async def _reader_stays_idle_while_paused():
|
||||
client = NqiClient()
|
||||
run = asyncio.Event()
|
||||
reached = asyncio.Event()
|
||||
started: list[float] = []
|
||||
|
||||
async def bounds(_self, _service_code):
|
||||
reached.set()
|
||||
return (0.0, 0.0, 0.05, 0.05)
|
||||
|
||||
async def tile(_self, _service_code, _id_field, area):
|
||||
started.append(area[0])
|
||||
return [{"properties": {"grid20_id": "5"}}], 1
|
||||
|
||||
client._layer_bounds = bounds.__get__(client, NqiClient)
|
||||
client._tile_features = tile.__get__(client, NqiClient)
|
||||
agen = client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), _noop, None, run)
|
||||
nxt = asyncio.create_task(agen.__anext__())
|
||||
try:
|
||||
await asyncio.wait_for(reached.wait(), 1)
|
||||
await asyncio.sleep(0.05)
|
||||
assert started == []
|
||||
assert not nxt.done()
|
||||
run.set()
|
||||
assert await nxt == "5"
|
||||
assert started
|
||||
finally:
|
||||
run.set()
|
||||
nxt.cancel()
|
||||
await agen.aclose()
|
||||
await client.aclose()
|
||||
|
||||
|
||||
def test_pause_holds_the_next_grid(tmp_path: Path):
|
||||
asyncio.run(_pause_holds_the_next_grid(tmp_path))
|
||||
|
||||
|
||||
async def _pause_holds_the_next_grid(tmp_path: Path):
|
||||
seen: list[str] = []
|
||||
job = DownloadJob(
|
||||
id="20260921120009",
|
||||
directory=tmp_path,
|
||||
network="NR",
|
||||
city_code="JM",
|
||||
city_name="江门",
|
||||
month="2026-09",
|
||||
groups=["rsrp"],
|
||||
concurrency=1,
|
||||
grid_ids=["1", "2"],
|
||||
csv_path=tmp_path / "out.csv",
|
||||
created_at="",
|
||||
)
|
||||
|
||||
class Fake:
|
||||
async def grid_feature(self, _service_code, grid_id, _id_field):
|
||||
seen.append(grid_id)
|
||||
if grid_id == "1":
|
||||
job.run_event.clear()
|
||||
job.status = "paused"
|
||||
return {"grid20_id": grid_id}
|
||||
|
||||
async def cell_rows(self, _service_code, _grid_id, _network):
|
||||
return []
|
||||
|
||||
async def source():
|
||||
yield "1"
|
||||
yield "2"
|
||||
|
||||
async def watch():
|
||||
try:
|
||||
for _ in range(50):
|
||||
if seen == ["1"]:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
else:
|
||||
raise AssertionError("下载没有在第一格停下")
|
||||
await asyncio.sleep(0.15)
|
||||
assert seen == ["1"]
|
||||
finally:
|
||||
job.run_event.set()
|
||||
|
||||
columns = columns_for("NR", ["rsrp"])
|
||||
journal = CsvJournal(job.csv_path, tmp_path / "progress.jsonl", [column.label for column in columns])
|
||||
journal.open()
|
||||
await asyncio.gather(_pump(job, Fake(), journal, columns, "svc", source()), watch())
|
||||
journal.close()
|
||||
assert seen == ["1", "2"]
|
||||
assert job.status == "done"
|
||||
|
||||
|
||||
def _make_job(manager: JobManager, output: Path | None) -> DownloadJob:
|
||||
return manager.create(
|
||||
network="NR",
|
||||
city_code="JM",
|
||||
city_name="江门",
|
||||
month="2026-09",
|
||||
groups=["rsrp"],
|
||||
concurrency=4,
|
||||
grid_ids=["1"],
|
||||
csv_path=output,
|
||||
grid_size="GRID20",
|
||||
whole_city=output is None,
|
||||
)
|
||||
|
||||
|
||||
Generated
-23
@@ -236,15 +236,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ca/1d/1271f287ff7170ddafc2aad36260c4eec20ccd2fea70f38455e9d56d427b/cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452", size = 3805376, upload-time = "2026-09-30T15:29:58.729Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "et-xmlfile"
|
||||
version = "2.0.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d3/38/af70d7ab1ae9d4da450eeec1fa3918940a5fafb9055e934af8d6eb0c2313/et_xmlfile-2.0.0.tar.gz", hash = "sha256:dab3f4764309081ce75662649be815c4c9081e88f0837825f90fd28317d4da54", size = 17234, upload-time = "2024-10-25T17:25:40.039Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/8b/5fe2cc11fee489817272089c4203e679c63b570a5aaeb18d852ae3cbba6a/et_xmlfile-2.0.0-py3-none-any.whl", hash = "sha256:7a91720bc756843502c3b7504c77b8fe44217c85c537d85037f0f536151b2caa", size = 18059, upload-time = "2024-10-25T17:25:39.051Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastapi"
|
||||
version = "0.162.0"
|
||||
@@ -337,7 +328,6 @@ dependencies = [
|
||||
{ name = "cryptography" },
|
||||
{ name = "fastapi" },
|
||||
{ name = "httpx" },
|
||||
{ name = "openpyxl" },
|
||||
{ name = "python-multipart" },
|
||||
{ name = "uvicorn" },
|
||||
]
|
||||
@@ -353,7 +343,6 @@ requires-dist = [
|
||||
{ name = "cryptography", specifier = ">=44" },
|
||||
{ name = "fastapi", specifier = ">=0.115" },
|
||||
{ name = "httpx", specifier = ">=0.28" },
|
||||
{ name = "openpyxl", specifier = ">=3.1" },
|
||||
{ name = "python-multipart", specifier = ">=0.0.20" },
|
||||
{ name = "uvicorn", specifier = ">=0.34" },
|
||||
]
|
||||
@@ -364,18 +353,6 @@ dev = [
|
||||
{ name = "pytest", specifier = ">=8.3" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openpyxl"
|
||||
version = "3.1.5"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "et-xmlfile" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3d/f9/88d94a75de065ea32619465d2f77b29a0469500e99012523b91cc4141cd1/openpyxl-3.1.5.tar.gz", hash = "sha256:cf0e3cf56142039133628b5acffe8ef0c12bc902d2aadd3e0fe5878dc08d1050", size = 186464, upload-time = "2024-06-28T14:03:44.161Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c0/da/977ded879c29cbd04de313843e76868e6e13408a94ed6b987245dc7c8506/openpyxl-3.1.5-py2.py3-none-any.whl", hash = "sha256:5282c12b107bffeef825f4617dc029afaf41d0ea60823bbb665ef3079dc79de2", size = 250910, upload-time = "2024-06-28T14:03:41.161Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "opentelemetry-api"
|
||||
version = "1.45.1"
|
||||
|
||||
@@ -27,6 +27,12 @@ fn backend_port() -> u16 {
|
||||
PORT.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn write_sample_csv(path: String) -> Result<(), String> {
|
||||
let content = "\u{FEFF}20米栅格ID\r\n541927061\r\n544536471\r\n";
|
||||
std::fs::write(path, content).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn repo_root() -> Option<PathBuf> {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
@@ -115,6 +121,12 @@ fn start_backend(app: &tauri::App) {
|
||||
.current_dir(&plan.cwd)
|
||||
.env("NQI_PORT", port.to_string())
|
||||
.env("NQI_DATA_DIR", &plan.data_dir)
|
||||
.env_remove("HTTP_PROXY")
|
||||
.env_remove("HTTPS_PROXY")
|
||||
.env_remove("ALL_PROXY")
|
||||
.env_remove("http_proxy")
|
||||
.env_remove("https_proxy")
|
||||
.env_remove("all_proxy")
|
||||
.stdin(Stdio::null());
|
||||
if let Ok(log) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
@@ -170,7 +182,7 @@ pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.invoke_handler(tauri::generate_handler![backend_port])
|
||||
.invoke_handler(tauri::generate_handler![backend_port, write_sample_csv])
|
||||
.setup(|app| {
|
||||
start_backend(app);
|
||||
Ok(())
|
||||
|
||||
+6
-4
@@ -10,10 +10,12 @@ const user = ref<UserInfo | null>(null);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<n-config-provider :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="themeOverrides">
|
||||
<n-message-provider>
|
||||
<LoginView v-if="!user" @success="user = $event" />
|
||||
<Shell v-else :user="user" @logout="user = null" />
|
||||
<n-config-provider class="app-root" :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="themeOverrides">
|
||||
<n-message-provider class="app-root">
|
||||
<div class="app-root">
|
||||
<LoginView v-if="!user" @success="user = $event" />
|
||||
<Shell v-else :user="user" @logout="user = null" />
|
||||
</div>
|
||||
</n-message-provider>
|
||||
</n-config-provider>
|
||||
</template>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NIcon, NInput, NSpin, NTooltip } from "naive-ui";
|
||||
import { onMounted, onUnmounted, ref } from "vue";
|
||||
import { NAlert, NButton, NIcon, NInput, NModal, NSelect, NSpin, NTooltip } from "naive-ui";
|
||||
import { HelpCircleOutline, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
|
||||
import { ApiError } from "../../shared/http";
|
||||
import { loadCaptcha, login, refreshCaptcha, sendSms, type UserInfo } from "./api";
|
||||
import { loadCaptcha, loadSaved, login, refreshCaptcha, resumeSaved, sendSms, type UserInfo } from "./api";
|
||||
import { isDark, toggleTheme } from "../../shared/theme";
|
||||
|
||||
const emit = defineEmits<{ success: [user: UserInfo] }>();
|
||||
@@ -21,13 +21,30 @@ const sending = ref(false);
|
||||
const submitting = ref(false);
|
||||
const errorText = ref("");
|
||||
const smsHint = ref("");
|
||||
const saved = ref<UserInfo[]>([]);
|
||||
const savedId = ref<string | null>(null);
|
||||
const resuming = ref(false);
|
||||
const countdown = ref(0);
|
||||
let timer = 0;
|
||||
|
||||
onMounted(() => {
|
||||
void connect();
|
||||
void refreshSaved();
|
||||
});
|
||||
|
||||
async function refreshSaved() {
|
||||
try {
|
||||
const result = await loadSaved();
|
||||
saved.value = result.accounts;
|
||||
if (!result.accounts.some((item) => item.loginId === savedId.value)) {
|
||||
savedId.value = result.accounts[0]?.loginId ?? null;
|
||||
}
|
||||
} catch {
|
||||
saved.value = [];
|
||||
savedId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function connect() {
|
||||
offline.value = "";
|
||||
ready.value = false;
|
||||
@@ -50,8 +67,8 @@ async function connect() {
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadCaptcha() {
|
||||
errorText.value = "";
|
||||
async function reloadCaptcha(keepError = false) {
|
||||
if (!keepError) errorText.value = "";
|
||||
try {
|
||||
if (!sessionId.value) {
|
||||
await connect();
|
||||
@@ -66,26 +83,59 @@ async function reloadCaptcha() {
|
||||
}
|
||||
}
|
||||
|
||||
function stopCountdown() {
|
||||
window.clearInterval(timer);
|
||||
countdown.value = 0;
|
||||
}
|
||||
|
||||
function startCountdown() {
|
||||
stopCountdown();
|
||||
countdown.value = 60;
|
||||
timer = window.setInterval(() => {
|
||||
countdown.value -= 1;
|
||||
if (countdown.value <= 0) stopCountdown();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function savedLabel(item: UserInfo) {
|
||||
const name = item.userName || item.loginId;
|
||||
return item.cityName ? `${name} · ${item.cityName}` : name;
|
||||
}
|
||||
|
||||
async function useSaved() {
|
||||
if (!savedId.value) return;
|
||||
resuming.value = true;
|
||||
errorText.value = "";
|
||||
try {
|
||||
const result = await resumeSaved(savedId.value);
|
||||
if (result.user) emit("success", result.user);
|
||||
} catch (error) {
|
||||
errorText.value = error instanceof ApiError ? error.message : "登录失败";
|
||||
await refreshSaved();
|
||||
} finally {
|
||||
resuming.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function requestSms() {
|
||||
if (!sessionId.value || countdown.value > 0) return;
|
||||
if (!sessionId.value || countdown.value > 0 || sending.value) return;
|
||||
sending.value = true;
|
||||
errorText.value = "";
|
||||
smsHint.value = "";
|
||||
startCountdown();
|
||||
try {
|
||||
const result = await sendSms(sessionId.value);
|
||||
smsHint.value = result.message || "短信已发送";
|
||||
countdown.value = 60;
|
||||
timer = window.setInterval(() => {
|
||||
countdown.value -= 1;
|
||||
if (countdown.value <= 0) window.clearInterval(timer);
|
||||
}, 1000);
|
||||
smsHint.value = result.message || "短信发送已受理";
|
||||
} catch (error) {
|
||||
stopCountdown();
|
||||
errorText.value = error instanceof ApiError ? error.message : "短信发送失败";
|
||||
} finally {
|
||||
sending.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
async function submit(smsCodeText = "") {
|
||||
if (smsRequired.value && !smsCodeText) return;
|
||||
errorText.value = "";
|
||||
submitting.value = true;
|
||||
try {
|
||||
@@ -94,22 +144,28 @@ async function submit() {
|
||||
username: username.value.trim(),
|
||||
password: password.value,
|
||||
captcha: captcha.value.trim(),
|
||||
smsCode: smsCode.value.trim(),
|
||||
smsCode: smsCodeText,
|
||||
});
|
||||
if (result.status === "sms_required") {
|
||||
smsRequired.value = true;
|
||||
smsHint.value = result.message || "请获取并填写短信验证码";
|
||||
smsCode.value = "";
|
||||
smsHint.value = "";
|
||||
return;
|
||||
}
|
||||
if (result.user) emit("success", result.user);
|
||||
if (result.user) {
|
||||
smsRequired.value = false;
|
||||
stopCountdown();
|
||||
emit("success", result.user);
|
||||
}
|
||||
} catch (error) {
|
||||
errorText.value = error instanceof ApiError ? error.message : "登录失败";
|
||||
smsRequired.value = false;
|
||||
await reloadCaptcha();
|
||||
if (!smsRequired.value) await reloadCaptcha(true);
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onUnmounted(stopCountdown);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -133,8 +189,19 @@ async function submit() {
|
||||
<n-spin :show="!ready && !offline">
|
||||
<n-alert v-if="!ready" type="warning" style="margin-bottom: 12px">连接失败,正在重试。</n-alert>
|
||||
<n-alert v-else-if="offline" type="warning" style="margin-bottom: 12px">{{ offline }}</n-alert>
|
||||
<n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
|
||||
<form @submit.prevent="submit">
|
||||
<n-alert v-if="errorText && !smsRequired" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
|
||||
<form @submit.prevent="submit()">
|
||||
<div v-if="saved.length" class="form-row">
|
||||
<label for="saved">已登录</label>
|
||||
<div class="captcha-line">
|
||||
<n-select
|
||||
id="saved"
|
||||
v-model:value="savedId"
|
||||
:options="saved.map((item) => ({ label: savedLabel(item), value: item.loginId }))"
|
||||
/>
|
||||
<n-button type="primary" secondary :loading="resuming" :disabled="!savedId" @click="useSaved">进入</n-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="username">账号</label>
|
||||
<n-input id="username" v-model:value="username" placeholder="账号" autocomplete="username" />
|
||||
@@ -158,21 +225,22 @@ async function submit() {
|
||||
<img v-if="captchaUrl" :src="captchaUrl" alt="验证码" title="点击刷新" @click="reloadCaptcha" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="smsRequired" class="form-row">
|
||||
<label for="sms">短信</label>
|
||||
<div class="captcha-line">
|
||||
<n-input id="sms" v-model:value="smsCode" placeholder="短信验证码" />
|
||||
<n-button :disabled="sending || countdown > 0" @click="requestSms">
|
||||
{{ countdown > 0 ? `${countdown}s` : "获取短信" }}
|
||||
</n-button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="smsHint" class="file-name" style="margin: 0 0 8px 96px">{{ smsHint }}</p>
|
||||
<div class="gate-actions">
|
||||
<n-button type="primary" attr-type="submit" :loading="submitting" :disabled="!ready">登录</n-button>
|
||||
<n-button type="primary" attr-type="submit" :loading="submitting && !smsRequired" :disabled="!ready">登录</n-button>
|
||||
</div>
|
||||
</form>
|
||||
</n-spin>
|
||||
</section>
|
||||
<n-modal v-model:show="smsRequired" :mask-closable="false" :closable="false" preset="card" title="短信认证" style="width: 420px">
|
||||
<n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
|
||||
<n-input v-model:value="smsCode" placeholder="输入短信验证码" @keyup.enter="submit(smsCode.trim())" />
|
||||
<p v-if="smsHint" class="file-name" style="margin: 8px 0 0">{{ smsHint }}</p>
|
||||
<div class="sms-actions">
|
||||
<n-button :disabled="sending || countdown > 0" @click="requestSms">
|
||||
{{ countdown > 0 ? `重新发送(${countdown})` : "发送验证码" }}
|
||||
</n-button>
|
||||
<n-button type="primary" :loading="submitting" :disabled="!smsCode.trim()" @click="submit(smsCode.trim())">提交</n-button>
|
||||
</div>
|
||||
</n-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -38,6 +38,17 @@ export function login(body: {
|
||||
});
|
||||
}
|
||||
|
||||
export function loadSaved() {
|
||||
return api<{ accounts: UserInfo[] }>("/api/auth/saved");
|
||||
}
|
||||
|
||||
export function resumeSaved(loginId: string) {
|
||||
return api<{ status: string; user?: UserInfo }>("/api/auth/resume", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ loginId }),
|
||||
});
|
||||
}
|
||||
|
||||
export function logout() {
|
||||
return api<{ ok: boolean }>("/api/auth/logout", { method: "POST" });
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import { NButton, NEmpty, NIcon, NProgress, NTag, useMessage } from "naive-ui";
|
||||
import { FolderOpenOutline, PlayOutline, StopCircleOutline } from "@vicons/ionicons5";
|
||||
import { NButton, NEmpty, NIcon, NInputNumber, NProgress, NTag, NTooltip, useMessage } from "naive-ui";
|
||||
import { FolderOpenOutline, HelpCircleOutline, PauseOutline, PlayOutline, StopCircleOutline } from "@vicons/ionicons5";
|
||||
import { ApiError, openLocal } from "../../shared/http";
|
||||
import { cancelJob, loadJobs, resumeJob, type DownloadJob } from "./api";
|
||||
import { cancelJob, loadDownloadSettings, loadJobs, pauseJob, resumeJob, saveDownloadSettings, type DownloadJob } from "./api";
|
||||
|
||||
const props = defineProps<{ focusId: string }>();
|
||||
const message = useMessage();
|
||||
const jobs = ref<DownloadJob[]>([]);
|
||||
const maxJobs = ref(2);
|
||||
const tab = ref<"active" | "done">("active");
|
||||
let timer = 0;
|
||||
|
||||
@@ -18,6 +19,7 @@ const visible = computed(() => (tab.value === "active" ? activeJobs.value : done
|
||||
const statusText: Record<string, string> = {
|
||||
queued: "等待中",
|
||||
running: "下载中",
|
||||
paused: "已暂停",
|
||||
cancelled: "已停止",
|
||||
error: "出错",
|
||||
done_with_errors: "部分失败",
|
||||
@@ -26,6 +28,11 @@ const statusText: Record<string, string> = {
|
||||
|
||||
onMounted(() => {
|
||||
void refresh();
|
||||
void loadDownloadSettings()
|
||||
.then((result) => {
|
||||
maxJobs.value = result.maxConcurrentJobs;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
timer = window.setInterval(() => void refresh(), 1000);
|
||||
});
|
||||
|
||||
@@ -40,11 +47,48 @@ async function refresh() {
|
||||
}
|
||||
}
|
||||
|
||||
function statusLabel(job: DownloadJob) {
|
||||
if (job.status === "cancelled" && (job.message === "已取消" || job.message === "已中断")) return job.message;
|
||||
return statusText[job.status] || job.status;
|
||||
}
|
||||
|
||||
function scanning(job: DownloadJob) {
|
||||
return Boolean(job.wholeCity) && job.listingDone === false;
|
||||
}
|
||||
|
||||
function percent(job: DownloadJob) {
|
||||
if (!job.total) return 0;
|
||||
if (scanning(job) || !job.total) return 0;
|
||||
return Math.min(100, Math.round((job.completed / job.total) * 100));
|
||||
}
|
||||
|
||||
function countText(job: DownloadJob) {
|
||||
const written = `已写入 ${job.writtenRows} 行`;
|
||||
const progress = scanning(job)
|
||||
? `已完成 ${job.completed} · 已读取 ${job.discovered || 0} 个栅格`
|
||||
: `${job.completed}/${job.total} 个栅格`;
|
||||
return `${job.id} · ${progress} · ${written}`;
|
||||
}
|
||||
|
||||
async function saveLimit(value: number | null) {
|
||||
if (!value) return;
|
||||
try {
|
||||
const result = await saveDownloadSettings(value);
|
||||
maxJobs.value = result.maxConcurrentJobs;
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
message.error(error instanceof ApiError ? error.message : "同时任务数保存失败");
|
||||
}
|
||||
}
|
||||
|
||||
async function pause(job: DownloadJob) {
|
||||
try {
|
||||
await pauseJob(job.id);
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
message.error(error instanceof ApiError ? error.message : "暂停失败");
|
||||
}
|
||||
}
|
||||
|
||||
async function stop(job: DownloadJob) {
|
||||
try {
|
||||
await cancelJob(job.id);
|
||||
@@ -81,12 +125,29 @@ async function openDir(job: DownloadJob) {
|
||||
<section class="page">
|
||||
<header class="page-head">
|
||||
<div>
|
||||
<h2>下载管理</h2>
|
||||
<h2>下载管理</h2>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<span class="limit-label">同时任务</span>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
|
||||
</template>
|
||||
同时进行的下载任务数。每个任务仍按自己的并发数下载。
|
||||
</n-tooltip>
|
||||
<n-input-number
|
||||
class="limit-control"
|
||||
:value="maxJobs"
|
||||
:min="1"
|
||||
:max="8"
|
||||
size="small"
|
||||
@update:value="saveLimit"
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
<div class="tabs">
|
||||
<button class="tab" :class="{ on: tab === 'active' }" type="button" @click="tab = 'active'">
|
||||
正在下载<em>{{ activeJobs.length }}</em>
|
||||
未完成<em>{{ activeJobs.length }}</em>
|
||||
</button>
|
||||
<button class="tab" :class="{ on: tab === 'done' }" type="button" @click="tab = 'done'">
|
||||
已完成<em>{{ doneJobs.length }}</em>
|
||||
@@ -102,15 +163,34 @@ async function openDir(job: DownloadJob) {
|
||||
<div class="task-top">
|
||||
<div>
|
||||
<h3>{{ job.name }}</h3>
|
||||
<div class="sub">{{ job.completed }}/{{ job.total }} 个栅格 · 已写入 {{ job.writtenRows }} 行</div>
|
||||
<div class="sub">{{ countText(job) }}</div>
|
||||
</div>
|
||||
<div class="task-actions">
|
||||
<n-tag size="small" :type="job.status === 'running' ? 'info' : job.status === 'done' ? 'success' : 'warning'">
|
||||
{{ statusText[job.status] || job.status }}
|
||||
<n-tag size="small" :type="job.status === 'running' ? 'info' : job.status === 'done' ? 'success' : job.status === 'paused' ? 'warning' : 'default'">
|
||||
{{ statusLabel(job) }}
|
||||
</n-tag>
|
||||
<n-button v-if="job.status === 'running' || job.status === 'queued'" size="small" @click="stop(job)">
|
||||
<template #icon><n-icon><StopCircleOutline /></n-icon></template>
|
||||
停止
|
||||
<template v-if="job.status === 'running'">
|
||||
<n-button v-if="job.message !== '正在停止'" size="small" @click="pause(job)">
|
||||
<template #icon><n-icon><PauseOutline /></n-icon></template>
|
||||
暂停
|
||||
</n-button>
|
||||
<n-button size="small" @click="stop(job)">
|
||||
<template #icon><n-icon><StopCircleOutline /></n-icon></template>
|
||||
停止
|
||||
</n-button>
|
||||
</template>
|
||||
<template v-else-if="job.status === 'paused'">
|
||||
<n-button size="small" type="primary" secondary @click="resume(job)">
|
||||
<template #icon><n-icon><PlayOutline /></n-icon></template>
|
||||
继续
|
||||
</n-button>
|
||||
<n-button size="small" @click="stop(job)">
|
||||
<template #icon><n-icon><StopCircleOutline /></n-icon></template>
|
||||
停止
|
||||
</n-button>
|
||||
</template>
|
||||
<n-button v-else-if="job.status === 'queued'" size="small" @click="stop(job)">
|
||||
取消
|
||||
</n-button>
|
||||
<n-button v-else-if="job.status !== 'done'" size="small" type="primary" secondary @click="resume(job)">
|
||||
<template #icon><n-icon><PlayOutline /></n-icon></template>
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
NButton,
|
||||
NCheckbox,
|
||||
NCheckboxGroup,
|
||||
NDatePicker,
|
||||
NIcon,
|
||||
NInput,
|
||||
NInputNumber,
|
||||
@@ -21,13 +22,18 @@ const message = useMessage();
|
||||
const meta = ref<Meta | null>(null);
|
||||
const network = ref("NR");
|
||||
const cityCode = ref("JM");
|
||||
const month = ref(previousMonth());
|
||||
const month = ref<string | null>(previousMonth());
|
||||
const concurrency = ref(8);
|
||||
const groups = ref<string[]>([]);
|
||||
const outputDir = ref("");
|
||||
const file = ref<File | null>(null);
|
||||
const submitting = ref(false);
|
||||
|
||||
const gridSize = ref("GRID20");
|
||||
const sizeOptions = [
|
||||
{ label: "20米", value: "GRID20" },
|
||||
{ label: "50米", value: "GRID50" },
|
||||
];
|
||||
const networkOptions = [
|
||||
{ label: "5G", value: "NR" },
|
||||
{ label: "4G", value: "LTE" },
|
||||
@@ -52,12 +58,46 @@ onMounted(async () => {
|
||||
watch(network, syncGroups);
|
||||
|
||||
function syncGroups() {
|
||||
groups.value = (meta.value?.groups[network.value] || []).map((item) => item.id);
|
||||
const items = meta.value?.groups[network.value] || [];
|
||||
groups.value = items.some((item) => item.id === "rsrp") ? ["rsrp"] : [];
|
||||
}
|
||||
|
||||
function onFile(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
file.value = input.files?.[0] ?? null;
|
||||
const selected = input.files?.[0] ?? null;
|
||||
if (selected && !selected.name.toLowerCase().endsWith(".csv")) {
|
||||
message.warning("区域表只支持 CSV");
|
||||
input.value = "";
|
||||
file.value = null;
|
||||
return;
|
||||
}
|
||||
file.value = selected;
|
||||
}
|
||||
|
||||
async function downloadSample() {
|
||||
const content = "\uFEFF20米栅格ID\r\n541927061\r\n544536471\r\n";
|
||||
if (!("__TAURI_INTERNALS__" in window)) {
|
||||
const blob = new Blob([content], { type: "text/csv;charset=utf-8" });
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = "区域表示例.csv";
|
||||
link.click();
|
||||
URL.revokeObjectURL(link.href);
|
||||
return;
|
||||
}
|
||||
const { save } = await import("@tauri-apps/plugin-dialog");
|
||||
const selected = await save({
|
||||
defaultPath: "区域表示例.csv",
|
||||
filters: [{ name: "CSV", extensions: ["csv"] }],
|
||||
});
|
||||
if (!selected) return;
|
||||
try {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
await invoke("write_sample_csv", { path: selected });
|
||||
message.success("例程已保存");
|
||||
} catch {
|
||||
message.error("例程保存失败");
|
||||
}
|
||||
}
|
||||
|
||||
async function pickDir() {
|
||||
@@ -66,16 +106,17 @@ async function pickDir() {
|
||||
}
|
||||
|
||||
async function start() {
|
||||
if (!file.value) {
|
||||
message.warning("请先选择栅格 ID 表");
|
||||
if (file.value && !file.value.name.toLowerCase().endsWith(".csv")) {
|
||||
message.warning("区域表只支持 CSV");
|
||||
return;
|
||||
}
|
||||
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month.value)) {
|
||||
message.warning("月份格式应为 YYYY-MM");
|
||||
if (!month.value || !/^\d{4}-(0[1-9]|1[0-2])$/.test(month.value)) {
|
||||
message.warning("请选择月份");
|
||||
return;
|
||||
}
|
||||
const form = new FormData();
|
||||
form.append("file", file.value);
|
||||
form.append("grid_size", gridSize.value);
|
||||
if (file.value) form.append("file", file.value);
|
||||
form.append("network", network.value);
|
||||
form.append("city_code", cityCode.value);
|
||||
form.append("month", month.value);
|
||||
@@ -85,7 +126,10 @@ async function start() {
|
||||
submitting.value = true;
|
||||
try {
|
||||
const job = await createJob(form);
|
||||
message.success("已开始下载");
|
||||
const removed = job.duplicateCount || 0;
|
||||
if (job.status === "queued") message.success("已加入等待");
|
||||
else if (!file.value) message.success("已开始下载整个地市");
|
||||
else message.success(removed ? `已开始下载,去掉 ${removed} 个重复栅格` : "已开始下载");
|
||||
emit("started", job.id);
|
||||
} catch (error) {
|
||||
message.error(error instanceof ApiError ? error.message : "创建下载失败");
|
||||
@@ -97,16 +141,20 @@ async function start() {
|
||||
|
||||
<template>
|
||||
<section class="page">
|
||||
<div class="page-scroll">
|
||||
<header class="page-head">
|
||||
<div>
|
||||
<h2>栅格下载</h2>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<n-button type="primary" :loading="submitting" @click="start">开始下载</n-button>
|
||||
</div>
|
||||
</header>
|
||||
<header class="page-head">
|
||||
<div>
|
||||
<h2>栅格下载</h2>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<n-button type="primary" :loading="submitting" @click="start">开始下载</n-button>
|
||||
</div>
|
||||
</header>
|
||||
<div class="page-body">
|
||||
<div class="panel">
|
||||
<div class="form-row">
|
||||
<label>栅格</label>
|
||||
<n-select v-model:value="gridSize" :options="sizeOptions" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>网络</label>
|
||||
<n-select v-model:value="network" :options="networkOptions" />
|
||||
@@ -125,10 +173,10 @@ async function start() {
|
||||
<template #trigger>
|
||||
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
|
||||
</template>
|
||||
例如 2026-09。
|
||||
选择要下载的月份。
|
||||
</n-tooltip>
|
||||
</label>
|
||||
<n-input v-model:value="month" placeholder="YYYY-MM" />
|
||||
<n-date-picker v-model:formatted-value="month" type="month" value-format="yyyy-MM" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>
|
||||
@@ -142,7 +190,7 @@ async function start() {
|
||||
</label>
|
||||
<n-input-number v-model:value="concurrency" :min="1" :max="32" />
|
||||
</div>
|
||||
<div class="form-row" style="align-items: start">
|
||||
<div class="form-row form-top">
|
||||
<label>
|
||||
项目
|
||||
<n-tooltip>
|
||||
@@ -152,8 +200,8 @@ async function start() {
|
||||
选择要导出的指标。
|
||||
</n-tooltip>
|
||||
</label>
|
||||
<n-checkbox-group v-model:value="groups">
|
||||
<div v-for="item in meta?.groups[network] || []" :key="item.id" style="margin-bottom: 6px">
|
||||
<n-checkbox-group v-model:value="groups" class="checks">
|
||||
<div v-for="item in meta?.groups[network] || []" :key="item.id" class="check-line">
|
||||
<n-checkbox :value="item.id">{{ item.label }}</n-checkbox>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
@@ -171,15 +219,16 @@ async function start() {
|
||||
<template #trigger>
|
||||
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
|
||||
</template>
|
||||
支持 CSV、TXT、XLSX。
|
||||
不选文件则边读取边下载该地市的全部栅格,同时下载的数量由并发决定。选择文件时只支持 CSV。
|
||||
</n-tooltip>
|
||||
</label>
|
||||
<div class="captcha-line">
|
||||
<label class="n-button n-button--default-type" style="padding: 0 12px; line-height: 32px; border: 1px solid #d5e0ea; border-radius: 6px; cursor: pointer">
|
||||
<n-button tag="label">
|
||||
选择文件
|
||||
<input type="file" accept=".csv,.txt,.xlsx" hidden @change="onFile" />
|
||||
</label>
|
||||
<span class="file-name">{{ file?.name || "尚未选择" }}</span>
|
||||
<input type="file" accept=".csv,text/csv" hidden @change="onFile" />
|
||||
</n-button>
|
||||
<n-button quaternary @click="downloadSample">下载例程</n-button>
|
||||
<span class="file-name">{{ file?.name || "不选则下载整个地市" }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
|
||||
@@ -21,10 +21,14 @@ export interface DownloadJob {
|
||||
network: string;
|
||||
cityName: string;
|
||||
month: string;
|
||||
wholeCity?: boolean;
|
||||
listingDone?: boolean;
|
||||
discovered?: number;
|
||||
total: number;
|
||||
completed: number;
|
||||
failed: number;
|
||||
writtenRows: number;
|
||||
duplicateCount?: number;
|
||||
csvPath: string;
|
||||
failures: { id: string; message: string }[];
|
||||
createdAt: string;
|
||||
@@ -49,3 +53,18 @@ export function cancelJob(id: string) {
|
||||
export function resumeJob(id: string) {
|
||||
return api<DownloadJob>(`/api/download/jobs/${id}/resume`, { method: "POST" });
|
||||
}
|
||||
|
||||
export function pauseJob(id: string) {
|
||||
return api<DownloadJob>(`/api/download/jobs/${id}/pause`, { method: "POST" });
|
||||
}
|
||||
|
||||
export function loadDownloadSettings() {
|
||||
return api<{ maxConcurrentJobs: number }>("/api/download/settings");
|
||||
}
|
||||
|
||||
export function saveDownloadSettings(maxConcurrentJobs: number) {
|
||||
return api<{ maxConcurrentJobs: number }>("/api/download/settings", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ maxConcurrentJobs }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { NButton, NIcon, NLayoutSider, NMenu } from "naive-ui";
|
||||
import { LogOutOutline, MoonOutline, PersonOutline, SunnyOutline } from "@vicons/ionicons5";
|
||||
import { logout, type UserInfo } from "../features/auth/api";
|
||||
import { isDark, toggleTheme } from "../shared/theme";
|
||||
import { navGroups, type PageKey } from "./navigation";
|
||||
import { navOptions, type PageKey } from "./navigation";
|
||||
import GridDownloadView from "../features/download/GridDownloadView.vue";
|
||||
import DownloadManagerView from "../features/download/DownloadManagerView.vue";
|
||||
|
||||
@@ -12,6 +12,7 @@ const props = defineProps<{ user: UserInfo }>();
|
||||
const emit = defineEmits<{ logout: [] }>();
|
||||
|
||||
const page = ref<PageKey>("grid");
|
||||
const expanded = ref<string[]>([]);
|
||||
const focusId = ref("");
|
||||
|
||||
function onMenu(key: string) {
|
||||
@@ -36,8 +37,8 @@ async function signOut() {
|
||||
<div class="shell">
|
||||
<aside class="sider">
|
||||
<div class="sider-title">NqiTools</div>
|
||||
<n-layout-sider :native-scrollbar="false" :width="220" style="background: transparent; flex: 1">
|
||||
<n-menu :value="page" :options="navGroups" @update:value="onMenu" />
|
||||
<n-layout-sider :native-scrollbar="false" :width="220" style="background: transparent; flex: 1; min-height: 0">
|
||||
<n-menu v-model:expanded-keys="expanded" :value="page" :options="navOptions" @update:value="onMenu" />
|
||||
</n-layout-sider>
|
||||
<div class="sider-user">
|
||||
<n-icon :size="18"><PersonOutline /></n-icon>
|
||||
|
||||
@@ -9,14 +9,14 @@ function renderIcon(icon: Component) {
|
||||
|
||||
export type PageKey = "grid" | "tasks";
|
||||
|
||||
export const navGroups = [
|
||||
export const navOptions = [
|
||||
{
|
||||
type: "group" as const,
|
||||
label: "下载",
|
||||
key: "download",
|
||||
icon: renderIcon(CloudDownloadOutline),
|
||||
children: [
|
||||
{ label: "栅格下载", key: "grid" as const, icon: renderIcon(CloudDownloadOutline) },
|
||||
{ label: "下载管理", key: "tasks" as const, icon: renderIcon(ListOutline) },
|
||||
],
|
||||
},
|
||||
{ label: "下载管理", key: "tasks" as const, icon: renderIcon(ListOutline) },
|
||||
];
|
||||
|
||||
+71
-17
@@ -31,9 +31,11 @@
|
||||
|
||||
html,
|
||||
body,
|
||||
#app {
|
||||
#app,
|
||||
.app-root {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
button,
|
||||
@@ -44,9 +46,12 @@ select {
|
||||
|
||||
.gate {
|
||||
position: relative;
|
||||
min-height: 100%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
box-sizing: border-box;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 32px 16px;
|
||||
background: var(--bg);
|
||||
}
|
||||
@@ -106,6 +111,14 @@ select {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.form-top {
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.form-top label {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.brand p {
|
||||
margin: 2px 0 0;
|
||||
font-size: 13px;
|
||||
@@ -117,6 +130,11 @@ select {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.captcha-line .n-select {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.form-row label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -134,13 +152,18 @@ select {
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.gate-actions {
|
||||
.gate-actions,
|
||||
.sms-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.sms-actions {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.shell {
|
||||
height: 100%;
|
||||
display: grid;
|
||||
@@ -210,9 +233,16 @@ select {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.page-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.page-head {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
flex: none;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -247,13 +277,31 @@ select {
|
||||
}
|
||||
|
||||
.panel {
|
||||
margin: 16px 20px 24px;
|
||||
margin: 16px 20px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
border-radius: 10px;
|
||||
padding: 16px 16px 8px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
cursor: help;
|
||||
.form-row .n-select,
|
||||
.form-row .n-date-picker,
|
||||
.form-row .n-input-number {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.checks {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.check-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-height: 28px;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
@@ -329,7 +377,7 @@ select {
|
||||
}
|
||||
|
||||
.empty {
|
||||
margin: 48px auto;
|
||||
margin: auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@@ -337,6 +385,17 @@ select {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex: none;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.limit-label {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.limit-control {
|
||||
width: 112px;
|
||||
}
|
||||
|
||||
.fail-list {
|
||||
@@ -350,8 +409,3 @@ select {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
margin: 48px auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user