feat: 实现已确认的登录、采集和任务导出
This commit is contained in:
@@ -0,0 +1,460 @@
|
||||
"""门户登录。登录、短信和凭证续期与已验证的 NqiTools 相同。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
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.nqi.constants import (
|
||||
CAS_CAPTCHA,
|
||||
CAS_CONFIG,
|
||||
CAS_LOGIN,
|
||||
CAS_PASSWORD_CHECK,
|
||||
CAS_SMS,
|
||||
CAS_USER,
|
||||
GIS_API,
|
||||
ORIGIN,
|
||||
PORTAL_ONLINE,
|
||||
PORTAL_SERVICE,
|
||||
USER_AGENT,
|
||||
)
|
||||
from app.nqi.sign import build_sign
|
||||
|
||||
_EXECUTION = re.compile(r'name="execution"\s+value="([^"]+)"', re.I)
|
||||
_PUBLIC_KEY = re.compile(r'setPublicKey\("([^"]+)"\)')
|
||||
_GENERIC_LOGIN_FAILURE = "登录未成功,请检查验证码或短信验证码"
|
||||
|
||||
|
||||
class NqiError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NqiAuthError(NqiError):
|
||||
pass
|
||||
|
||||
|
||||
class NqiNetworkError(NqiError):
|
||||
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 login_page_url(url: str) -> str:
|
||||
if "service=" in url:
|
||||
return url
|
||||
return f"{CAS_LOGIN}?service={quote(PORTAL_SERVICE, safe='')}"
|
||||
|
||||
|
||||
def sms_notice(payload: dict) -> str:
|
||||
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,
|
||||
)
|
||||
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 = str(data.get("code", ""))
|
||||
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("请先完成验证码校验")
|
||||
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 fetch_bytes(self, url: str) -> tuple[str, bytes]:
|
||||
response = await self._request("GET", url, headers={"Referer": f"{ORIGIN}/pro-portal/"})
|
||||
if response.status_code >= 400:
|
||||
raise NqiError("采集地址没有返回数据")
|
||||
name = url.rsplit("/", 1)[-1] or "nqi.csv"
|
||||
return name, response.content
|
||||
|
||||
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 _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 NqiNetworkError("平台响应超时,请稍后重试") from exc
|
||||
except httpx.RequestError as exc:
|
||||
raise NqiNetworkError("连接失败,请稍后重试") 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
|
||||
|
||||
|
||||
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 _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 _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("登录已失效,请重新登录")
|
||||
if response.status_code >= 500:
|
||||
raise NqiNetworkError("平台暂时不可用,请稍后重试")
|
||||
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
|
||||
@@ -0,0 +1,23 @@
|
||||
"""平台地址与门户页面公开的签名参数。与已验证的 NqiTools 保持一致。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
ORIGIN = "https://nqi.gmcc.net:20443"
|
||||
CAS_LOGIN = f"{ORIGIN}/cas/login"
|
||||
CAS_CONFIG = f"{ORIGIN}/cas/getConfig"
|
||||
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_API = f"{ORIGIN}/pro-gis-tenant/gmcc-wyzc/api"
|
||||
|
||||
APP_KEY = "1e395dc741b64ce1913cf411e6c08384"
|
||||
APP_SECRET = "2d6f5e13b9d54c99bea58f46c2a45ddb"
|
||||
SIGN_VERSION = "1.0.0"
|
||||
|
||||
USER_AGENT = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""登录过程只放在内存里,超时后丢掉密码。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from app.nqi.client import LoginChallenge, NqiClient
|
||||
|
||||
FLOW_TTL_SECONDS = 10 * 60
|
||||
flows: dict[str, tuple[NqiClient, LoginChallenge, str]] = {}
|
||||
|
||||
|
||||
async def purge(now: float | None = None) -> None:
|
||||
moment = time.monotonic() if now is None else now
|
||||
expired: list[str] = []
|
||||
for session_id, (client, challenge, _purpose) in list(flows.items()):
|
||||
created = getattr(challenge, "created_at", None)
|
||||
if created is None or moment - float(created) < FLOW_TTL_SECONDS:
|
||||
continue
|
||||
expired.append(session_id)
|
||||
for session_id in expired:
|
||||
client, challenge, _purpose = flows.pop(session_id)
|
||||
challenge.password = ""
|
||||
await client.aclose()
|
||||
|
||||
|
||||
def remember(client: NqiClient, challenge: LoginChallenge, purpose: str) -> str:
|
||||
session_id = uuid.uuid4().hex
|
||||
challenge.created_at = time.monotonic()
|
||||
flows[session_id] = (client, challenge, purpose)
|
||||
return session_id
|
||||
|
||||
|
||||
def take(session_id: str) -> tuple[NqiClient, LoginChallenge, str] | None:
|
||||
return flows.get(session_id)
|
||||
|
||||
|
||||
def drop(session_id: str) -> None:
|
||||
flows.pop(session_id, None)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""复现门户脚本里的请求签名。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from app.nqi.constants import APP_KEY, APP_SECRET, SIGN_VERSION
|
||||
|
||||
_SKIP = {"sign", "SIG", "UPPER_SIG"}
|
||||
|
||||
|
||||
def encode_uri_component(value: str) -> str:
|
||||
return quote(value, safe="-_.!~*'()")
|
||||
|
||||
|
||||
def build_sign(
|
||||
params: dict | None = None,
|
||||
*,
|
||||
encode: bool = True,
|
||||
timestamp: str | None = None,
|
||||
nonce: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
stamp = timestamp if timestamp is not None else str(int(time.time()))
|
||||
nonce_str = nonce if nonce is not None else uuid.uuid4().hex
|
||||
payload: dict[str, str] = {}
|
||||
for key, value in (params or {}).items():
|
||||
text = "" if value is None else str(value)
|
||||
payload[str(key)] = text if text == "" or not encode else encode_uri_component(text)
|
||||
payload["timestamp"] = stamp
|
||||
payload["nonceStr"] = nonce_str
|
||||
payload["version"] = SIGN_VERSION
|
||||
raw = "".join(f"{key}{payload[key]}" for key in sorted(payload) if key not in _SKIP)
|
||||
sign = hashlib.md5((raw + APP_SECRET).encode("utf-8")).hexdigest().upper()
|
||||
return {
|
||||
"sign": sign,
|
||||
"timestamp": stamp,
|
||||
"nonceStr": nonce_str,
|
||||
"version": SIGN_VERSION,
|
||||
"appKey": APP_KEY,
|
||||
}
|
||||
Reference in New Issue
Block a user