chore: 环境包依赖收敛到 requirements.txt,清理旧插件目录与 _pack.py

- build-python-env.ps1:白名单只留包名,版本统一从仓库根 requirements.txt 解析;-FromVenv 打包前加版本守卫校验 .venv 一致性,支持 -ShowDeps 只打印解析结果

- 桌面端发版SOP 同步新流程与历史坑(1.1.9 环境包、禁止用 -FromVenv 打补丁包)

- requirements.txt 补 pycryptodome 3.24.0;package-lock 版本对齐 1.10.8

- 删除已废弃的插件级 _pack.py(统一走 tools/agent_cli.py 打包)与旧英文目录 plugins/xq0077(已由 XQ0077 携程数据导出 取代)
This commit is contained in:
2026-11-09 18:46:35 +08:00
parent 46749aa711
commit 229e3e6878
16 changed files with 102 additions and 894 deletions
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "37du-electron-shell",
"version": "1.0.3",
"version": "1.10.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "37du-electron-shell",
"version": "1.0.3",
"version": "1.10.8",
"dependencies": {
"adm-zip": "^0.5.18",
"better-sqlite3": "12.4.1",
@@ -21,7 +21,8 @@ param(
[string]$EnvVersion = "1.0.0",
[switch]$FromVenv, # 从本地 .venv 全量打包(推荐,不联网)
[switch]$SkipLocal, # do NOT install into electron-shell/python-env/
[switch]$Force # re-download embeddable / get-pip
[switch]$Force, # re-download embeddable / get-pip
[switch]$ShowDeps # 只解析并打印依赖清单后退出(校验 requirements.txt 用,不打包)
)
$ErrorActionPreference = "Stop"
@@ -39,27 +40,85 @@ $EmbedZip = Join-Path $DownloadDir "python-$PythonVersion-embed-amd64.zip"
$GetPip = Join-Path $DownloadDir "get-pip.py"
$PipIndex = $null # e.g. "https://pypi.tuna.tsinghua.edu.cn/simple"
# All dependencies (top-level + key transitive), pinned to .venv-validated versions
$Pinned = @(
"requests==2.34.2", "python-dotenv==1.2.2", "cryptography==50.0.1", "pycryptodome==3.24.0",
"pandas==3.0.5", "numpy==2.3.5", "openpyxl==3.1.5",
"python-dateutil==2.9.0.post0", "tzdata==2026.3", "et-xmlfile",
"websocket-client==1.9.0",
"DrissionPage==4.1.1.4", "DrissionGet==1.2.1", "DrissionRecord==2.0.1",
"lxml==6.1.1", "psutil==7.2.2", "tldextract==5.3.2", "cssselect==1.5.0", "click==8.4.2",
"ddddocr==1.6.1", "onnxruntime==1.28.0", "Pillow==12.3.0",
"opencv-python-headless==5.0.0.93", "flatbuffers==25.12.19", "protobuf==7.35.1",
# ================== 依赖清单:版本唯一真源 = 仓库根 requirements.txt ==================
# 历史坑:这里曾硬编码一份 pin 列表(第三份清单),与 requirements.txt 长期漂移
# (numpy/pandas/onnxruntime 等都落后多个小版本),而 .venv 装的是 requirements 的版本,
# 导致「-FromVenv 打包」与「embeddable+pip 打包」产物不一致。
# 现在只维护「环境包需要哪些包」的白名单,版本一律从 requirements.txt 解析。
$ReqFile = Join-Path $Repo "requirements.txt"
if (-not (Test-Path $ReqFile)) { throw "缺少依赖清单:$ReqFile" }
$ReqVersion = @{}
foreach ($line in Get-Content -Path $ReqFile) {
if ($line -match '^\s*([A-Za-z0-9][A-Za-z0-9_.\-]*)\s*==\s*([^\s;#]+)') {
$ReqVersion[$matches[1].ToLower().Replace('_', '-').Replace('.', '-')] = $matches[2]
}
}
# 环境包白名单(只写包名,版本取自 requirements.txt)
$EnvPackages = @(
"requests", "python-dotenv", "cryptography", "pycryptodome",
"pandas", "numpy", "openpyxl",
"python-dateutil", "tzdata", "et-xmlfile",
"websocket-client",
"DrissionPage", "DrissionGet", "DrissionRecord",
"lxml", "psutil", "tldextract", "cssselect", "click",
"ddddocr", "onnxruntime", "Pillow",
"opencv-python-headless", "flatbuffers", "protobuf",
# OCR(XQ0003 请假附件:病假/结婚证/产检关键词与登记日期核验)
# rapidocr>=3 必须显式固定,连同 opencv_python/omegaconf 等运行依赖,否则
# 走 embeddable+pip 模式时该栈不会装、插件 OCR 全面降级为人工复核。
"rapidocr==3.9.2", "opencv-python==5.0.0.93",
"omegaconf==2.3.1", "antlr4-python3-runtime==4.9.3", "colorlog==6.12.0",
"pyclipper==1.4.0", "Shapely==2.1.2", "PyYAML==6.0.3", "tqdm==4.70.1",
"pywin32==312",
"urllib3==2.7.0", "certifi==2026.7.22", "idna==3.18",
"charset-normalizer==3.4.9", "six==1.17.0", "packaging==26.3"
"rapidocr", "opencv-python",
"omegaconf", "antlr4-python3-runtime", "colorlog",
"pyclipper", "Shapely", "PyYAML", "tqdm",
"pywin32",
"urllib3", "certifi", "idna",
"charset-normalizer", "six", "packaging"
)
$Pinned = @()
foreach ($p in $EnvPackages) {
$k = $p.ToLower().Replace('_', '-').Replace('.', '-')
if (-not $ReqVersion.ContainsKey($k)) { throw "requirements.txt 缺少环境包依赖:$p" }
$Pinned += "$p==$($ReqVersion[$k])"
}
Write-Host "依赖来源:requirements.txt(白名单 $($Pinned.Count) 个包)" -ForegroundColor DarkGray
# 版本守卫:本地 .venv 必须与 requirements.txt 一致(唯一真源),否则打出来的包会跟随
# 一个「没被记录」的版本。返回对象(用对象而非数组:PowerShell 里返回空数组会被展开成 $null):
# Found = $false 表示 .venv 不存在;否则 Drift 为漂移项数组。
function Get-VenvDrift([string]$VenvPath) {
$VenvPy = Join-Path $VenvPath "Scripts\python.exe"
if (-not (Test-Path $VenvPy)) { return [pscustomobject]@{ Found = $false; Drift = @() } }
$Frozen = @{}
& $VenvPy -m pip freeze 2>$null | ForEach-Object {
if ($_ -match '^([A-Za-z0-9][A-Za-z0-9_.\-]*)\s*==\s*([^\s]+)') {
$Frozen[$matches[1].ToLower().Replace('_', '-').Replace('.', '-')] = $matches[2]
}
}
$drift = @()
foreach ($p in $EnvPackages) {
$k = $p.ToLower().Replace('_', '-').Replace('.', '-')
$want = $ReqVersion[$k]
$have = $Frozen[$k]
if ($have -ne $want) { $drift += "$p .venv=$have / requirements.txt=$want" }
}
return [pscustomobject]@{ Found = $true; Drift = $drift }
}
if ($ShowDeps) {
$Pinned | ForEach-Object { Write-Host " $_" }
$guard = Get-VenvDrift (Join-Path $Repo ".venv")
if (-not $guard.Found) {
Write-Host " (.venv 不存在,跳过版本一致性校验)" -ForegroundColor DarkGray
} elseif ($guard.Drift.Count -eq 0) {
Write-Host " 版本守卫通过:.venv 与 requirements.txt 一致($($EnvPackages.Count) 个包)" -ForegroundColor Green
} else {
Write-Host " [!] 本地 .venv 与 requirements.txt 不一致:" -ForegroundColor Yellow
$guard.Drift | ForEach-Object { Write-Host " $_" -ForegroundColor Yellow }
}
Write-Host "(-ShowDeps:仅解析依赖,不执行打包)" -ForegroundColor Cyan
return
}
function Download-File([string]$Url, [string]$Dest) {
if (-not $Force -and (Test-Path $Dest) -and (Get-Item $Dest).Length -gt 0) {
Write-Host " cache hit: $Dest"
@@ -92,6 +151,16 @@ if ($FromVenv) {
-not (Test-Path (Join-Path $Venv "Lib\site-packages"))) {
throw "venv 打包所需目录缺失:基础解释器($BasePy) 或 .venv\Lib\site-packages"
}
# 版本守卫:本地 .venv 必须与 requirements.txt 一致(唯一真源),否则打出来的包会跟随
# 一个「没被记录」的版本。不一致时先 pip install -r requirements.txt 对齐再打包。
$guard = Get-VenvDrift $Venv
if (-not $guard.Found) {
Write-Host " 未发现 .venv,跳过版本一致性校验" -ForegroundColor DarkGray
} elseif ($guard.Drift.Count -gt 0) {
throw ("本地 .venv 与 requirements.txt 版本不一致,请先 pip install -r requirements.txt 对齐:`n " + ($guard.Drift -join "`n "))
} else {
Write-Host " 版本守卫通过:.venv 与 requirements.txt 一致($($EnvPackages.Count) 个包)"
}
Write-Host "base interpreter: $BasePy"
# 解释器 + 运行时 DLL + 标准库 + 扩展模块目录(DLLs/)
foreach ($f in @("python.exe", "python311.dll", "python3.dll",
+13 -2
View File
@@ -83,10 +83,21 @@ curl -s -H "X-API-Token: <CONTROLPLANE_TOKEN>" http://172.30.30.243:8800/api/she
```powershell
cd d:\work\code\37duAutomation\desktop\electron-shell
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 -EnvVersion 1.1.4
# 产物:dist-env\python-env-1.1.4.zip + .sha256,并本地安装到 python-env\1.1.4\ 供联调
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 -EnvVersion 1.1.9 -FromVenv
# 产物:dist-env\python-env-1.1.9.zip + .sha256,并本地安装到 python-env\1.1.9\ 供联调
# 只看依赖解析结果(不打包):加 -ShowDeps,会打印 41 个包版本 + .venv 一致性校验结果
```
**依赖版本唯一真源 = 仓库根 `requirements.txt`**(2026-11-09 收敛):
* 脚本里只维护「环境包需要哪些包」的白名单(`$EnvPackages`,仅包名),版本一律从 `requirements.txt` 解析,不再硬编码第三份清单;
* `-FromVenv` 打包前有**版本守卫**:`.venv` 里白名单包的版本与 `requirements.txt` 不一致会直接报错,提示先 `pip install -r requirements.txt` 对齐;
* 因此流程固定为:改依赖 → 改 `requirements.txt` → 本地 `pip install` → 打包;
* `.venv` 的 site-packages 是**全量**拷进环境包的,`.venv` 里装了什么包,环境包里就有什么,多余的历史依赖(如 1.1.7 里的 selenium/trio/screenvision 那一整棵树)会在重打包时自动消失。
⚠ 历史坑(勿回退):`-FromVenv` 与「embeddable + pip」两种模式产物必须一致;1.1.7 之前硬编码清单落后多个小版本(numpy 2.3.5/pandas 3.0.5/onnxruntime 1.28.0),与 `.venv` 分裂。
⚠ 若只想在上一版基础上打补丁(改 webhost 某个 `.py`),不要用 `-FromVenv` 重打全量包(会丢包/换版本),应解出上一版 zip、只替换目标文件后重新压缩。
```powershell
d:\work\code\37duAutomation\.venv\Scripts\python.exe tools\agent_cli.py `
--admin puddy --password 123456 --base http://172.30.30.243:8800 `
@@ -1,41 +0,0 @@
pt DistutilsExecError as msg:
raise CompileError(msg)
continue
elif ext in self._mc_extensions:
# Compile .MC to .RC file to .RES file.
# * '-h dir' specifies the directory for the
# generated include file
# * '-r dir' specifies the target directory of the
# generated RC file and the binary message resource
# it includes
#
# For now (since there are no options to change this),
# we use the source-directory for the include file and
# the build directory for the RC file and message
# resources. This works at least for win32all.
h_dir = os.path.dirname(src)
rc_dir = os.path.dirname(obj)
try:
# first compile .MC to .RC and .H file
self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])
base, _ = os.path.splitext(os.path.basename(src))
rc_file = os.path.join(rc_dir, base + '.rc')
# then compile .RC to .RES file
self.spawn([self.rc, "/fo" + obj, rc_file])
except DistutilsExecError as msg:
raise CompileError(msg)
continue
else:
# how to handle this file?
raise CompileError(f"Don't know how to compile {src} to {obj}")
args = [self.cc] + compile_opts + pp_opts
if add_cpp_opts:
args.append('/EHsc')
args.append(input_opt)
args.append("/Fo" + obj)
args.extend(extra_postargs)
try:
self.spawn
-75
View File
@@ -1,75 +0,0 @@
# -*- coding: utf-8 -*-
"""携程数据导出 - webhost 场景插件(XQ0077)
流程(纯接口,不使用浏览器):
1) 登录深大/lotsmall 管理端(图片验证码 OCR + RSA 密码加密;token 缓存复用);
2) statisticsSupport(取报表接入参数)→ verifySaasAuthCode(换 JWT)→ preview(取元数据);
3) searchFilter 先查询判有无数据,无数据直接跳过;有数据才 newExport 下载 xlsx
→ 检票员检票报表_YYYYMMDD_HHMMSS.xlsx。
"""
import os
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
from . import config
from .data import lotsmall_report
class TicketInspectorReportPlugin(ScenePlugin):
id = "xq0077"
name = "携程数据导出"
version = "1.0.2"
description = ("深大/lotsmall 管理端「检票员检票报表」导出:账密自动登录(图片验证码 OCR + RSA 密码加密),"
"纯接口查询判有无数据后导出 xlsx,日期口径固定昨天 00:00:00 ~ 今天 23:59:59")
platform = "" # 管理端自带账密登录,不使用底座共享登录态
uses_month = False
capabilities = ["xq0077"]
permissions = {"platforms": []}
# 与 plugin.json.fields 一致
fields = {
"account": {"type": "string", "title": "登录账号", "default": "",
"description": "深大/lotsmall 管理端账号(手机号或用户名)"},
"password": {"type": "string", "title": "登录密码", "default": "",
"description": "管理端登录密码(明文存本地配置)"},
"save_dir": {"type": "string", "title": "保存目录", "default": "",
"description": "留空=D:\\资料\\财务\\携程数据导出"},
"debug_mode": {"type": "boolean", "title": "调试日志", "default": False},
}
def run(self, fields, ctx) -> dict:
fields = fields or {}
config.set_log(ctx.log)
config.set_progress(ctx.progress)
config.set_debug(bool(fields.get("debug_mode")))
account = str(fields.get("account") or "").strip()
password = str(fields.get("password") or "").strip()
if not (account and password):
raise RuntimeError("请在插件界面填写深大/lotsmall 管理端的登录账号与密码")
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or config.default_output_dir()
os.makedirs(save_dir, exist_ok=True)
begin, end = config.date_window()
ctx.log(f"日期区间:{begin} ~ {end}")
ctx.log(f"保存目录:{save_dir}")
result = lotsmall_report.run_export(account, password, save_dir)
config.progress(100)
total = int(result.get("total") or 0)
file = result.get("file") or ""
date_range = f"{begin} ~ {end}"
if total <= 0 or not file:
return {
"summary": f"无数据,未导出({date_range})",
"detail": {"range": date_range, "total": 0, "save_dir": save_dir},
"path": save_dir,
}
return {
"summary": f"检票员检票报表导出完成:{os.path.basename(file)}({total} 条)",
"detail": {"range": date_range, "total": total, "file": file, "save_dir": save_dir},
"path": file,
}
PLUGINS.append(TicketInspectorReportPlugin())
-161
View File
@@ -1,161 +0,0 @@
# -*- coding: utf-8 -*-
"""xq0077 携程数据导出 插件 - 配置常量与全局钩子。
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
业务模块统一经 config.log() 输出日志(转发到 ctx.log,无 ctx 时回落到 print)。
站点(深大/lotsmall 管理端):
- 管理端 www.lotsmall.cn(/admin/api/checkCode 图片验证码 + /admin/storeMerchant/logining 账密登录,
返回 user.token 即管理端 tyAuthToken;statisticsSupport 换取报表接入参数);
- 报表平台 platform-report-sh1.zhiyoubao.com(换 JWT → preview → searchFilter → newExport)。
"""
import os
import time
from datetime import date, timedelta
# ==================== 站点与接口 ====================
ADMIN_BASE = 'https://www.lotsmall.cn'
REPORT_BASE = 'https://platform-report-sh1.zhiyoubao.com'
API_CHECKCODE = '/admin/api/checkCode' # 管理端图片验证码(JPEG 直出)
API_ADMIN_LOGIN = '/admin/storeMerchant/logining' # 管理端账密登录(返回 user.token)
API_STATISTICS_SUPPORT = '/statistics/webApi/statisticsSupport/'
API_VERIFY_SAAS = '/api/partner/auth/verifySaasAuthCode'
API_PREVIEW = '/api/report/preview/{report_id}'
API_SEARCH = '/api/report/searchFilter'
API_EXPORT = '/api/report/newExport'
# 登录页密码 RSA 公钥(PKCS#1 v1.5,平台前端硬编码,2026-11 实测;管理端与用户中心同一把)
RSA_PUBLIC_KEY = (
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI5kmdW9rmxQlTraZ6Wx+C7kYRDjL332N53dsqFsqq'
'T+PX6mosaM5hW4MS4vUbQNtUblhmQgzmUD0KBJFH9YZMmSPLdCC+G4r7d2PPFBrCy+9dFUMUNaT4Penya'
'VQJyAp3bhUJ7n93bRJT9jtxsdDwJ/Zl12A/kO93fr7+waaepwIDAQAB'
)
CAPTCHA_MIN_LEN = 3 # 管理端图片验证码长度范围(实测 4~5 位)
CAPTCHA_MAX_LEN = 6
# 管理端 token 失效(请跳转到登录页)
CODE_TOKEN_EXPIRED = 1004001011
CODE_OK = 200
# ==================== 报表(检票员检票报表) ====================
REPORT_ID = 3066
REPORT_NAME = '检票员检票报表'
REPORT_URL = f'https://platform-report-sh1.zhiyoubao.com/reportView?id={REPORT_ID}'
# 报表查询固定入参(平台页面实测值)
TERMINAL_TPE = '0'
MERCHANT_ID = '23985'
USER_INFO_ID = '59567'
SUB_ACCOUNT_ID = '59925'
ROLE_TYPE = '4'
APP_ID_DEFAULT = 'xj'
PAGE_INDEX = 1
PAGE_SIZE = 50
# ==================== 输出路径 ====================
DEFAULT_SAVE_DIR = r'D:\资料\财务\携程数据导出'
def _app_data_dir():
return os.path.join(
os.environ.get('LOCALAPPDATA') or os.environ.get('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'lotsmall_token.json') # {"accessToken": ...}
def default_output_dir():
"""默认输出目录。"""
return DEFAULT_SAVE_DIR
# ==================== 日期口径(固定规则) ====================
def date_window():
"""返回 (起, 止) 时间字符串:昨天 00:00:00 ~ 今天 23:59:59。"""
today = date.today()
prev = today - timedelta(days=1)
return f'{prev:%Y-%m-%d} 00:00:00', f'{today:%Y-%m-%d} 23:59:59'
def export_filename():
"""导出文件名:检票员检票报表_YYYYMMDD_HHMMSS.xlsx。"""
return f'{REPORT_NAME}_{time.strftime("%Y%m%d_%H%M%S")}.xlsx'
# ==================== 运行参数(项目规范:全局重试 3 次) ====================
RETRY_MAX = 3 # 接口请求/验证码轮次重试
TIMEOUT = 30 # 普通接口超时
DOWNLOAD_TIMEOUT = 180 # 导出 xlsx 下载超时
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'Chrome/120.0.0.0 Safari/537.36')
# ==================== 全局钩子(run() 启动时注入) ====================
_log = None
_progress = None
_debug = False
def set_log(fn):
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
global _log
_log = fn
def log(msg, level="INFO"):
if level == "DEBUG" and not _debug:
return
if _log:
_log(str(msg), level)
else:
print(f"[{level}] {msg}")
class _ModuleLogger:
"""模块级 logger 适配:统一转发到 config.log。"""
@staticmethod
def debug(msg, *args):
log(msg % args if args else msg, "DEBUG")
@staticmethod
def info(msg, *args):
log(msg % args if args else msg, "INFO")
@staticmethod
def warning(msg, *args):
log(msg % args if args else msg, "WARN")
@staticmethod
def error(msg, *args):
log(msg % args if args else msg, "ERROR")
logger = _ModuleLogger()
def set_progress(fn):
"""注入 ctx.progress。"""
global _progress
_progress = fn
def progress(pct):
"""上报进度(0~100);无 ctx 或异常时静默忽略,不影响主流程。"""
if not _progress:
return
try:
_progress(max(0, min(100, int(pct))))
except Exception:
pass
def set_debug(flag):
global _debug
_debug = bool(flag)
def is_debug():
return _debug
-2
View File
@@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
"""xq0077 携程数据导出 - 数据层(登录 + 检票员检票报表导出)。"""
-222
View File
@@ -1,222 +0,0 @@
# -*- 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}
-222
View File
@@ -1,222 +0,0 @@
# -*- coding: utf-8 -*-
"""xq0077 携程数据导出 - 检票员检票报表导出(纯接口,自包含)。
链路(2026-11 实测):
statisticsSupport(管理端 token 换 authCode/appId/sign/timestamp/userCode/corpCode)
→ verifySaasAuthCode(换报表平台 JWT)
→ preview(取 reportDetailId 与 reportColumnList)
→ searchFilter(查询,判 total)
→ total > 0 才 newExport(下载 xlsx 二进制)。
日期口径固定:昨天 00:00:00 ~ 今天 23:59:59;
查询无数据(total 为 0 或缺失)直接跳过导出,返回 {"total": 0, "file": ""}。
"""
import os
import time
import urllib.parse
import requests
from .. import config
from . import lotsmall_login
class AuthError(RuntimeError):
"""账密错误/配置缺失:不可重试(避免锁号)。"""
def _log(msg, level="INFO"):
config.log(msg, level)
# ==================== 报表平台会话 ====================
def _report_session():
session = requests.Session()
session.headers.update({
"User-Agent": config.UA,
"Origin": config.REPORT_BASE,
"Referer": config.REPORT_BASE + "/",
})
return session
def _verify_saas(session, auth_code, app_id):
"""authCode/appId 换报表平台 JWT。"""
resp = session.get(config.REPORT_BASE + config.API_VERIFY_SAAS,
params={"authCode": auth_code, "appId": app_id},
timeout=config.TIMEOUT)
try:
body = resp.json()
except ValueError:
raise RuntimeError(f"verifySaasAuthCode 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
result = body.get("result") or {}
jwt = (result.get("token") or result.get("accessToken")
or (body.get("data") or {}).get("token"))
if not jwt:
raise RuntimeError(f"未取到 JWT:{str(body)[:300]}")
return jwt
def _auth_headers(info, app_id, jwt):
"""报表平台后续接口统一请求头(除 JWT 外还要带 authCode/appId/timestamp/sign)。"""
return {
"authCode": info["authCode"],
"appId": app_id,
"timestamp": str(info["timestamp"]),
"sign": info["sign"],
"Authorization": jwt,
"Content-Type": "application/json",
"Origin": config.REPORT_BASE,
"Referer": config.REPORT_BASE + "/",
}
def _preview(session, info, app_id, headers):
"""取报表元数据:reportDetailId 与 reportColumnList。"""
params = {
"authCode": info["authCode"],
"appId": app_id,
"sign": info["sign"],
"timestamp": info["timestamp"],
"userCode": info.get("bigDataLoginAuthCode"),
"corpCode": info.get("corpCode"),
"terminalTpe": 0,
}
url = config.REPORT_BASE + config.API_PREVIEW.format(report_id=config.REPORT_ID)
resp = session.get(url, params=params, headers=headers, timeout=config.TIMEOUT)
try:
body = resp.json()
except ValueError:
raise RuntimeError(f"preview 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
result = body.get("result") or {}
detail_id = result.get("reportDetailId") or result.get("id")
columns = result.get("reportColumnList") or []
if not detail_id:
raise RuntimeError(f"preview 未返回 reportDetailId:{str(body)[:300]}")
return detail_id, columns
def _query_body(info, app_id, detail_id, columns, begin, end):
"""searchFilter / newExport 共用请求体(newExport 再追加 reportColumnFilterList)。"""
return {
"shareMode": 0,
"reportType": 0,
"id": detail_id,
"params": {
"terminalTpe": config.TERMINAL_TPE,
"merchant_id": config.MERCHANT_ID,
"userInfoId": config.USER_INFO_ID,
"corpCode": info.get("corpCode"),
"appId": app_id,
"userCode": info.get("bigDataLoginAuthCode"),
"subAccountId": config.SUB_ACCOUNT_ID,
"roleType": config.ROLE_TYPE,
"pageIndex": config.PAGE_INDEX,
"pageSize": config.PAGE_SIZE,
"beginTradeDate": begin,
"endTradeDate": end,
"id": str(config.REPORT_ID),
},
"reportColumnDisplayList": columns,
}
def _search(session, headers, body):
"""查询报表,返回 total(0 或缺省即无数据)。"""
resp = session.post(config.REPORT_BASE + config.API_SEARCH,
headers=headers, json=body, timeout=config.TIMEOUT)
try:
result = (resp.json() or {}).get("result") or {}
except ValueError:
raise RuntimeError(f"searchFilter 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
items = result.get("reportSearchList") or []
first = items[0] if items else {}
try:
total = int(first.get("total") or 0)
except (TypeError, ValueError):
total = 0
_log(f"查询结果:total={total},rows={len(first.get('rows') or [])}"
f"({config.PAGE_SIZE} 条/页仅用于探测,导出为全量)")
return total
def _export(session, headers, body, save_dir):
"""下载 xlsx 并落盘,返回文件路径。"""
resp = session.post(config.REPORT_BASE + config.API_EXPORT,
headers=headers, json=body, timeout=config.DOWNLOAD_TIMEOUT)
if resp.content[:2] != b'PK':
raise RuntimeError(f"导出返回非 xlsx(HTTP {resp.status_code}):{resp.text[:300]}")
cd = resp.headers.get("content-disposition") or ""
if "filename=" in cd:
server_name = cd.split("filename=", 1)[1].strip().strip('"')
_log(f"服务端文件名:{urllib.parse.unquote(server_name)}")
path = os.path.join(save_dir, config.export_filename())
with open(path, 'wb') as f:
f.write(resp.content)
_log(f"导出完成 → {path}({len(resp.content)} bytes)")
return path
# ==================== 主入口 ====================
def run_export(account, password, save_dir=''):
"""查询并导出「检票员检票报表」。
返回:{'total': 查询总数, 'file': 落盘路径(无数据时为空字符串)}
登录/接口失败抛 RuntimeError(账密错误立即停止,不重试)。
"""
save_dir = (save_dir or '').strip().strip('"') or config.default_output_dir()
os.makedirs(save_dir, exist_ok=True)
begin, end = config.date_window()
_log(f"日期区间:{begin} ~ {end}")
_log(f"保存目录:{save_dir}")
config.progress(5)
last_err = None
for attempt in range(1, config.RETRY_MAX + 1):
try:
# 1) 登录(优先复用缓存 token)
login = lotsmall_login.ensure_login(account, password, force=(attempt > 1))
if not login.get("success"):
msg = login.get("message") or "登录失败"
if "账号或密码错误" in msg or "缺失" in msg:
raise AuthError(msg)
raise RuntimeError(f"登录失败:{msg}")
info = lotsmall_login.fetch_report_params(login.get("token"))
if not info:
raise RuntimeError("取不到报表接入参数(token 可能已失效)")
app_id = str(info.get("appId") or config.APP_ID_DEFAULT)
for key in ("authCode", "sign", "timestamp"):
if not info.get(key):
raise RuntimeError(f"statisticsSupport 缺少 {key}:{str(info)[:300]}")
config.progress(25)
# 2) 换 JWT → preview
session = _report_session()
jwt = _verify_saas(session, info["authCode"], app_id)
headers = _auth_headers(info, app_id, jwt)
detail_id, columns = _preview(session, info, app_id, headers)
_log(f"报表元数据:reportDetailId={detail_id},列数={len(columns)}")
config.progress(45)
# 3) 查询判有无数据(无数据跳过导出)
body = _query_body(info, app_id, detail_id, columns, begin, end)
total = _search(session, headers, body)
if total <= 0:
_log("查询无数据,跳过导出")
config.progress(100)
return {'total': 0, 'file': ''}
config.progress(65)
# 4) 导出
body["reportColumnFilterList"] = [{"reportDetailId": detail_id}]
path = _export(session, headers, body, save_dir)
config.progress(100)
return {'total': total, 'file': path}
except AuthError:
raise
except Exception as e:
last_err = e
_log(f"第 {attempt}/{config.RETRY_MAX} 次导出失败:{e}", "WARN")
time.sleep(1)
raise RuntimeError(f"检票员检票报表导出失败(重试 {config.RETRY_MAX} 次耗尽):{last_err}")
-51
View File
@@ -1,51 +0,0 @@
{
"schema_version": 1,
"id": "xq0077",
"name": "携程数据导出",
"version": "1.0.2",
"description": "深大/lotsmall 管理端「检票员检票报表」导出:账密自动登录(图片验证码 OCR + RSA 密码加密),纯接口查询判有无数据后导出 xlsx,日期口径固定昨天 00:00:00 ~ 今天 23:59:59。登录 token 缓存复用,密码错误立即停止避免锁号。",
"category": "财务",
"icon": "",
"platform": "",
"uses_month": false,
"ui": true,
"capabilities": [
"xq0077"
],
"permissions": {
"platforms": []
},
"fields": {
"type": "object",
"properties": {
"account": {
"type": "string",
"title": "登录账号",
"default": "",
"description": "深大/lotsmall 管理端账号(手机号或用户名)"
},
"password": {
"type": "string",
"title": "登录密码",
"default": "",
"description": "管理端登录密码(明文存本地配置)"
},
"save_dir": {
"type": "string",
"title": "保存目录",
"default": "D:\\资料\\财务\\携程数据导出",
"description": "导出的 xlsx 统一输出目录"
},
"debug_mode": {
"type": "boolean",
"title": "调试日志",
"default": false,
"description": "开启后输出完整调试日志(默认关闭)"
}
},
"required": [
"account",
"password"
]
}
}
-5
View File
@@ -1,5 +0,0 @@
requests>=2.28
cryptography>=39.0
ddddocr>=1.4
opencv-python-headless>=4.8
numpy>=1.24
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-13
View File
@@ -1,13 +0,0 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>携程数据导出</title>
<script type="module" crossorigin src="/pui/xq0077/assets/index-B5bAs3Hl.js"></script>
<link rel="stylesheet" crossorigin href="/pui/xq0077/assets/index-CXuG8RKx.css">
</head>
<body>
<div id="app"></div>
</body>
</html>
+1
View File
@@ -43,6 +43,7 @@ proxy_tools==0.1.0
psutil==7.2.2
pyclipper==1.4.0
pycparser==3.0
pycryptodome==3.24.0
pydantic==2.13.5
pydantic_core==2.46.5
pyinstaller==6.22.3