"""门户登录与栅格查询。""" 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 quote, urlencode, urljoin 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\("([^"]+)"\)') _FORM_ACTION = re.compile(r']*id="fm1"[^>]*action="([^"]*)"', re.I) _FORM_ACTION_REV = re.compile(r']*action="([^"]*)"[^>]*id="fm1"', re.I) _ERROR_TEXT = re.compile(r'id="errMsg"[^>]*>(.*?) 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 _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 = "" captcha: str = "" config_ready: bool = False @dataclass class NqiClient: client: httpx.AsyncClient = field(init=False) def __post_init__(self) -> None: 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=200, max_keepalive_connections=40), ) async def aclose(self) -> None: await self.client.aclose() 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 None, 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: 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 page_url if action.startswith("/"): action = ORIGIN + action elif not action.startswith("http"): 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( execution=execution.group(1), 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: 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 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, } 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"}: 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), } 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, "短信发送失败") 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", ""), ] 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(): raise NqiError(_login_failure_message(response)) 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.client.get(CAS_USER, headers=headers) data = _json_or_error(response, "读取登录用户失败") if not data.get("loginId") and not data.get("userName"): raise NqiError("登录状态已失效") return data 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": 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": "", "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.client.get( f"{GIS_PROD}/api/{service_code}/wfs", params=params, headers={"Referer": f"{ORIGIN}/pro-problem-warehouse-web/"}, ) if response.status_code in {401, 403}: raise NqiError("登录已失效,请重新登录") 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, ) -> 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, "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) 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"[^>]*>(.*?)]*>(.*?)]*>(.*?)]+>", "", 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" 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