feat: 完成登录与栅格下载桌面端
This commit is contained in:
@@ -0,0 +1,359 @@
|
||||
"""门户登录与栅格查询。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import calendar
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import httpx
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
|
||||
from app.platform.constants import (
|
||||
APP_KEY,
|
||||
CAS_CAPTCHA,
|
||||
CAS_CONFIG,
|
||||
CAS_LOGIN,
|
||||
CAS_SMS,
|
||||
CAS_USER,
|
||||
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'<form[^>]*id="fm1"[^>]*action="([^"]*)"', re.I)
|
||||
_FORM_ACTION_REV = re.compile(r'<form[^>]*action="([^"]*)"[^>]*id="fm1"', re.I)
|
||||
_ERROR_TEXT = re.compile(r'id="errMsg"[^>]*>(.*?)</', re.S)
|
||||
|
||||
|
||||
class NqiError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
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", ""))
|
||||
|
||||
|
||||
@dataclass
|
||||
class LoginChallenge:
|
||||
execution: str
|
||||
public_key: str
|
||||
form_action: str
|
||||
captcha_png: bytes
|
||||
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=True,
|
||||
)
|
||||
|
||||
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 ""
|
||||
|
||||
async def open_login(self) -> LoginChallenge:
|
||||
response = await self.client.get(CAS_LOGIN, 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("登录页没有返回加密参数,请稍后重试")
|
||||
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)
|
||||
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)})
|
||||
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,
|
||||
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},
|
||||
)
|
||||
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.client.post(
|
||||
CAS_CONFIG,
|
||||
json=payload,
|
||||
headers={"Referer": CAS_LOGIN, "Origin": ORIGIN},
|
||||
)
|
||||
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.client.post(
|
||||
CAS_SMS,
|
||||
json=payload,
|
||||
headers={"Referer": CAS_LOGIN, "Origin": ORIGIN},
|
||||
)
|
||||
data = _json_or_error(response, "短信发送失败")
|
||||
if data.get("success") is False:
|
||||
raise NqiError(str(data.get("msg") or "短信发送失败"))
|
||||
return str(data.get("msg") or "短信已发送")
|
||||
|
||||
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",
|
||||
},
|
||||
)
|
||||
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 "登录未成功,请检查验证码或短信验证码")
|
||||
return await self.current_user()
|
||||
|
||||
async def current_user(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 {
|
||||
"loginId": data.get("loginId") or "",
|
||||
"userName": data.get("userName") or "",
|
||||
"cityName": data.get("cityName") or "",
|
||||
"orgName": data.get("orgName") or "",
|
||||
}
|
||||
|
||||
async def layer_code(self, *, city_code: str, month: str, network: str) -> dict:
|
||||
params = {
|
||||
"dataType": "GRID",
|
||||
"cityCode": city_code,
|
||||
"date": month_end(month),
|
||||
"gridSize": "GRID20",
|
||||
"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) -> 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"grid20_id={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 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 _signed_get(self, url: str, params: dict) -> dict:
|
||||
headers = build_sign(params)
|
||||
headers["Referer"] = f"{ORIGIN}/pro-problem-warehouse-web/"
|
||||
response = await self.client.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.client.post(url, json=body, headers=headers)
|
||||
return _api_payload(response)
|
||||
|
||||
|
||||
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 _json_or_error(response: httpx.Response, fallback: str) -> dict:
|
||||
if response.status_code in {401, 403}:
|
||||
raise NqiError("登录已失效,请重新登录")
|
||||
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
|
||||
Reference in New Issue
Block a user