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
|
||||
Reference in New Issue
Block a user