223 lines
8.6 KiB
Python
223 lines
8.6 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""xq0077 携程数据导出 - 管理端登录模块(纯接口,自包含)。
|
||
|
||
流程(2026-11 实测):
|
||
1) GET /admin/api/checkCode?rand=<ms> 取图片验证码(JPEG 直出,需同一会话 Cookie);
|
||
2) ddddocr 识别验证码;
|
||
3) POST /admin/storeMerchant/logining JSON {username, password: RSA加密, checkcode, cipherText:1},
|
||
返回 user.token 即管理端 tyAuthToken(后续 statisticsSupport 等接口用它)。
|
||
|
||
重试策略:验证码类失败最多 3 轮;账号/密码错误立即停止,绝不重试(避免锁号)。
|
||
token 缓存:%LOCALAPPDATA%\\37duAutomation\\.sessions\\lotsmall_token.json({"accessToken": ...}),
|
||
每次运行先用缓存 token 调 statisticsSupport 探测,失效再登录。
|
||
"""
|
||
import base64
|
||
import json
|
||
import os
|
||
import time
|
||
import urllib.parse
|
||
|
||
import requests
|
||
from cryptography.hazmat.primitives import serialization
|
||
from cryptography.hazmat.primitives.asymmetric import padding
|
||
|
||
from .. import config
|
||
|
||
|
||
def _log(msg, level="INFO"):
|
||
config.log(msg, level)
|
||
|
||
|
||
# ==================== 基础会话 ====================
|
||
def new_session():
|
||
session = requests.Session()
|
||
session.headers.update({
|
||
"User-Agent": config.UA,
|
||
"Origin": config.ADMIN_BASE,
|
||
"Referer": config.ADMIN_BASE + "/admin/storeMerchant/login",
|
||
"Accept": "application/json, text/plain, */*",
|
||
})
|
||
return session
|
||
|
||
|
||
def fetch_code_image(session):
|
||
"""取管理端图片验证码(JPEG 字节);验证码与当前会话 Cookie 绑定。"""
|
||
resp = session.get(config.ADMIN_BASE + config.API_CHECKCODE,
|
||
params={"rand": int(time.time() * 1000)}, timeout=config.TIMEOUT)
|
||
if resp.status_code != 200 or not resp.content:
|
||
raise RuntimeError(f"获取图片验证码失败(HTTP {resp.status_code})")
|
||
if resp.content[:2] != b'\xff\xd8': # JPEG 魔数,避免把错误 JSON 当图片
|
||
raise RuntimeError(f"图片验证码返回非图片:{resp.text[:120]}")
|
||
return resp.content
|
||
|
||
|
||
def ocr_code(img_bytes):
|
||
"""ddddocr 识别验证码;长度不在合理区间视为识别失败。"""
|
||
try:
|
||
import ddddocr
|
||
except ImportError:
|
||
raise RuntimeError("未安装 ddddocr,请先 pip install ddddocr")
|
||
code = ddddocr.DdddOcr(show_ad=False).classification(img_bytes).strip()
|
||
if config.CAPTCHA_MIN_LEN <= len(code) <= config.CAPTCHA_MAX_LEN:
|
||
return code
|
||
return ""
|
||
|
||
|
||
def rsa_encrypt(text):
|
||
"""RSA PKCS#1 v1.5 加密 + URL 编码(与前端 setRSA 一致)。"""
|
||
pem = ("-----BEGIN PUBLIC KEY-----\n" + config.RSA_PUBLIC_KEY +
|
||
"\n-----END PUBLIC KEY-----")
|
||
key = serialization.load_pem_public_key(pem.encode())
|
||
cipher = key.encrypt(text.encode(), padding.PKCS1v15())
|
||
return urllib.parse.quote(base64.b64encode(cipher).decode(), safe="")
|
||
|
||
|
||
def do_login(session, account, password, code):
|
||
"""账密登录。注意:管理端 apiPost 用 x-www-form-urlencoded(qs 序列化),不能发 JSON。"""
|
||
payload = {
|
||
"username": account,
|
||
"password": rsa_encrypt(password),
|
||
"checkcode": code,
|
||
"cipherText": 1,
|
||
}
|
||
resp = session.post(config.ADMIN_BASE + config.API_ADMIN_LOGIN, data=payload,
|
||
headers={"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"},
|
||
timeout=config.TIMEOUT)
|
||
try:
|
||
return resp.json(), resp.text
|
||
except ValueError:
|
||
raise RuntimeError(f"登录接口返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||
|
||
|
||
# ==================== token 缓存 ====================
|
||
def _atomic_write(path, text):
|
||
"""原子写:先写临时文件再整体替换,避免中断留下半截文件。"""
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
tmp = f'{path}.tmp'
|
||
with open(tmp, 'w', encoding='utf-8') as f:
|
||
f.write(text)
|
||
os.replace(tmp, path)
|
||
|
||
|
||
def load_token():
|
||
if not os.path.exists(config.TOKEN_FILE):
|
||
return ""
|
||
try:
|
||
with open(config.TOKEN_FILE, encoding='utf-8') as f:
|
||
return str((json.load(f) or {}).get("accessToken") or "")
|
||
except Exception as e:
|
||
_log(f"读取 token 缓存失败:{e}", "WARN")
|
||
return ""
|
||
|
||
|
||
def save_token(token):
|
||
try:
|
||
_atomic_write(config.TOKEN_FILE, json.dumps({"accessToken": token}, ensure_ascii=False))
|
||
_log(f"token 已缓存 → {config.TOKEN_FILE}")
|
||
except Exception as e:
|
||
_log(f"token 缓存写入失败(不影响本次运行):{e}", "WARN")
|
||
|
||
|
||
# ==================== 管理端 token 探测 / 报表接入参数 ====================
|
||
def fetch_report_params(token):
|
||
"""statisticsSupport 探测 token 并取报表接入参数。
|
||
|
||
返回 data(含 authCode/appId/sign/timestamp/bigDataLoginAuthCode/corpCode);
|
||
token 失效或返回异常时返回 None。
|
||
"""
|
||
if not token:
|
||
return None
|
||
ts = int(time.time() * 1000)
|
||
url = (f"{config.ADMIN_BASE}{config.API_STATISTICS_SUPPORT}"
|
||
f"?timestamp={ts}&reportId={config.REPORT_ID}"
|
||
f"&reportUrl={config.REPORT_URL}&terminalTpe=0")
|
||
try:
|
||
resp = requests.get(url, headers={
|
||
"tyAuthToken": token,
|
||
"User-Agent": config.UA,
|
||
"Referer": config.ADMIN_BASE + "/manage/",
|
||
}, timeout=config.TIMEOUT)
|
||
data = resp.json()
|
||
except Exception as e:
|
||
_log(f"statisticsSupport 探测异常:{e}", "WARN")
|
||
return None
|
||
if data.get("code") == config.CODE_TOKEN_EXPIRED:
|
||
_log("管理端 token 已失效(请跳转到登录页)")
|
||
return None
|
||
if data.get("code") != config.CODE_OK or not data.get("data"):
|
||
_log(f"statisticsSupport 失败:{str(data)[:200]}", "WARN")
|
||
return None
|
||
return data["data"]
|
||
|
||
|
||
# ==================== 主入口 ====================
|
||
def ensure_login(account, password, force=False):
|
||
"""确保存在可用的管理端 token。
|
||
|
||
先复用缓存 token(statisticsSupport 探测),失效再走账密登录。
|
||
返回 dict:{success, token, message, relogin}
|
||
"""
|
||
account = (account or '').strip()
|
||
password = (password or '').strip()
|
||
|
||
if not force:
|
||
token = load_token()
|
||
if token and fetch_report_params(token):
|
||
_log("已通过缓存的 token 复用管理端登录态")
|
||
return {"success": True, "token": token, "message": "复用缓存登录态", "relogin": False}
|
||
|
||
if not (account and password):
|
||
msg = "登录账号/密码缺失:请在插件界面填写并保存配置"
|
||
_log(msg, "ERROR")
|
||
return {"success": False, "token": "", "message": msg, "relogin": False}
|
||
|
||
session = new_session()
|
||
last_msg = ""
|
||
for attempt in range(1, config.RETRY_MAX + 1):
|
||
_log(f"登录第 {attempt}/{config.RETRY_MAX} 轮")
|
||
try:
|
||
code = ocr_code(fetch_code_image(session))
|
||
_log(f"图片验证码 OCR:{code or '识别失败'}")
|
||
except Exception as e:
|
||
last_msg = f"获取验证码异常:{e}"
|
||
_log(last_msg, "WARN")
|
||
continue
|
||
if not code:
|
||
last_msg = "本轮验证码未识别出来"
|
||
_log(last_msg, "WARN")
|
||
continue
|
||
|
||
try:
|
||
resp, raw = do_login(session, account, password, code)
|
||
except Exception as e:
|
||
last_msg = f"登录请求异常:{e}"
|
||
_log(last_msg, "WARN")
|
||
continue
|
||
|
||
if not isinstance(resp, dict):
|
||
last_msg = f"登录返回异常:{raw[:300]}"
|
||
_log(last_msg, "WARN")
|
||
continue
|
||
|
||
if resp.get("success"):
|
||
user = resp.get("user") or {}
|
||
token = str(user.get("token") or "")
|
||
if not token:
|
||
last_msg = "登录成功但未返回 user.token"
|
||
_log(last_msg, "WARN")
|
||
continue
|
||
_log(f"登录成功,token={token[:24]}...")
|
||
save_token(token)
|
||
return {"success": True, "token": token, "message": "登录成功", "relogin": True}
|
||
|
||
msg = str(resp.get("message") or "")
|
||
last_msg = f"登录失败:{msg or raw[:300]}"
|
||
_log(last_msg, "WARN")
|
||
|
||
if "双因子" in msg or resp.get("twoFactorValidationSwitch") == "T":
|
||
return {"success": False, "token": "", "message": "账号开启了双因子验证,无法自动登录", "relogin": False}
|
||
if "密码" in msg or "账号" in msg:
|
||
return {"success": False, "token": "", "message": f"账号或密码错误,已停止:{msg}", "relogin": False}
|
||
|
||
return {"success": False, "token": "", "message": last_msg or "登录失败", "relogin": False}
|