"""门户登录与栅格查询。""" from __future__ import annotations import asyncio import base64 import calendar import json import re import time from collections import deque from collections.abc import AsyncIterator from dataclasses import dataclass, field from urllib.parse import quote, urlencode import httpx from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from app.shared.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, PORTAL_SERVICE, USER_AGENT, ) from app.platform.sign import build_sign, wfs_sig _EXECUTION = re.compile(r'name="execution"\s+value="([^"]+)"', re.I) _PUBLIC_KEY = re.compile(r'setPublicKey\("([^"]+)"\)') _GENERIC_LOGIN_FAILURE = "登录未成功,请检查验证码或短信验证码" POOL_CONNECTIONS = 300 class NqiError(Exception): pass class NqiAuthError(NqiError): pass class TileReadError(NqiError): """分块读取失败,调用方决定重试、拆分或记入失败块。""" def __init__(self, message: str, kind: str) -> None: super().__init__(message) self.kind = kind # 每块最多重试 3 次,依次等待这些秒数。GRID20 从 0.02° 起拆,GRID50 从 0.05° 起拆。 TILE_RETRY_WAITS = (1, 3, 9) MIN_TILE_WIDTH = 0.005 MAX_TILE_DEPTH = 8 # 没有 numberMatched 时,单块条数达到这个值就继续拆,避免服务端截断后悄悄少读。 TILE_SPLIT_AT = 10000 def rsa_encrypt(public_key_b64: str, text: str) -> str: der = base64.b64decode(public_key_b64) key = serialization.load_der_public_key(der) encrypted = key.encrypt(text.encode("utf-8"), padding.PKCS1v15()) return base64.b64encode(encrypted).decode("ascii") def month_end(month: str) -> str: """2026-09 -> 20260930。图层接口使用该月最后一天。""" year_text, month_text = month.split("-", 1) year = int(year_text) month_number = int(month_text) if month_number < 1 or month_number > 12: raise NqiError("月份需要是 YYYY-MM") last_day = calendar.monthrange(year, month_number)[1] return f"{year:04d}{month_number:02d}{last_day:02d}" 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 needs_captcha(message: str) -> bool: """失败原因是图形验证码。短信验证码错误不在这里。""" if not message or message == _GENERIC_LOGIN_FAILURE: return False text = message.replace("短信验证码", "") if "验证码" in text: return True lowered = text.lower() return "captcha" in lowered and "sms" not in lowered @dataclass class LoginChallenge: execution: str public_key: str captcha_png: bytes page_url: str captcha_type: str = "image/jpeg" username: str = "" password: str = "" captcha: str = "" config_ready: bool = False @dataclass class NqiClient: client: httpx.AsyncClient = field(init=False) def __post_init__(self) -> None: self._inflight = 0 self._idle = asyncio.Event() self._idle.set() self.client = httpx.AsyncClient( headers={ "User-Agent": USER_AGENT, "Accept": "application/json, text/plain, */*", "Accept-Language": "zh-CN,zh;q=0.9", }, timeout=httpx.Timeout(45.0, connect=15.0), follow_redirects=True, trust_env=False, limits=httpx.Limits( max_connections=POOL_CONNECTIONS, max_keepalive_connections=POOL_CONNECTIONS, ), ) raw_send = self.client.send async def send(request, *args, **kwargs): self._inflight += 1 self._idle.clear() try: return await raw_send(request, *args, **kwargs) finally: self._inflight = max(0, self._inflight - 1) if self._inflight == 0: self._idle.set() self.client.send = send async def aclose(self) -> None: await self.client.aclose() async def wait_idle(self, timeout: float = 5.0) -> None: """等在途请求结束。到时仍未结束也返回,调用方再关闭客户端。""" deadline = time.monotonic() + timeout while True: if self._inflight == 0: await asyncio.sleep(0) if self._inflight == 0: return remaining = deadline - time.monotonic() if remaining <= 0: return try: await asyncio.wait_for(self._idle.wait(), min(0.2, remaining)) except TimeoutError: continue def export_cookies(self) -> list[dict[str, str]]: exported: list[dict[str, str]] = [] for cookie in self.client.cookies.jar: exported.append( { "name": cookie.name, "value": cookie.value, "domain": cookie.domain or "", "path": cookie.path or "/", } ) return exported def import_cookies(self, cookies: list[dict]) -> None: for cookie in cookies: if not cookie.get("name"): continue self.client.cookies.set( cookie["name"], cookie.get("value", ""), domain=cookie.get("domain") or "", path=cookie.get("path") or "/", ) def ticket(self) -> str: for name in ("CASTGC", "TGC"): value = self.client.cookies.get(name) if value: 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._request( "GET", CAS_LOGIN, check_auth=False, params={"service": PORTAL_SERVICE}, ) 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)) captcha = await self._request( "GET", CAS_CAPTCHA, check_auth=False, headers={"Referer": page_url}, ) if captcha.status_code != 200 or not captcha.content: raise NqiError("验证码获取失败") return LoginChallenge( execution=execution.group(1), public_key=public_key.group(1), captcha_png=captcha.content, page_url=page_url, captcha_type=_media_type(captcha), ) async def refresh_captcha(self, challenge: LoginChallenge) -> bytes: response = await self._request( "GET", CAS_CAPTCHA, check_auth=False, params={"id": "refresh"}, headers={"Referer": challenge.page_url}, ) if response.status_code != 200 or not response.content: raise NqiError("验证码刷新失败") challenge.captcha_png = response.content challenge.captcha_type = _media_type(response) return response.content async def prepare_login(self, challenge: LoginChallenge, username: str, password: str, captcha: str) -> str: challenge.username = username challenge.password = password challenge.captcha = captcha.strip() payload = { "loginId": rsa_encrypt(challenge.public_key, username), "password": rsa_encrypt(challenge.public_key, password), "captcha": challenge.captcha, } response = await self._request( "POST", CAS_CONFIG, check_auth=False, json=payload, headers=self._ajax_headers(challenge), ) data = _json_or_error(response, "登录校验失败") code = _code(data) if code not in {"0", "1"}: message = data.get("message") or data.get("msg") or "账号、密码或验证码不正确" raise NqiError(str(message)) challenge.config_ready = True return code async def send_sms(self, challenge: LoginChallenge) -> str: if not challenge.username or not challenge.password: raise NqiError("请先填写账号和密码") payload = { "loginId": rsa_encrypt(challenge.public_key, challenge.username), "password": rsa_encrypt(challenge.public_key, challenge.password), } response = await self._request( "POST", CAS_SMS, check_auth=False, json=payload, headers=self._ajax_headers(challenge), timeout=httpx.Timeout(120.0, connect=15.0), ) data = _json_or_error(response, "短信发送失败") return sms_notice(data) async def submit_login(self, challenge: LoginChallenge, sms_code: str = "") -> dict: if not challenge.config_ready: raise NqiError("请先完成验证码校验") # 网页表单里 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", ""), ] response = await self._request( "POST", challenge.page_url, check_auth=False, 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", }, ) if not self.ticket(): message = _login_failure_message(response) found = _EXECUTION.search(response.text or "") if found: challenge.execution = found.group(1) if needs_captcha(message): challenge.config_ready = False raise NqiError(message) return await self.current_user() async def _cas_user_payload(self) -> dict: ticket = self.ticket() headers = {"Referer": f"{ORIGIN}/pro-portal/"} if ticket: headers["tgc"] = ticket response = await self._request("GET", CAS_USER, headers=headers) data = _json_or_error(response, "读取登录用户失败") if not data.get("loginId") and not data.get("userName"): raise NqiAuthError("登录已失效,请重新登录") return data async def current_user(self) -> dict: return _public_user(await self._cas_user_payload()) async def touch_session(self) -> dict: """访问门户和图层接口,滑动服务端的登录有效期。""" data = await self._cas_user_payload() 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 await self._request( "POST", CAS_PASSWORD_CHECK, json={}, headers=headers, timeout=httpx.Timeout(20.0, connect=10.0), ) async def _touch_online(self) -> None: try: await self._request( "GET", PORTAL_ONLINE, headers={"Referer": f"{ORIGIN}/pro-portal/"}, timeout=httpx.Timeout(20.0, connect=10.0), follow_redirects=False, ) except NqiAuthError: raise except NqiError: 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": grid_size, "networkType": network, } payload = await self._signed_get(f"{GIS_API}/base/v2/zc/layerCode/get", params) data = payload.get("data") or {} service_code = data.get("serviceCode") if not service_code: raise NqiError(payload.get("msg") or "该月份没有数据") version = str(data.get("version") or "") expected = month.replace("-", "") if version and not version.startswith(expected): raise NqiError(f"{month} 暂无数据") return data async def grid_feature(self, service_code: str, grid_id: str, id_field: str = "grid20_id") -> dict | None: params = { "maxFeatures": "5", "SERVICE": "Wfs", "VERSION": "2.0.0", "REQUEST": "Getfeature", "outputFormat": "application/json", "SRS": "EPSG:4326", "STYLES": "", "ak": APP_KEY, "sig": wfs_sig(service_code), "CQL_FILTER": f"{id_field}={grid_id}", } response = await self._request( "GET", f"{GIS_PROD}/api/{service_code}/wfs", params=params, headers={"Referer": f"{ORIGIN}/pro-problem-warehouse-web/"}, ) if response.status_code != 200: raise NqiError(f"栅格查询失败({response.status_code})") text = response.text.lstrip() if text.startswith("<"): raise NqiError("栅格查询被拒绝") try: payload = response.json() except json.JSONDecodeError as exc: raise NqiError("栅格查询返回的不是数据") from exc features = payload.get("features") or [] if not features: 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, halt_event: asyncio.Event | None = None, *, grid_size: str = "GRID20", failed_tiles: list | None = None, seen: set[int] | None = None, tiles: list | None = None, ) -> AsyncIterator[str]: """按图层范围分块产出编号。一块返回就交出,不等整层读完。""" if seen is None: seen = set() for item in skip or (): if str(item).isdigit(): seen.add(int(item)) if tiles is None: bounds = await self._layer_bounds(service_code) step = 0.05 if grid_size == "GRID50" else 0.02 pending: deque[tuple[tuple[float, float, float, float], int]] = deque( (tile, 0) for tile in _tiles(*bounds, step) ) else: pending = deque((tuple(tile), 0) for tile in tiles) inflight: set[asyncio.Task] = set() async def fetch(tile: tuple[float, float, float, float], depth: int): width = tile[2] - tile[0] for attempt in range(len(TILE_RETRY_WAITS) + 1): try: features, matched = await self._tile_features(service_code, id_field, tile) return "ok", tile, depth, features, matched except NqiAuthError: raise except TileReadError as exc: if exc.kind == "timeout" and _can_split(width, depth): return "split", tile, depth, [], None if attempt >= len(TILE_RETRY_WAITS): return "fail", tile, depth, [], None if not await _interruptible_sleep(TILE_RETRY_WAITS[attempt], cancel_event, run_event): return "stop", tile, depth, [], None except NqiError: return "fail", tile, depth, [], None return "fail", tile, depth, [], None try: await progress(len(seen)) while not cancel_event.is_set() and (pending or inflight): if not await _wait_turn(cancel_event, run_event, halt_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: try: kind, tile, depth, features, matched = task.result() except NqiAuthError: raise width = tile[2] - tile[0] if kind == "stop": continue if kind == "fail": if failed_tiles is not None: failed_tiles.append([tile[0], tile[1], tile[2], tile[3]]) continue if kind == "split" or _should_split(features, matched, width, depth): pending.extend((child, depth + 1) for child in _split_tile(tile)) continue matched_count = _matched_count(matched) truncated = (matched_count is not None and matched_count > len(features)) or ( matched_count is None and len(features) >= TILE_SPLIT_AT ) if truncated and failed_tiles is not None: failed_tiles.append([tile[0], tile[1], tile[2], tile[3]]) for feature in features: grid_id = normalize_id((feature.get("properties") or {}).get(id_field)) if not grid_id: continue number = int(grid_id) if number in seen: continue seen.add(number) fresh.append(grid_id) await progress(len(seen)) for grid_id in fresh: if not await _wait_turn(cancel_event, run_event, halt_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._request( "GET", f"{GIS_PROD}/api/{service_code}/wfs", params={ "SERVICE": "Wfs", "VERSION": "2.0.0", "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 | None]: west, south, east, north = tile ring = f"{west} {south},{east} {south},{east} {north},{west} {north},{west} {south}" try: response = await self._request( "GET", f"{GIS_PROD}/api/{service_code}/wfs", params={ "SERVICE": "Wfs", "VERSION": "2.0.0", "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), ) except NqiAuthError: raise except NqiError as exc: text = str(exc) if "超时" in text: raise TileReadError(text, "timeout") from exc if "连接失败" in text: raise TileReadError(text, "connect") from exc raise if response.status_code >= 500: raise TileReadError("平台暂时不可用,请稍后重试", "server") if response.status_code != 200: raise NqiError("读取地市栅格失败") text = response.text.lstrip() if not text.startswith("{"): raise TileReadError("读取地市栅格失败", "json") try: payload = response.json() except json.JSONDecodeError as exc: raise TileReadError("读取地市栅格失败", "json") from exc features = payload.get("features") if not isinstance(features, list): raise TileReadError("读取地市栅格失败", "json") return features, _matched_count(payload.get("numberMatched")) async def cell_rows(self, service_code: str, grid_id: str, network: str) -> list[dict]: body = { "current": 1, "data": str(grid_id), "isPage": False, "networkType": network, "operatorType": "YD", "serviceCode": service_code, "size": 1000, } payload = await self._signed_post(f"{GIS_API}/base/v2/zc/cellInfo/page/compatible", body) data = payload.get("data") or {} records = list(data.get("records") or []) total = int(data.get("total") or len(records)) page = 1 while len(records) < total and page < 20: page += 1 body = {**body, "current": page, "isPage": True, "size": 1000} payload = await self._signed_post(f"{GIS_API}/base/v2/zc/cellInfo/page/compatible", body) extra = (payload.get("data") or {}).get("records") or [] if not extra: break records.extend(extra) return records async def _request(self, method: str, url: str, *, check_auth: bool = True, **kwargs) -> httpx.Response: send = getattr(self.client, method.lower()) try: response = await send(url, **kwargs) except httpx.TimeoutException as exc: raise NqiError("平台响应超时,请稍后重试") from exc except httpx.RequestError as exc: raise NqiError("连接失败,请稍后重试") from exc except RuntimeError as exc: if "client has been closed" in str(exc): raise NqiAuthError("需要重新登录") from exc raise if check_auth and (response.status_code in {401, 403} or _landed_on_login(response)): raise NqiAuthError("登录已失效,请重新登录") return response async def _signed_get(self, url: str, params: dict) -> dict: headers = build_sign(params) headers["Referer"] = f"{ORIGIN}/pro-problem-warehouse-web/" response = await self._request("GET", url, params=params, headers=headers) return _api_payload(response) async def _signed_post(self, url: str, body: dict) -> dict: headers = build_sign({}) headers["Referer"] = f"{ORIGIN}/pro-problem-warehouse-web/" response = await self._request("POST", url, json=body, headers=headers) return _api_payload(response) def _can_split(width: float, depth: int) -> bool: return width > MIN_TILE_WIDTH + 1e-9 and depth < MAX_TILE_DEPTH def _matched_count(matched) -> int | None: if isinstance(matched, bool) or matched is None: return None if isinstance(matched, int): return matched if isinstance(matched, float): return int(matched) if isinstance(matched, str) and matched.strip().isdigit(): return int(matched.strip()) return None def _should_split(features: list, matched, width: float, depth: int) -> bool: if not _can_split(width, depth): return False count = _matched_count(matched) if count is None: return len(features) >= TILE_SPLIT_AT return count > len(features) async def _interruptible_sleep(seconds: float, cancel_event: asyncio.Event, run_event: asyncio.Event | None) -> bool: """重试等待可被暂停或停止打断。返回 False 表示任务已停止。""" left = seconds while left > 0: if not await _wait_turn(cancel_event, run_event): return False step = min(0.2, left) await asyncio.sleep(step) left -= step return not cancel_event.is_set() async def _wait_turn( cancel_event: asyncio.Event, run_event: asyncio.Event | None, halt_event: asyncio.Event | None = None, ) -> bool: """暂停时停住。返回 False 表示停止或要按新的并发重开。""" def halted() -> bool: return halt_event is not None and halt_event.is_set() if run_event is None: return not cancel_event.is_set() and not halted() while not run_event.is_set(): if cancel_event.is_set() or halted(): return False try: await asyncio.wait_for(run_event.wait(), timeout=0.3) except asyncio.TimeoutError: continue return not cancel_event.is_set() and not halted() 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"[^>]*>(.*?)]*>(.*?)]*>(.*?)]+>", "", match.group(1)) detail = re.sub(r"\s+", " ", detail).strip() if detail: return detail return _GENERIC_LOGIN_FAILURE def _media_type(response: httpx.Response) -> str: raw = response.headers.get("content-type", "image/jpeg").split(";", 1)[0].strip() return raw or "image/jpeg" def _landed_on_login(response: httpx.Response) -> bool: url = getattr(response, "url", None) if url is None: return False path = getattr(url, "path", "") or "" if path: return path.rstrip("/").endswith("/cas/login") return "/cas/login" in str(url) def _json_or_error(response: httpx.Response, fallback: str) -> dict: if response.status_code in {401, 403}: raise NqiAuthError("登录已失效,请重新登录") try: data = response.json() except json.JSONDecodeError as exc: raise NqiError(fallback) from exc if not isinstance(data, dict): raise NqiError(fallback) return data def _api_payload(response: httpx.Response) -> dict: data = _json_or_error(response, "平台接口没有返回数据") code = data.get("code") if code not in (0, "0", None): raise NqiError(str(data.get("msg") or data.get("message") or "平台接口返回失败")) return data