feat: 完善登录保持、栅格下载和任务调度

This commit is contained in:
2026-10-25 05:42:24 +08:00
parent dab26ff4ee
commit 4cf64957c5
25 changed files with 1871 additions and 320 deletions
+365 -57
View File
@@ -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"