refactor: 重构为可部署到服务器的模块化结构(v5.0.0)
- 拆包 fengxiang/:config/client/store/notify/monitor/admin/tts,统一入口 order_monitor.py - 服务器形态:Docker 常驻,Cookie 由本机登录后 POST 上传并热加载,不再依赖桌面弹窗 - 修复:首次启动重推历史订单、speak() 阻塞主循环、夜间 sleep 10h 不可中断 - 修复:test_push.py 残留 miservice 依赖(小爱已移除)、run_monitor.bat 写死盘符 - 配置化:webhook/shopId 移出源码(环境变量 > config.yaml > 默认值) - 可观测:滚动文件日志 + /healthz + Docker HEALTHCHECK + 告警冷却 - 飞书通道保留配置位,默认关闭(原 token 已失效 code=19001) - 新增 22 项单元测试(不联网)
This commit is contained in:
1 parent
ab6a2bb7ea
commit
4ee30399bf
30 files changed
+2404
-819
No files matched your search
@@ -0,0 +1,20 @@
|
|||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
*.pyo
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
data/
|
||||||
|
logs/
|
||||||
|
tests/
|
||||||
|
*.md
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
config.yaml
|
||||||
|
cookies.json
|
||||||
|
state.json
|
||||||
|
requirements-local.txt
|
||||||
|
run.bat
|
||||||
|
*.bat
|
||||||
|
setup_autostart.ps1
|
||||||
+18
-2
@@ -1,5 +1,13 @@
|
|||||||
# Sensitive
|
# 凭据与运行数据(绝不入库)
|
||||||
|
config.yaml
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
cookies.json
|
cookies.json
|
||||||
|
state.json
|
||||||
|
data/
|
||||||
|
logs/
|
||||||
|
|
||||||
|
# 旧版本遗留
|
||||||
xiaomi_config.json
|
xiaomi_config.json
|
||||||
xiaomi_raw_cookies.json
|
xiaomi_raw_cookies.json
|
||||||
order_data.json
|
order_data.json
|
||||||
@@ -7,6 +15,14 @@ order_data.json
|
|||||||
# Python
|
# Python
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
|
*.pyo
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
.pytest_cache/
|
||||||
|
|
||||||
# IDE
|
# IDE / 系统
|
||||||
.claude/
|
.claude/
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -1,78 +1,42 @@
|
|||||||
# 丰享订单监控项目
|
# 丰享订单监控 —— 项目上下文(给 AI 协作用)
|
||||||
|
|
||||||
## 项目概述
|
## 一句话
|
||||||
|
监控丰享商家端(fs.szfx.com)新订单 → 推企业微信。本机负责登录(过腾讯验证码),
|
||||||
|
服务器 Docker 负责 7×24 轮询与推送。
|
||||||
|
|
||||||
自动监控丰享商家端(fs.szfx.com)的新订单,同时推送到企业微信、飞书群和本地TTS语音播报**。
|
## 运行形态
|
||||||
|
- 本机 Windows:`run.bat` 跑 `order_monitor.py`;`login.bat` 跑 `fengxiang_scraper.py` 登录并上传 Cookie
|
||||||
|
- 服务器:`/data/docker/fengxiang-monitor`,容器 `fengxiang-monitor`,宿主机 `52100` → 容器 `8089`
|
||||||
|
- 生产只启用企业微信通道;飞书配置位保留但默认关闭(原 token 已失效,`code=19001`)
|
||||||
|
|
||||||
## 文件说明
|
## 代码约定
|
||||||
|
- 包 `fengxiang/`,配置三级覆盖:**环境变量 > config.yaml > config.py 的 DEFAULTS**
|
||||||
|
- 密钥(webhook、admin token)只能出现在 `config.yaml` / `.env`,绝不写进源码
|
||||||
|
- 异常分三类:`SessionExpired`(要登录)/ `ApiError`(业务错误码)/ `NetworkError`(可重试)
|
||||||
|
- 状态用 `store.State`:`last_order_id` + `pushed_ids` 双保险去重,写入必须原子(tmp + os.replace)
|
||||||
|
- 推送失败不能抛到主循环;告警必须经过 `Dispatcher.alert` 的冷却
|
||||||
|
- 主循环任何异常都要兜住(`except Exception` 记日志后继续),进程不能死
|
||||||
|
- TTS 只在 `sys.platform == "win32"` 且 `tts.enabled` 时启用
|
||||||
|
|
||||||
| 文件 | 用途 |
|
## 关键业务规则
|
||||||
|------|------|
|
1. 首次启动只建基线,**不推历史订单**
|
||||||
| `order_monitor.py` | 主程序:监控订单 + 企业微信 + 飞书 + 本地TTS播报 |
|
2. 积压 > `bulk_summary_threshold`(默认 5)时发一条汇总,不逐条推
|
||||||
| `push_latest_order.py` | 单次获取最新订单并推送企业微信 |
|
3. 夜间 21:00–07:40 分片休眠(每 60s 醒一次),期间仍响应 Cookie 更新与停止信号
|
||||||
| `fetch_orders.py` | 复用 Cookie 获取订单数据(命令行) |
|
4. Cookie 文件变化自动热重载,无需重启容器
|
||||||
| `fengxiang_scraper.py` | 首次登录获取 Cookie(Playwright 半自动) |
|
5. 会话失效 → 告警(30min 冷却)→ 阻塞等待新 Cookie → 自动恢复并回推恢复通知
|
||||||
| `cookies.json` | 丰享平台的登录 Cookie |
|
|
||||||
| `order_data.json` | 订单数据样例 |
|
|
||||||
|
|
||||||
## 已逆向的 API
|
## 常用命令
|
||||||
|
```bash
|
||||||
### 丰享平台
|
python -m unittest discover -s tests -v # 22 项测试,不联网
|
||||||
|
python fetch_orders.py 1 5 # 调试取单
|
||||||
- **登录**: `POST https://fspass.szfx.com/api/login`
|
python push_latest_order.py --dry # 调试推送
|
||||||
- 参数: `uname`(手机号), `upass`(密码Base64反转), `ticket`, `randstr`(腾讯验证码)
|
docker compose up -d --build && docker compose logs -f
|
||||||
- 登录后通过 `https://fs.szfx.com/saasmerchant/setstoken` 设置 Cookie
|
curl -s localhost:52100/healthz
|
||||||
- Cookie 保存在浏览器中,主要: `USS`, `PTOKEN`, `CPTOKEN`, `STOKEN`
|
|
||||||
|
|
||||||
- **订单列表**: `POST https://fs.szfx.com/saasmerchant/pcweb/order/quickpayorder/list`
|
|
||||||
- Content-Type: application/json
|
|
||||||
- Body: `{"shopId": "20434543575189", "page": 1, "pageSize": 20}`
|
|
||||||
- 需要登录 Cookie,未登录返回 `errno: 110003`
|
|
||||||
- 返回: `{errno: 0, data: {total, list: [...], count}}`
|
|
||||||
|
|
||||||
- **关键字段**:
|
|
||||||
- `shopId`: `20434543575189` (益选便利店)
|
|
||||||
- `orderId`: 订单号
|
|
||||||
- `amountPayable`: 实付金额(单位:分)
|
|
||||||
- `allPrice`: 订单金额(单位:分)
|
|
||||||
- `shopName`, `city`, `companyName`, `workplaceName`: 业务信息
|
|
||||||
- `createTime`, `payTime`, `finishTime`: 时间戳(秒)
|
|
||||||
|
|
||||||
### 本地 TTS(IndexTTS2)
|
|
||||||
|
|
||||||
- 使用本地部署的 IndexTTS2 模型,无需联网
|
|
||||||
- 模型路径: `E:\2025Code\python\IndexTT\index-tts\`
|
|
||||||
- 语音样本: `examples/voice_01.wav`
|
|
||||||
- 封装模块: `local_tts.py`
|
|
||||||
- 调用方式: `_local_speak(text)` → 合成 WAV → 本地播放
|
|
||||||
|
|
||||||
### 企业微信 Webhook
|
|
||||||
- URL: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=644ab6d9-3b66-4166-88e9-5a8a89e3731d`
|
|
||||||
- 只能发消息,不能收消息
|
|
||||||
|
|
||||||
## order_monitor.py 核心逻辑
|
|
||||||
|
|
||||||
1. Playwright 打开浏览器,用户手动登录丰享平台
|
|
||||||
2. 登录成功后,通过浏览器页面的 `fetch()` 调用订单 API(复用浏览器会话,最自然)
|
|
||||||
3. 每次拉取最近 N 条订单,和上次最新订单号对比,找出所有新订单
|
|
||||||
4. 新订单同时推送企业微信 + 飞书 + 本地TTS播报
|
|
||||||
5. 高峰期(11-13点、17-19点)10-20秒轮询,闲时 30-60 秒
|
|
||||||
6. 每 5 分钟刷新页面防 Session 过期
|
|
||||||
7. Session 过期自动检测 → 通知企业微信 → 等待用户重新登录
|
|
||||||
|
|
||||||
## 消息格式
|
|
||||||
|
|
||||||
- 企业微信: `【丰享丰食】订单收款成功,收款24.00元`
|
|
||||||
- 本地TTS: 同上文案语音播报
|
|
||||||
|
|
||||||
## 已安装的依赖
|
|
||||||
|
|
||||||
```
|
|
||||||
pip install playwright requests
|
|
||||||
playwright install chromium
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 注意事项
|
## 已知坑
|
||||||
|
- 丰享接口是逆向的,`errno` 含义可能变;会话失效码目前 `{110003, 10009}`
|
||||||
- 丰享登录有**腾讯验证码 TCaptcha**,无法纯接口绕过,必须用 Playwright 浏览器登录
|
- 未配置 `admin.token` 时写接口只允许 127.0.0.1(避免裸奔)
|
||||||
- Windows 终端输出中文会乱码,但实际发送的内容是正确的 UTF-8
|
- 单实例:状态文件无锁,同店铺不要起两个容器
|
||||||
|
- `amountPayable` 单位是**分**,展示要 /100
|
||||||
|
- 原仓库历史里有明文 webhook,已迁到配置;改动提交时不要再写回源码
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
# 丰享订单监控 —— 生产镜像
|
||||||
|
# 只装运行必需的依赖;Playwright / torch / IndexTTS2 都不进镜像(服务器上用不到)
|
||||||
|
|
||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
ENV PYTHONUNBUFFERED=1 \
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PIP_NO_CACHE_DIR=1 \
|
||||||
|
TZ=Asia/Shanghai \
|
||||||
|
FX_DATA_DIR=/app/data \
|
||||||
|
FX_CONFIG=/app/config.yaml
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends tzdata ca-certificates curl \
|
||||||
|
&& rm -rf /var/lib/apt/lists/* \
|
||||||
|
&& useradd --create-home --uid 10001 app
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY fengxiang ./fengxiang
|
||||||
|
COPY order_monitor.py fetch_orders.py push_latest_order.py healthcheck.py ./
|
||||||
|
|
||||||
|
RUN mkdir -p /app/data && chown -R app:app /app
|
||||||
|
|
||||||
|
USER app
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
EXPOSE 8089
|
||||||
|
|
||||||
|
# 健康检查看的是"是否还在轮询",不是端口是否通
|
||||||
|
HEALTHCHECK --interval=60s --timeout=10s --start-period=60s --retries=3 \
|
||||||
|
CMD ["python", "healthcheck.py"]
|
||||||
|
|
||||||
|
CMD ["python", "order_monitor.py"]
|
||||||
@@ -1,63 +1,174 @@
|
|||||||
# 丰享订单监控
|
# 丰享订单监控 v5
|
||||||
|
|
||||||
自动监控丰享商家端(fs.szfx.com)新订单,同时推送到**企业微信**、**飞书群**并进行**本地TTS语音播报**。
|
监控丰享商家端(fs.szfx.com)新订单,实时推送到企业微信;可选本地语音播报。
|
||||||
|
支持两种运行形态:**Windows 本机** 和 **Linux 服务器 Docker 常驻**。
|
||||||
|
|
||||||
## 快速开始
|
---
|
||||||
|
|
||||||
双击 `run.bat` 启动。首次运行会自动打开浏览器登录丰享平台,后续复用 Cookie 无需反复登录。
|
## 1. 架构
|
||||||
|
|
||||||
## 文件说明
|
```
|
||||||
|
┌──────────────────────────────┐
|
||||||
|
本机 Windows │ fengxiang_scraper.py │
|
||||||
|
(人工过验证码) │ Playwright 登录 → Cookie │
|
||||||
|
└───────────┬──────────────────┘
|
||||||
|
│ POST /api/cookies(token 鉴权)
|
||||||
|
▼
|
||||||
|
服务器 Docker ┌──────────────────────────────┐
|
||||||
|
fengxiang-monitor │ admin.py :8089 /healthz │
|
||||||
|
│ monitor.py 主循环 │
|
||||||
|
│ ├─ client.py → 丰享订单 API │ ← 5~10s 轮询
|
||||||
|
│ ├─ store.py 状态去重 │
|
||||||
|
│ └─ notify.py → 企业微信 │
|
||||||
|
└──────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
| 文件 | 用途 |
|
- **为什么登录必须在本地**:丰享登录挂腾讯 TCaptcha,无法纯接口绕过;服务器上没有桌面。
|
||||||
|
所以「人工过验证码」留在本机,登录成功后把 Cookie 推给服务器,服务器热加载,无需重启。
|
||||||
|
- **为什么不用 TTS 跑在服务器**:IndexTTS2 依赖 torch + GPU + 声卡,容器里跑不了。
|
||||||
|
服务器只负责推送,手机端企业微信本身就有提示音。需要喇叭播报时另见 §7。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 快速开始(Windows 本机)
|
||||||
|
|
||||||
|
```bat
|
||||||
|
python -m pip install -r requirements-local.txt
|
||||||
|
playwright install chromium
|
||||||
|
copy config.example.yaml config.yaml :: 填 notify.wecom.webhook
|
||||||
|
run.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
- `run.bat`:启动监控(自动识别 `.venv` / IndexTTS2 环境 / 系统 Python)
|
||||||
|
- `login.bat`:登录丰享并把 Cookie 上传到服务器(仅服务器形态需要)
|
||||||
|
- `setup_autostart.ps1`:注册开机自启任务计划
|
||||||
|
|
||||||
|
## 3. 部署到服务器(Docker)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 服务器上
|
||||||
|
mkdir -p /data/docker/fengxiang-monitor && cd /data/docker/fengxiang-monitor
|
||||||
|
# 上传代码后:
|
||||||
|
cp config.example.yaml config.yaml
|
||||||
|
vi config.yaml # 填 admin.token(必填,用于接收 Cookie)
|
||||||
|
|
||||||
|
cat > .env <<'EOF'
|
||||||
|
FX_WECOM_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx
|
||||||
|
FX_ADMIN_TOKEN=改成足够长的随机串
|
||||||
|
EOF
|
||||||
|
|
||||||
|
docker compose up -d --build
|
||||||
|
docker compose ps # STATUS 应为 healthy
|
||||||
|
curl -s localhost:52100/healthz | python3 -m json.tool
|
||||||
|
```
|
||||||
|
|
||||||
|
首次部署后必须在本地跑一次 `login.bat`(或 `fengxiang_scraper.py --upload`)把 Cookie 推上去,
|
||||||
|
否则监控会一直停在「等待 Cookie」状态。
|
||||||
|
|
||||||
|
## 4. 目录与文件
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `order_monitor.py` | 主程序:监控订单 + 企业微信/飞书推送 + 本地TTS播报 |
|
| `order_monitor.py` | 统一入口(本地 / 容器共用) |
|
||||||
| `local_tts.py` | 本地 TTS 封装模块(基于 IndexTTS2) |
|
| `fengxiang/config.py` | 配置加载:环境变量 > config.yaml > 默认值 |
|
||||||
| `run.bat` | 一键启动脚本 |
|
| `fengxiang/client.py` | 丰享 API 客户端(连接复用、重试、异常分类) |
|
||||||
| `push_latest_order.py` | 单次获取最新订单并推送 |
|
| `fengxiang/monitor.py` | 主循环:轮询调度、夜间暂停、Cookie 热重载 |
|
||||||
| `fetch_orders.py` | 复用 Cookie 获取订单数据(命令行) |
|
| `fengxiang/store.py` | 状态持久化(最新订单号 + 去重集合,原子写) |
|
||||||
| `fengxiang_scraper.py` | 首次登录获取 Cookie(Playwright 半自动) |
|
| `fengxiang/notify.py` | 通知通道(企业微信 / 飞书,可插拔 + 告警冷却) |
|
||||||
| `cookies.json` | 丰享平台登录 Cookie(自动生成) |
|
| `fengxiang/admin.py` | 管理接口:`/healthz`、`/api/cookies`、`/api/test-push` |
|
||||||
|
| `fengxiang/tts.py` | 本地播报队列(仅 Windows,容器自动禁用) |
|
||||||
|
| `fengxiang_scraper.py` | 本机登录 + 上传 Cookie |
|
||||||
|
| `fetch_orders.py` / `push_latest_order.py` | 调试工具:取单 / 单次推送 |
|
||||||
|
| `healthcheck.py` | 容器健康检查(判断是否还在轮询) |
|
||||||
|
| `tests/test_core.py` | 22 项单元测试,不联网 |
|
||||||
|
|
||||||
## 运行环境
|
运行数据都在 `data/`(容器内 `/app/data`):`cookies.json`、`state.json`、`logs/monitor.log`。
|
||||||
|
|
||||||
- Python 虚拟环境: `E:\2025Code\python\IndexTT\index-tts\.venv`
|
## 5. 管理接口
|
||||||
- 依赖: `playwright`、`requests`
|
|
||||||
- 浏览器: Chromium(Playwright 自动管理)
|
|
||||||
- TTS 模型: IndexTTS2(本地部署,首次加载需 1-2 分钟)
|
|
||||||
|
|
||||||
## 通知渠道
|
| 接口 | 鉴权 | 用途 |
|
||||||
|
|------|------|------|
|
||||||
|
| `GET /healthz`(= `/api/status`) | 否 | 运行状态,Docker HEALTHCHECK 用 |
|
||||||
|
| `POST /api/cookies` | 是 | 更新 Cookie,立即校验并热生效 |
|
||||||
|
| `POST /api/test-push` | 是 | 发一条测试消息验证通道 |
|
||||||
|
|
||||||
| 渠道 | 说明 |
|
鉴权:`X-Auth-Token: <token>` 或 `Authorization: Bearer <token>` 或 `?token=`。
|
||||||
|------|------|
|
未配置 token 时**只允许 127.0.0.1** 调用写接口(安全默认)。
|
||||||
| 企业微信 | Webhook 推送消息 |
|
|
||||||
| 飞书群 | Webhook 推送消息 |
|
|
||||||
| 本地 TTS | IndexTTS2 合成语音 + 扬声器播放 |
|
|
||||||
|
|
||||||
## 轮询策略
|
```bash
|
||||||
|
curl -s localhost:52100/healthz
|
||||||
|
curl -X POST localhost:52100/api/test-push -H "X-Auth-Token: $T" -d '{"text":"测试"}'
|
||||||
|
```
|
||||||
|
|
||||||
| 时段 | 间隔 | 拉取数量 |
|
`/healthz` 返回:
|
||||||
|------|------|---------|
|
|
||||||
| 高峰期 11:00-13:00, 17:00-19:00 | 5-10秒 | 20条 |
|
|
||||||
| 闲时 | 5-10秒 | 5条 |
|
|
||||||
| 夜间 21:00-07:40 | 自动暂停 | — |
|
|
||||||
|
|
||||||
## 消息格式
|
```json
|
||||||
|
{"app":"fengxiang-monitor","mode":"peak","cookie_valid":true,"cookie_age_sec":120,
|
||||||
|
"last_order_id":"...","last_poll_age_sec":3,"total_pushed":42,"uptime_sec":3600}
|
||||||
|
```
|
||||||
|
|
||||||
- 推送: `【丰享丰食】订单收款成功,收款24.00元`
|
`mode`:`peak` / `idle` / `night`。`cookie_age_sec` 超过 7 天就要留意续期。
|
||||||
- TTS: 同上文案语音播报
|
|
||||||
|
|
||||||
## 已逆向 API
|
## 6. 运维手册
|
||||||
|
|
||||||
### 丰享平台
|
**Cookie 过期(最常见)**
|
||||||
|
1. 企业微信会收到「登录已失效」告警(30 分钟冷却,不会刷屏)
|
||||||
|
2. 本机跑 `login.bat`(或 `fengxiang_scraper.py --upload`)
|
||||||
|
3. 服务器收到后自动恢复,并回推一条「监控恢复,中断约 N 分钟」
|
||||||
|
|
||||||
- **登录**: `POST https://fspass.szfx.com/api/login`
|
**查日志**
|
||||||
- 腾讯验证码 TCaptcha,必须浏览器手动登录
|
```bash
|
||||||
- **订单列表**: `POST https://fs.szfx.com/saasmerchant/pcweb/order/quickpayorder/list`
|
docker logs -f --tail 100 fengxiang-monitor
|
||||||
- Body: `{"shopId": "20434543575189", "page": 1, "pageSize": 20}`
|
docker exec fengxiang-monitor tail -f /app/data/logs/monitor.log
|
||||||
- 返回: `{errno: 0, data: {total, list: [...], count}}`
|
```
|
||||||
|
|
||||||
## 注意事项
|
**重启 / 升级**
|
||||||
|
```bash
|
||||||
|
docker compose restart
|
||||||
|
docker compose up -d --build # 改代码后
|
||||||
|
```
|
||||||
|
|
||||||
- Cookie 过期时自动弹浏览器提示重新登录,并推送通知
|
**误推送了历史订单**:删 `data/state.json` 后重启会让程序重新建立基线(不推历史)。
|
||||||
- 每 5 分钟自动保活防 Session 过期
|
**想补推某个时间段的订单**:当前设计不做补推,恢复时会合并成一条汇总(阈值见 `bulk_summary_threshold`)。
|
||||||
- 无需小米账号或小爱音箱,TTS 完全本地运行
|
|
||||||
|
## 7. 可选:喇叭播报
|
||||||
|
|
||||||
|
服务器侧不跑 TTS。若确实需要店里喇叭响,两条路:
|
||||||
|
1. 服务器上已有的 `wework-xiaoai-bot` 容器带小爱 TTS,把本项目的推送目标改成它;
|
||||||
|
2. 店内电脑跑一个极简「取单播放」客户端(轮询 `/healthz` 不够,需另加接口)→ 本地 IndexTTS2 播报。
|
||||||
|
|
||||||
|
## 8. 配置项速查
|
||||||
|
|
||||||
|
见 `config.example.yaml` 全文注释。关键几项:
|
||||||
|
|
||||||
|
| 配置 | 默认 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `polling.interval_min/max` | 5 / 10 | 轮询间隔(秒,随机取值) |
|
||||||
|
| `polling.peak_page_size` | 20 | 高峰时段每次拉取条数 |
|
||||||
|
| `polling.idle_page_size` | 5 | 闲时拉取条数 |
|
||||||
|
| `polling.night_start/end` | 21:00 / 07:40 | 夜间暂停区间 |
|
||||||
|
| `polling.bulk_summary_threshold` | 5 | 积压超过 N 单改发汇总 |
|
||||||
|
| `notify.alert_cooldown_sec` | 1800 | 同类告警冷却 |
|
||||||
|
| `admin.token` | 空 | 空则写接口只允许本机 |
|
||||||
|
|
||||||
|
## 9. 与原版的差异(重构要点)
|
||||||
|
|
||||||
|
| 原问题 | 现状 |
|
||||||
|
|--------|------|
|
||||||
|
| `cookies.json` 不在仓库,服务器上直接弹浏览器 | 服务器不弹浏览器:告警 + 等 Cookie 推送,自动恢复 |
|
||||||
|
| TTS 绑死 Windows `winsound` + 本机 IndexTTS2 | TTS 变可选通道,非 Windows 自动禁用 |
|
||||||
|
| `test_push.py` 仍 `import miservice`(小爱已删) | 已删除 |
|
||||||
|
| `run_monitor.bat` 写死 `d:\coding\fengxiang` | 已删除,`run.bat` 基于脚本目录 |
|
||||||
|
| 初始拉单失败会把 20 单全推一遍 | 首次只建基线,不推历史 |
|
||||||
|
| `speak()` 阻塞主循环数秒 | 后台线程 + 队列 |
|
||||||
|
| 只有 print,无日志/无健康检查 | 文件日志滚动 + `/healthz` + Docker HEALTHCHECK |
|
||||||
|
| webhook / shopId 硬编码在源码 | 全部走 config/env |
|
||||||
|
| 飞书 webhook 失效(`code=19001`)却一直报错 | 保留配置位,默认关闭,填了才启用 |
|
||||||
|
| 每 5 秒新建 TLS 连接 | Session 复用 + 有限重试 + 指数退避 |
|
||||||
|
|
||||||
|
## 10. 已知限制
|
||||||
|
|
||||||
|
- 丰享接口是非官方逆向,字段/错误码随时可能变;`client.py` 集中处理,改一处即可。
|
||||||
|
- 只监控「快捷买单」订单列表,不含退款、取消等状态变更。
|
||||||
|
- 单实例运行(状态文件无锁);同一店铺不要起两个容器。
|
||||||
|
- `shopId` 目前只有一个店铺(益选便利店),多店铺需扩展为列表。
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# 丰享订单监控配置模板
|
||||||
|
# 复制为 config.yaml 后修改;密钥建议改用环境变量注入(见文件末尾)
|
||||||
|
|
||||||
|
shop_id: "20434543575189"
|
||||||
|
timezone: Asia/Shanghai
|
||||||
|
|
||||||
|
api:
|
||||||
|
base_url: https://fs.szfx.com
|
||||||
|
order_path: /saasmerchant/pcweb/order/quickpayorder/list
|
||||||
|
login_url: >-
|
||||||
|
https://fspass.szfx.com/ucenter/userlogin?platform=saas
|
||||||
|
&redirect_url=https%3A%2F%2Ffs.szfx.com%2FMMS%23%2F
|
||||||
|
&return_url=https%3A%2F%2Ffs.szfx.com%2Fsaasmerchant%2Fsetstoken
|
||||||
|
timeout: 20
|
||||||
|
max_retries: 2
|
||||||
|
|
||||||
|
notify:
|
||||||
|
# 服务器上只开企业微信;feishu 留位置,enabled=true 且填 webhook 后才会生效
|
||||||
|
channels: [wecom]
|
||||||
|
alert_cooldown_sec: 1800 # 同一类告警的冷却时间,防刷屏
|
||||||
|
wecom:
|
||||||
|
webhook: "" # 或用 FX_WECOM_WEBHOOK
|
||||||
|
feishu:
|
||||||
|
enabled: false # 注意:仓库里原有的飞书 token 已失效(code=19001)
|
||||||
|
webhook: ""
|
||||||
|
|
||||||
|
polling:
|
||||||
|
peak_hours: [[11, 13], [17, 19]] # 高峰时段(左闭右开)
|
||||||
|
interval_min: 5
|
||||||
|
interval_max: 10
|
||||||
|
peak_page_size: 20
|
||||||
|
idle_page_size: 5
|
||||||
|
night_start: "21:00" # 夜间暂停起点
|
||||||
|
night_end: "07:40" # 夜间结束点
|
||||||
|
night_check_sec: 60 # 夜间分片休眠步长(同时决定 Cookie 感知延迟)
|
||||||
|
keepalive_sec: 300 # 保活探测间隔
|
||||||
|
bulk_summary_threshold: 5 # 积压超过该条数改发汇总,防刷屏
|
||||||
|
|
||||||
|
paths:
|
||||||
|
cookies: data/cookies.json
|
||||||
|
state: data/state.json
|
||||||
|
logs: data/logs
|
||||||
|
|
||||||
|
admin:
|
||||||
|
enabled: true
|
||||||
|
host: 0.0.0.0
|
||||||
|
port: 8089
|
||||||
|
token: "" # 或用 FX_ADMIN_TOKEN;为空时只允许本机回环写
|
||||||
|
|
||||||
|
log:
|
||||||
|
level: INFO
|
||||||
|
max_bytes: 5242880
|
||||||
|
backup_count: 5
|
||||||
|
|
||||||
|
# 本地 Windows 模式才需要
|
||||||
|
tts:
|
||||||
|
enabled: false
|
||||||
|
voice_prompt: ""
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 环境变量(优先级高于本文件):
|
||||||
|
# FX_CONFIG=config.yaml 配置文件路径
|
||||||
|
# FX_SHOP_ID 店铺 ID
|
||||||
|
# FX_WECOM_WEBHOOK 企业微信机器人 webhook
|
||||||
|
# FX_FEISHU_WEBHOOK / FX_FEISHU_ENABLED
|
||||||
|
# FX_CHANNELS=wecom,feishu 覆盖通道列表
|
||||||
|
# FX_ADMIN_TOKEN 管理接口 token
|
||||||
|
# FX_ADMIN_PORT 管理接口端口(默认 8089)
|
||||||
|
# FX_DATA_DIR=/app/data cookies/state/logs 统一目录
|
||||||
|
# FX_LOG_LEVEL=INFO
|
||||||
|
# FX_TTS_ENABLED=0
|
||||||
|
# FX_INDEXTTS_HOME / FX_INDEXTTS_VOICE 本地 TTS(Windows)
|
||||||
|
# FX_SERVER / FX_ADMIN_TOKEN fengxiang_scraper.py --upload 用
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# 生产部署:docker compose up -d --build
|
||||||
|
# 密钥不写在文件里:同目录 .env 会自动被 compose 读取用于变量替换
|
||||||
|
services:
|
||||||
|
monitor:
|
||||||
|
build: .
|
||||||
|
image: fengxiang-monitor:5.0.0
|
||||||
|
container_name: fengxiang-monitor
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
TZ: Asia/Shanghai
|
||||||
|
FX_DATA_DIR: /app/data
|
||||||
|
FX_WECOM_WEBHOOK: ${FX_WECOM_WEBHOOK:-}
|
||||||
|
FX_ADMIN_TOKEN: ${FX_ADMIN_TOKEN:-}
|
||||||
|
FX_LOG_LEVEL: ${FX_LOG_LEVEL:-INFO}
|
||||||
|
volumes:
|
||||||
|
- ./config.yaml:/app/config.yaml:ro
|
||||||
|
- ./data:/app/data
|
||||||
|
ports:
|
||||||
|
# 宿主机 52100 -> 容器 8089(管理/健康检查;Cookie 上传走这个口)
|
||||||
|
- "52100:8089"
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"""丰享订单监控核心包。
|
||||||
|
|
||||||
|
模块划分:
|
||||||
|
- config : 配置加载(config.yaml + 环境变量覆盖)
|
||||||
|
- logger : 日志初始化(控制台 + 滚动文件)
|
||||||
|
- client : 丰享商家端 API 客户端(连接复用、重试、异常分类)
|
||||||
|
- store : 运行状态持久化(最新订单号 + 已推送去重集合)
|
||||||
|
- notify : 通知通道(企业微信 / 飞书,可插拔)
|
||||||
|
- tts : 本地语音播报(仅 Windows 本地模式,进程内队列不阻塞主循环)
|
||||||
|
- monitor : 监控主循环(轮询调度、夜间暂停、Cookie 热重载与失效等待)
|
||||||
|
- admin : 内置管理/健康检查 HTTP 接口(接收本地推送的 Cookie)
|
||||||
|
"""
|
||||||
|
|
||||||
|
__version__ = "5.0.0"
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""内置管理接口(HTTP)。
|
||||||
|
|
||||||
|
存在的唯一目的是解决「服务器没有桌面,丰享登录必须人工过验证码」这个矛盾:
|
||||||
|
本机登录后把 Cookie POST 过来,容器内立刻热生效,不用重启、不用 SSH 拷文件。
|
||||||
|
|
||||||
|
接口:
|
||||||
|
GET /healthz 健康检查(Docker HEALTHCHECK 用,免鉴权,只返回运行指标)
|
||||||
|
GET /api/status 运行状态(同上,别名)
|
||||||
|
POST /api/cookies 更新 Cookie(需鉴权)
|
||||||
|
POST /api/test-push 发一条测试消息(需鉴权)
|
||||||
|
|
||||||
|
鉴权:请求头 X-Auth-Token 或 Authorization: Bearer <token>,也支持 ?token=。
|
||||||
|
安全默认:未配置 token 时只接受来自 127.0.0.1 的写请求。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from typing import Any, Dict
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
|
from .config import Config
|
||||||
|
|
||||||
|
log = logging.getLogger("fengxiang.admin")
|
||||||
|
|
||||||
|
MAX_BODY = 64 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
class _Handler(BaseHTTPRequestHandler):
|
||||||
|
server_version = "fengxiang-admin/1.0"
|
||||||
|
monitor = None # 由 AdminServer 注入
|
||||||
|
cfg = None
|
||||||
|
|
||||||
|
# -------- 工具方法 --------
|
||||||
|
def log_message(self, fmt: str, *args: Any) -> None:
|
||||||
|
log.debug("%s - %s", self.address_string(), fmt % args)
|
||||||
|
|
||||||
|
def _json(self, code: int, payload: Dict[str, Any]) -> None:
|
||||||
|
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def _auth_ok(self, query: Dict[str, list]) -> bool:
|
||||||
|
token = self.cfg.admin.token
|
||||||
|
if not token:
|
||||||
|
# 未配置 token:仅允许本机回环写入
|
||||||
|
return self.client_address[0] in ("127.0.0.1", "::1")
|
||||||
|
supplied = (
|
||||||
|
self.headers.get("X-Auth-Token")
|
||||||
|
or (self.headers.get("Authorization") or "").replace("Bearer ", "").strip()
|
||||||
|
or (query.get("token") or [""])[0]
|
||||||
|
)
|
||||||
|
return supplied == token
|
||||||
|
|
||||||
|
def _read_json(self) -> Dict[str, Any]:
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
if length <= 0 or length > MAX_BODY:
|
||||||
|
raise ValueError("请求体为空或过大")
|
||||||
|
raw = self.rfile.read(length)
|
||||||
|
data = json.loads(raw.decode("utf-8"))
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise ValueError("请求体必须是 JSON 对象")
|
||||||
|
return data
|
||||||
|
|
||||||
|
# -------- 路由 --------
|
||||||
|
def do_GET(self) -> None: # noqa: N802
|
||||||
|
path = urlparse(self.path).path
|
||||||
|
if path in ("/healthz", "/api/status", "/api/health"):
|
||||||
|
self._json(200, self.monitor.status())
|
||||||
|
return
|
||||||
|
if path == "/":
|
||||||
|
self._json(200, {
|
||||||
|
"service": "fengxiang-monitor admin",
|
||||||
|
"endpoints": ["GET /healthz", "GET /api/status",
|
||||||
|
"POST /api/cookies", "POST /api/test-push"],
|
||||||
|
})
|
||||||
|
return
|
||||||
|
self._json(404, {"error": "not found"})
|
||||||
|
|
||||||
|
def do_POST(self) -> None: # noqa: N802
|
||||||
|
parsed = urlparse(self.path)
|
||||||
|
path = parsed.path
|
||||||
|
query = parse_qs(parsed.query)
|
||||||
|
|
||||||
|
if not self._auth_ok(query):
|
||||||
|
self._json(401, {"error": "unauthorized"})
|
||||||
|
return
|
||||||
|
|
||||||
|
if path == "/api/cookies":
|
||||||
|
try:
|
||||||
|
payload = self._read_json()
|
||||||
|
except (ValueError, json.JSONDecodeError) as exc:
|
||||||
|
self._json(400, {"error": f"参数错误: {exc}"})
|
||||||
|
return
|
||||||
|
cookies = payload.get("cookies", payload)
|
||||||
|
if not isinstance(cookies, dict) or not cookies:
|
||||||
|
self._json(400, {"error": "cookies 必须是非空对象"})
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
ok = self.monitor.update_cookies({str(k): str(v) for k, v in cookies.items()})
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log.exception("写入 Cookie 失败")
|
||||||
|
self._json(500, {"error": str(exc)})
|
||||||
|
return
|
||||||
|
if ok:
|
||||||
|
self._json(200, {"ok": True, "count": len(cookies), "status": self.monitor.status()})
|
||||||
|
else:
|
||||||
|
self._json(422, {"ok": False, "error": "Cookie 校验未通过,可能已失效"})
|
||||||
|
return
|
||||||
|
|
||||||
|
if path == "/api/test-push":
|
||||||
|
try:
|
||||||
|
payload = self._read_json()
|
||||||
|
except (ValueError, json.JSONDecodeError):
|
||||||
|
payload = {}
|
||||||
|
text = payload.get("text") or "【丰享监控】测试消息,请忽略。"
|
||||||
|
result = self.monitor.dispatcher.notify(text)
|
||||||
|
self._json(200, {"result": result})
|
||||||
|
return
|
||||||
|
|
||||||
|
self._json(404, {"error": "not found"})
|
||||||
|
|
||||||
|
|
||||||
|
class AdminServer:
|
||||||
|
def __init__(self, cfg: Config, monitor) -> None:
|
||||||
|
self.cfg = cfg
|
||||||
|
self.monitor = monitor
|
||||||
|
handler = type("BoundHandler", (_Handler,), {"monitor": monitor, "cfg": cfg})
|
||||||
|
self.httpd = ThreadingHTTPServer((cfg.admin.host, cfg.admin.port), handler)
|
||||||
|
self.httpd.daemon_threads = True
|
||||||
|
self._thread = threading.Thread(target=self.httpd.serve_forever,
|
||||||
|
name="admin-http", daemon=True)
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
self._thread.start()
|
||||||
|
log.info("管理接口已启动 http://%s:%d (健康检查 /healthz)",
|
||||||
|
self.cfg.admin.host, self.cfg.admin.port)
|
||||||
|
if not self.cfg.admin.token:
|
||||||
|
log.warning("未设置 admin.token,写接口仅允许本机回环访问")
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
try:
|
||||||
|
self.httpd.shutdown()
|
||||||
|
self.httpd.server_close()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""丰享商家端 API 客户端。
|
||||||
|
|
||||||
|
相比原实现的关键改动:
|
||||||
|
1. 复用 requests.Session(原代码每 5 秒新建 TLS 连接,纯浪费)
|
||||||
|
2. 只对「网络层故障」做有限重试,业务错误码不重试
|
||||||
|
3. 用异常区分三种状态,替代原来返回 "SESSION_EXPIRED" 魔法字符串
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from requests.adapters import HTTPAdapter
|
||||||
|
from urllib3.util.retry import Retry
|
||||||
|
|
||||||
|
from .config import Config
|
||||||
|
|
||||||
|
log = logging.getLogger("fengxiang.client")
|
||||||
|
|
||||||
|
# 丰享返回的「会话失效」错误码
|
||||||
|
SESSION_EXPIRED_CODES = {110003, 10009}
|
||||||
|
|
||||||
|
|
||||||
|
class FengxiangError(Exception):
|
||||||
|
"""所有客户端异常的基类。"""
|
||||||
|
|
||||||
|
|
||||||
|
class SessionExpired(FengxiangError):
|
||||||
|
"""Cookie/会话失效,需要重新登录。"""
|
||||||
|
|
||||||
|
|
||||||
|
class ApiError(FengxiangError):
|
||||||
|
"""接口返回了非 0 的业务错误码。"""
|
||||||
|
|
||||||
|
def __init__(self, errno: Any, errmsg: str = ""):
|
||||||
|
self.errno = errno
|
||||||
|
self.errmsg = errmsg
|
||||||
|
super().__init__(f"errno={errno} errmsg={errmsg}")
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkError(FengxiangError):
|
||||||
|
"""网络/超时/非 JSON 响应,可稍后重试。"""
|
||||||
|
|
||||||
|
|
||||||
|
class FengxiangClient:
|
||||||
|
def __init__(self, cfg: Config, session: Optional[requests.Session] = None):
|
||||||
|
self.cfg = cfg
|
||||||
|
self.session = session or self._build_session()
|
||||||
|
self.cookies: Dict[str, str] = {}
|
||||||
|
|
||||||
|
def _build_session(self) -> requests.Session:
|
||||||
|
s = requests.Session()
|
||||||
|
retry = Retry(
|
||||||
|
total=self.cfg.api.max_retries,
|
||||||
|
connect=self.cfg.api.max_retries,
|
||||||
|
read=self.cfg.api.max_retries,
|
||||||
|
backoff_factor=0.5,
|
||||||
|
status_forcelist=(429, 500, 502, 503, 504),
|
||||||
|
allowed_methods=frozenset(["POST"]),
|
||||||
|
raise_on_status=False,
|
||||||
|
)
|
||||||
|
adapter = HTTPAdapter(max_retries=retry, pool_connections=2, pool_maxsize=4)
|
||||||
|
s.mount("https://", adapter)
|
||||||
|
s.mount("http://", adapter)
|
||||||
|
s.headers.update({
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||||
|
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"),
|
||||||
|
"Referer": self.cfg.api.base_url.rstrip("/") + "/MMS",
|
||||||
|
"Origin": self.cfg.api.base_url.rstrip("/"),
|
||||||
|
})
|
||||||
|
return s
|
||||||
|
|
||||||
|
def set_cookies(self, cookies: Dict[str, str]) -> None:
|
||||||
|
self.cookies = dict(cookies or {})
|
||||||
|
|
||||||
|
def list_orders(self, page_size: int = 5, page: int = 1) -> List[Dict[str, Any]]:
|
||||||
|
"""拉取订单列表。
|
||||||
|
|
||||||
|
返回订单列表;会话失效抛 SessionExpired;业务错误抛 ApiError;
|
||||||
|
网络问题抛 NetworkError。
|
||||||
|
"""
|
||||||
|
payload = {"shopId": self.cfg.shop_id, "page": page, "pageSize": page_size}
|
||||||
|
try:
|
||||||
|
resp = self.session.post(
|
||||||
|
self.cfg.api.order_url,
|
||||||
|
json=payload,
|
||||||
|
cookies=self.cookies,
|
||||||
|
timeout=self.cfg.api.timeout,
|
||||||
|
)
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
raise NetworkError(f"请求失败: {exc}") from exc
|
||||||
|
|
||||||
|
if resp.status_code >= 500:
|
||||||
|
raise NetworkError(f"服务端 {resp.status_code}")
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
raise NetworkError(f"HTTP {resp.status_code}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = resp.json()
|
||||||
|
except ValueError as exc:
|
||||||
|
raise NetworkError(f"响应非 JSON: {resp.text[:120]}") from exc
|
||||||
|
|
||||||
|
errno = data.get("errno")
|
||||||
|
if errno == 0:
|
||||||
|
orders = (data.get("data") or {}).get("list") or []
|
||||||
|
return [o for o in orders if isinstance(o, dict)]
|
||||||
|
if errno in SESSION_EXPIRED_CODES:
|
||||||
|
raise SessionExpired(f"errno={errno} {data.get('errmsg', '')}".strip())
|
||||||
|
raise ApiError(errno, str(data.get("errmsg", "")))
|
||||||
|
|
||||||
|
def check_cookie(self, cookies: Dict[str, str]) -> bool:
|
||||||
|
"""校验 Cookie 是否可用(不抛异常)。"""
|
||||||
|
self.set_cookies(cookies)
|
||||||
|
try:
|
||||||
|
self.list_orders(page_size=1)
|
||||||
|
return True
|
||||||
|
except SessionExpired:
|
||||||
|
return False
|
||||||
|
except FengxiangError as exc:
|
||||||
|
log.warning("Cookie 校验时出现非会话类错误: %s", exc)
|
||||||
|
return False
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
"""配置加载。
|
||||||
|
|
||||||
|
优先级:环境变量 > config.yaml > 内置默认值。
|
||||||
|
|
||||||
|
之所以做三级覆盖,是为了让同一个镜像在本地、测试、生产三种环境复用,
|
||||||
|
而密钥(企业微信 webhook、管理接口 token)永远不进代码库。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List, Tuple
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 默认值:一份可直接跑起来的基线配置
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
DEFAULT_LOGIN_URL = (
|
||||||
|
"https://fspass.szfx.com/ucenter/userlogin"
|
||||||
|
"?platform=saas&redirect_url=https%3A%2F%2Ffs.szfx.com%2FMMS%23%2F"
|
||||||
|
"&return_url=https%3A%2F%2Ffs.szfx.com%2Fsaasmerchant%2Fsetstoken"
|
||||||
|
)
|
||||||
|
|
||||||
|
DEFAULTS: Dict[str, Any] = {
|
||||||
|
"shop_id": "20434543575189",
|
||||||
|
"timezone": "Asia/Shanghai",
|
||||||
|
"api": {
|
||||||
|
"base_url": "https://fs.szfx.com",
|
||||||
|
"order_path": "/saasmerchant/pcweb/order/quickpayorder/list",
|
||||||
|
"login_url": DEFAULT_LOGIN_URL,
|
||||||
|
"timeout": 20,
|
||||||
|
"max_retries": 2,
|
||||||
|
},
|
||||||
|
"notify": {
|
||||||
|
# 服务器上只开企业微信;feishu 保留配置位,默认关闭
|
||||||
|
"channels": ["wecom"],
|
||||||
|
"alert_cooldown_sec": 1800,
|
||||||
|
"wecom": {"webhook": ""},
|
||||||
|
"feishu": {"webhook": "", "enabled": False},
|
||||||
|
},
|
||||||
|
"polling": {
|
||||||
|
"peak_hours": [[11, 13], [17, 19]],
|
||||||
|
"interval_min": 5,
|
||||||
|
"interval_max": 10,
|
||||||
|
"peak_page_size": 20,
|
||||||
|
"idle_page_size": 5,
|
||||||
|
"night_start": "21:00",
|
||||||
|
"night_end": "07:40",
|
||||||
|
"night_check_sec": 60,
|
||||||
|
"keepalive_sec": 300,
|
||||||
|
# 一次补推超过该条数就不再逐条推送,改发汇总,防止恢复后刷屏
|
||||||
|
"bulk_summary_threshold": 5,
|
||||||
|
},
|
||||||
|
"paths": {
|
||||||
|
"cookies": "data/cookies.json",
|
||||||
|
"state": "data/state.json",
|
||||||
|
"logs": "data/logs",
|
||||||
|
},
|
||||||
|
"admin": {
|
||||||
|
"enabled": True,
|
||||||
|
"host": "0.0.0.0",
|
||||||
|
"port": 8089,
|
||||||
|
"token": "",
|
||||||
|
},
|
||||||
|
"log": {"level": "INFO", "max_bytes": 5242880, "backup_count": 5},
|
||||||
|
"tts": {"enabled": False, "voice_prompt": ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _deep_merge(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""递归合并字典,override 覆盖 base。"""
|
||||||
|
out = dict(base)
|
||||||
|
for key, value in (override or {}).items():
|
||||||
|
if isinstance(value, dict) and isinstance(out.get(key), dict):
|
||||||
|
out[key] = _deep_merge(out[key], value)
|
||||||
|
else:
|
||||||
|
out[key] = value
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _as_bool(value: Any) -> bool:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return value
|
||||||
|
return str(value).strip().lower() in ("1", "true", "yes", "on", "y")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_hhmm(text: str) -> int:
|
||||||
|
"""'21:00' -> 1260(当天分钟数)。"""
|
||||||
|
hh, mm = str(text).split(":")[:2]
|
||||||
|
return int(hh) * 60 + int(mm)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 强类型配置对象
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@dataclass
|
||||||
|
class ApiCfg:
|
||||||
|
base_url: str
|
||||||
|
order_path: str
|
||||||
|
login_url: str
|
||||||
|
timeout: int
|
||||||
|
max_retries: int
|
||||||
|
|
||||||
|
@property
|
||||||
|
def order_url(self) -> str:
|
||||||
|
return self.base_url.rstrip("/") + self.order_path
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class NotifyCfg:
|
||||||
|
channels: List[str]
|
||||||
|
alert_cooldown_sec: int
|
||||||
|
wecom_webhook: str
|
||||||
|
feishu_webhook: str
|
||||||
|
feishu_enabled: bool
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PollingCfg:
|
||||||
|
peak_hours: List[Tuple[int, int]]
|
||||||
|
interval_min: int
|
||||||
|
interval_max: int
|
||||||
|
peak_page_size: int
|
||||||
|
idle_page_size: int
|
||||||
|
night_start_min: int
|
||||||
|
night_end_min: int
|
||||||
|
night_check_sec: int
|
||||||
|
keepalive_sec: int
|
||||||
|
bulk_summary_threshold: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PathsCfg:
|
||||||
|
cookies: Path
|
||||||
|
state: Path
|
||||||
|
logs: Path
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AdminCfg:
|
||||||
|
enabled: bool
|
||||||
|
host: str
|
||||||
|
port: int
|
||||||
|
token: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LogCfg:
|
||||||
|
level: str
|
||||||
|
max_bytes: int
|
||||||
|
backup_count: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TtsCfg:
|
||||||
|
enabled: bool
|
||||||
|
voice_prompt: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Config:
|
||||||
|
shop_id: str
|
||||||
|
timezone: str
|
||||||
|
api: ApiCfg
|
||||||
|
notify: NotifyCfg
|
||||||
|
polling: PollingCfg
|
||||||
|
paths: PathsCfg
|
||||||
|
admin: AdminCfg
|
||||||
|
log: LogCfg
|
||||||
|
tts: TtsCfg
|
||||||
|
raw: Dict[str, Any] = field(default_factory=dict, repr=False)
|
||||||
|
|
||||||
|
def ensure_dirs(self) -> None:
|
||||||
|
self.paths.cookies.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self.paths.state.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self.paths.logs.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_env(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""环境变量覆盖。命名约定:FX_<段>_<键>。"""
|
||||||
|
env = os.environ
|
||||||
|
if env.get("FX_SHOP_ID"):
|
||||||
|
data["shop_id"] = env["FX_SHOP_ID"]
|
||||||
|
if env.get("FX_WECOM_WEBHOOK"):
|
||||||
|
data["notify"]["wecom"]["webhook"] = env["FX_WECOM_WEBHOOK"]
|
||||||
|
if env.get("FX_FEISHU_WEBHOOK"):
|
||||||
|
data["notify"]["feishu"]["webhook"] = env["FX_FEISHU_WEBHOOK"]
|
||||||
|
if env.get("FX_FEISHU_ENABLED"):
|
||||||
|
data["notify"]["feishu"]["enabled"] = _as_bool(env["FX_FEISHU_ENABLED"])
|
||||||
|
if env.get("FX_CHANNELS"):
|
||||||
|
data["notify"]["channels"] = [
|
||||||
|
c.strip() for c in env["FX_CHANNELS"].split(",") if c.strip()
|
||||||
|
]
|
||||||
|
if env.get("FX_ADMIN_TOKEN"):
|
||||||
|
data["admin"]["token"] = env["FX_ADMIN_TOKEN"]
|
||||||
|
if env.get("FX_ADMIN_PORT"):
|
||||||
|
data["admin"]["port"] = int(env["FX_ADMIN_PORT"])
|
||||||
|
if env.get("FX_ADMIN_ENABLED"):
|
||||||
|
data["admin"]["enabled"] = _as_bool(env["FX_ADMIN_ENABLED"])
|
||||||
|
if env.get("FX_DATA_DIR"):
|
||||||
|
base = Path(env["FX_DATA_DIR"])
|
||||||
|
data["paths"]["cookies"] = str(base / "cookies.json")
|
||||||
|
data["paths"]["state"] = str(base / "state.json")
|
||||||
|
data["paths"]["logs"] = str(base / "logs")
|
||||||
|
if env.get("FX_LOG_LEVEL"):
|
||||||
|
data["log"]["level"] = env["FX_LOG_LEVEL"]
|
||||||
|
if env.get("FX_TTS_ENABLED"):
|
||||||
|
data["tts"]["enabled"] = _as_bool(env["FX_TTS_ENABLED"])
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def load_config(path: str | os.PathLike | None = None) -> Config:
|
||||||
|
"""加载配置。path 为 None 时按 FX_CONFIG -> ./config.yaml 顺序查找。"""
|
||||||
|
cfg_path = path or os.environ.get("FX_CONFIG") or "config.yaml"
|
||||||
|
data = dict(DEFAULTS)
|
||||||
|
|
||||||
|
p = Path(cfg_path)
|
||||||
|
if p.exists():
|
||||||
|
with open(p, "r", encoding="utf-8") as f:
|
||||||
|
loaded = yaml.safe_load(f) or {}
|
||||||
|
if not isinstance(loaded, dict):
|
||||||
|
raise ValueError(f"配置文件格式错误(应为 YAML 映射): {p}")
|
||||||
|
data = _deep_merge(data, loaded)
|
||||||
|
|
||||||
|
data = _apply_env(data)
|
||||||
|
|
||||||
|
notify = data["notify"]
|
||||||
|
feishu_on = bool(notify["feishu"].get("enabled")) and bool(notify["feishu"]["webhook"])
|
||||||
|
channels = []
|
||||||
|
for name in notify.get("channels") or []:
|
||||||
|
if name == "feishu" and not feishu_on:
|
||||||
|
continue
|
||||||
|
if name == "wecom" and not notify["wecom"]["webhook"]:
|
||||||
|
continue
|
||||||
|
channels.append(name)
|
||||||
|
|
||||||
|
polling = data["polling"]
|
||||||
|
cfg = Config(
|
||||||
|
shop_id=str(data["shop_id"]),
|
||||||
|
timezone=str(data.get("timezone") or "Asia/Shanghai"),
|
||||||
|
api=ApiCfg(
|
||||||
|
base_url=data["api"]["base_url"],
|
||||||
|
order_path=data["api"]["order_path"],
|
||||||
|
login_url=data["api"]["login_url"],
|
||||||
|
timeout=int(data["api"]["timeout"]),
|
||||||
|
max_retries=int(data["api"]["max_retries"]),
|
||||||
|
),
|
||||||
|
notify=NotifyCfg(
|
||||||
|
channels=channels,
|
||||||
|
alert_cooldown_sec=int(notify["alert_cooldown_sec"]),
|
||||||
|
wecom_webhook=notify["wecom"]["webhook"],
|
||||||
|
feishu_webhook=notify["feishu"]["webhook"],
|
||||||
|
feishu_enabled=feishu_on,
|
||||||
|
),
|
||||||
|
polling=PollingCfg(
|
||||||
|
peak_hours=[tuple(h) for h in polling["peak_hours"]],
|
||||||
|
interval_min=int(polling["interval_min"]),
|
||||||
|
interval_max=int(polling["interval_max"]),
|
||||||
|
peak_page_size=int(polling["peak_page_size"]),
|
||||||
|
idle_page_size=int(polling["idle_page_size"]),
|
||||||
|
night_start_min=parse_hhmm(polling["night_start"]),
|
||||||
|
night_end_min=parse_hhmm(polling["night_end"]),
|
||||||
|
night_check_sec=int(polling["night_check_sec"]),
|
||||||
|
keepalive_sec=int(polling["keepalive_sec"]),
|
||||||
|
bulk_summary_threshold=int(polling["bulk_summary_threshold"]),
|
||||||
|
),
|
||||||
|
paths=PathsCfg(
|
||||||
|
cookies=Path(data["paths"]["cookies"]),
|
||||||
|
state=Path(data["paths"]["state"]),
|
||||||
|
logs=Path(data["paths"]["logs"]),
|
||||||
|
),
|
||||||
|
admin=AdminCfg(
|
||||||
|
enabled=_as_bool(data["admin"]["enabled"]),
|
||||||
|
host=data["admin"]["host"],
|
||||||
|
port=int(data["admin"]["port"]),
|
||||||
|
token=data["admin"]["token"],
|
||||||
|
),
|
||||||
|
log=LogCfg(
|
||||||
|
level=str(data["log"]["level"]).upper(),
|
||||||
|
max_bytes=int(data["log"]["max_bytes"]),
|
||||||
|
backup_count=int(data["log"]["backup_count"]),
|
||||||
|
),
|
||||||
|
tts=TtsCfg(
|
||||||
|
enabled=_as_bool(data["tts"]["enabled"]),
|
||||||
|
voice_prompt=data["tts"].get("voice_prompt") or "",
|
||||||
|
),
|
||||||
|
raw=data,
|
||||||
|
)
|
||||||
|
cfg.ensure_dirs()
|
||||||
|
return cfg
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""日志初始化:控制台 + 按大小滚动的文件。
|
||||||
|
|
||||||
|
原项目全程 print,容器里 detached 运行就查不到历史,出问题无法回溯。
|
||||||
|
这里统一收口到 logging,容器 stdout 由 docker json-file 限制大小,文件另有 5MB 滚动。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
from logging.handlers import RotatingFileHandler
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def setup_logging(log_dir: Path, level: str = "INFO",
|
||||||
|
max_bytes: int = 5 * 1024 * 1024, backup_count: int = 5) -> logging.Logger:
|
||||||
|
log_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
root = logging.getLogger()
|
||||||
|
root.setLevel(getattr(logging, level.upper(), logging.INFO))
|
||||||
|
|
||||||
|
# 避免重复初始化(测试中多次调用)
|
||||||
|
for h in list(root.handlers):
|
||||||
|
root.removeHandler(h)
|
||||||
|
|
||||||
|
fmt = logging.Formatter(
|
||||||
|
"%(asctime)s %(levelname)-7s [%(name)s] %(message)s",
|
||||||
|
datefmt="%Y-%m-%d %H:%M:%S",
|
||||||
|
)
|
||||||
|
|
||||||
|
console = logging.StreamHandler(stream=sys.stdout)
|
||||||
|
console.setFormatter(fmt)
|
||||||
|
root.addHandler(console)
|
||||||
|
|
||||||
|
file_handler = RotatingFileHandler(
|
||||||
|
log_dir / "monitor.log",
|
||||||
|
maxBytes=max_bytes,
|
||||||
|
backupCount=backup_count,
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
file_handler.setFormatter(fmt)
|
||||||
|
root.addHandler(file_handler)
|
||||||
|
|
||||||
|
# requests/urllib3 的连接细节太吵,只留警告
|
||||||
|
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
||||||
|
return root
|
||||||
@@ -0,0 +1,429 @@
|
|||||||
|
"""监控主循环。
|
||||||
|
|
||||||
|
与原实现的行为差异(都是有意的):
|
||||||
|
1. 首次启动只建立基线,不推送历史订单(原来初始拉单失败会把 20 单全推一遍)
|
||||||
|
2. 夜间暂停改为分片休眠:每 60 秒醒一次,可感知 Cookie 更新与停止信号(原来 sleep 10 小时)
|
||||||
|
3. Cookie 失效不再弹浏览器(服务器没桌面),改为告警 + 轮询等待新 Cookie,收到即自动恢复
|
||||||
|
4. Cookie 文件变化自动热重载,无需重启容器
|
||||||
|
5. 网络抖动走指数退避,连续失败才升级告警
|
||||||
|
6. 恢复后积压订单超过阈值改发汇总,避免刷屏
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import signal
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from .client import ApiError, FengxiangClient, FengxiangError, NetworkError, SessionExpired
|
||||||
|
from .config import Config
|
||||||
|
from .notify import Dispatcher, build_channels
|
||||||
|
from .store import State
|
||||||
|
from .tts import Speaker
|
||||||
|
|
||||||
|
log = logging.getLogger("fengxiang.monitor")
|
||||||
|
|
||||||
|
COOKIE_WAIT_POLL_SEC = 15 # 等待新 Cookie 时的轮询间隔
|
||||||
|
COOKIE_RECHECK_SEC = 300 # 即使文件没变,也每 5 分钟再验一次
|
||||||
|
STATE_SAVE_SEC = 600 # 无事件时的状态落盘间隔
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_money(cents: Any) -> str:
|
||||||
|
try:
|
||||||
|
return f"{int(cents) / 100:.2f}元"
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return "0.00元"
|
||||||
|
|
||||||
|
|
||||||
|
def format_order_message(order: Dict[str, Any]) -> str:
|
||||||
|
return f"【丰享丰食】订单收款成功,收款{fmt_money(order.get('amountPayable'))}"
|
||||||
|
|
||||||
|
|
||||||
|
class Monitor:
|
||||||
|
def __init__(self, cfg: Config, client: Optional[FengxiangClient] = None,
|
||||||
|
dispatcher: Optional[Dispatcher] = None,
|
||||||
|
speaker: Optional[Speaker] = None):
|
||||||
|
self.cfg = cfg
|
||||||
|
self.client = client or FengxiangClient(cfg)
|
||||||
|
self.dispatcher = dispatcher or Dispatcher(
|
||||||
|
build_channels(cfg), cfg.notify.alert_cooldown_sec
|
||||||
|
)
|
||||||
|
self.speaker = speaker or Speaker(cfg.tts.voice_prompt, cfg.tts.enabled)
|
||||||
|
self.state = State.load(cfg.paths.state)
|
||||||
|
self.stop_event = threading.Event()
|
||||||
|
self._cookie_sig: Optional[tuple] = None
|
||||||
|
self._last_state_save = 0.0
|
||||||
|
self._net_failures = 0
|
||||||
|
self._started_at = time.time()
|
||||||
|
self._admin = None
|
||||||
|
self._last_cookie_check = 0.0
|
||||||
|
self._now_impl = self._default_now
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ 时间
|
||||||
|
def now(self) -> datetime.datetime:
|
||||||
|
"""当前时间。测试可通过替换 _now_impl 注入固定时间。"""
|
||||||
|
return self._now_impl()
|
||||||
|
|
||||||
|
def _default_now(self) -> datetime.datetime:
|
||||||
|
try:
|
||||||
|
import zoneinfo
|
||||||
|
return datetime.datetime.now(zoneinfo.ZoneInfo(self.cfg.timezone))
|
||||||
|
except Exception: # noqa: BLE001 - 无 tzdata 时退回本机时区
|
||||||
|
return datetime.datetime.now()
|
||||||
|
|
||||||
|
def is_peak(self) -> bool:
|
||||||
|
hour = self.now().hour
|
||||||
|
return any(start <= hour < end for start, end in self.cfg.polling.peak_hours)
|
||||||
|
|
||||||
|
def is_night(self) -> bool:
|
||||||
|
n = self.now()
|
||||||
|
minutes = n.hour * 60 + n.minute
|
||||||
|
p = self.cfg.polling
|
||||||
|
return minutes >= p.night_start_min or minutes < p.night_end_min
|
||||||
|
|
||||||
|
def seconds_until_morning(self) -> int:
|
||||||
|
n = self.now()
|
||||||
|
target = n.replace(hour=0, minute=0, second=0, microsecond=0) + datetime.timedelta(
|
||||||
|
minutes=self.cfg.polling.night_end_min
|
||||||
|
)
|
||||||
|
if target <= n:
|
||||||
|
target += datetime.timedelta(days=1)
|
||||||
|
return max(1, int((target - n).total_seconds()))
|
||||||
|
|
||||||
|
def poll_page_size(self) -> int:
|
||||||
|
p = self.cfg.polling
|
||||||
|
return p.peak_page_size if self.is_peak() else p.idle_page_size
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ Cookie
|
||||||
|
def _cookie_sig_of_file(self) -> Optional[tuple]:
|
||||||
|
path = Path(self.cfg.paths.cookies)
|
||||||
|
if not path.exists():
|
||||||
|
return None
|
||||||
|
st = path.stat()
|
||||||
|
return (st.st_mtime_ns, st.st_size)
|
||||||
|
|
||||||
|
def read_cookies(self) -> Optional[Dict[str, str]]:
|
||||||
|
path = Path(self.cfg.paths.cookies)
|
||||||
|
if not path.exists():
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
if isinstance(data, dict) and data:
|
||||||
|
return {str(k): str(v) for k, v in data.items()}
|
||||||
|
log.warning("cookie 文件内容不是非空字典,忽略")
|
||||||
|
return None
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
log.error("读取 cookie 文件失败: %s", exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def apply_cookies(self, cookies: Dict[str, str], source: str = "file") -> bool:
|
||||||
|
"""校验并应用 Cookie(供主循环与管理接口共用)。"""
|
||||||
|
if not cookies:
|
||||||
|
return False
|
||||||
|
if not self.client.check_cookie(cookies):
|
||||||
|
log.warning("来自 %s 的 Cookie 校验未通过", source)
|
||||||
|
return False
|
||||||
|
self.client.set_cookies(cookies)
|
||||||
|
old = self.state.cookie_updated_ts
|
||||||
|
self.state.cookie_updated_ts = time.time()
|
||||||
|
self.state.cookie_valid = True
|
||||||
|
self.state.save()
|
||||||
|
log.info("Cookie 已生效(来源=%s,共 %d 项,距上次更新 %.0f 秒)",
|
||||||
|
source, len(cookies), self.state.cookie_updated_ts - old if old else 0)
|
||||||
|
if old and self.state.gap_since_ts:
|
||||||
|
gap_min = (time.time() - self.state.gap_since_ts) / 60
|
||||||
|
self.dispatcher.notify(f"【丰享监控】已重新登录,监控恢复(中断约 {gap_min:.0f} 分钟)")
|
||||||
|
self.state.gap_since_ts = 0.0
|
||||||
|
self.state.save()
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _load_cookie_if_changed(self, force: bool = False) -> bool:
|
||||||
|
sig = self._cookie_sig_of_file()
|
||||||
|
if sig is None:
|
||||||
|
if force:
|
||||||
|
log.warning("未找到 Cookie 文件: %s", self.cfg.paths.cookies)
|
||||||
|
return False
|
||||||
|
if not force and sig == self._cookie_sig:
|
||||||
|
return True
|
||||||
|
cookies = self.read_cookies()
|
||||||
|
ok = self.apply_cookies(cookies or {}, source="file")
|
||||||
|
if ok:
|
||||||
|
self._cookie_sig = sig
|
||||||
|
else:
|
||||||
|
# 记录签名,避免同一份坏 Cookie 反复校验
|
||||||
|
self._cookie_sig = sig
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def update_cookies(self, cookies: Dict[str, str]) -> bool:
|
||||||
|
"""管理接口收到新 Cookie:落盘后立即校验生效。"""
|
||||||
|
from .store import atomic_write_json
|
||||||
|
atomic_write_json(Path(self.cfg.paths.cookies), cookies)
|
||||||
|
self._cookie_sig = self._cookie_sig_of_file()
|
||||||
|
return self.apply_cookies(cookies, source="admin-api")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ 状态
|
||||||
|
def status(self) -> Dict[str, Any]:
|
||||||
|
now = time.time()
|
||||||
|
return {
|
||||||
|
"app": "fengxiang-monitor",
|
||||||
|
"mode": ("night" if self.is_night() else ("peak" if self.is_peak() else "idle")),
|
||||||
|
"cookie_valid": bool(self.state.cookie_valid),
|
||||||
|
"cookie_age_sec": int(now - self.state.cookie_updated_ts) if self.state.cookie_updated_ts else None,
|
||||||
|
"last_order_id": self.state.last_order_id,
|
||||||
|
"last_poll_age_sec": int(now - self.state.last_poll_ts) if self.state.last_poll_ts else None,
|
||||||
|
"total_pushed": self.state.total_pushed,
|
||||||
|
"uptime_sec": int(now - self._started_at),
|
||||||
|
"net_failures": self._net_failures,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _save_state(self, force: bool = False) -> None:
|
||||||
|
now = time.time()
|
||||||
|
if force or now - self._last_state_save > STATE_SAVE_SEC:
|
||||||
|
self.state.save()
|
||||||
|
self._last_state_save = now
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ 主流程
|
||||||
|
def stop(self, *_args) -> None:
|
||||||
|
log.info("收到停止信号,准备退出")
|
||||||
|
self.stop_event.set()
|
||||||
|
|
||||||
|
def _install_signals(self) -> None:
|
||||||
|
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||||
|
try:
|
||||||
|
signal.signal(sig, self.stop)
|
||||||
|
except (ValueError, OSError): # 非主线程/平台不支持
|
||||||
|
pass
|
||||||
|
|
||||||
|
def run(self) -> None:
|
||||||
|
self._install_signals()
|
||||||
|
self.speaker.start()
|
||||||
|
log.info("丰享订单监控启动 v%s | shop=%s | 通道=%s",
|
||||||
|
__import__("fengxiang").__version__, self.cfg.shop_id,
|
||||||
|
",".join(c.name for c in self.dispatcher.channels) or "无")
|
||||||
|
|
||||||
|
if self.cfg.admin.enabled:
|
||||||
|
from .admin import AdminServer
|
||||||
|
self._admin = AdminServer(self.cfg, self)
|
||||||
|
self._admin.start()
|
||||||
|
|
||||||
|
# 1) 确保有可用 Cookie
|
||||||
|
if not self._ensure_cookie():
|
||||||
|
log.error("启动阶段未获得可用 Cookie,进入等待模式")
|
||||||
|
if self.stop_event.is_set():
|
||||||
|
self._shutdown()
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2) 建立基线(不推送历史订单)
|
||||||
|
if self.state.cookie_valid:
|
||||||
|
self._bootstrap()
|
||||||
|
|
||||||
|
# 3) 主循环
|
||||||
|
while not self.stop_event.is_set():
|
||||||
|
try:
|
||||||
|
if self.is_night():
|
||||||
|
self._night_wait()
|
||||||
|
continue
|
||||||
|
|
||||||
|
self._load_cookie_if_changed(force=False)
|
||||||
|
|
||||||
|
page_size = self.poll_page_size()
|
||||||
|
try:
|
||||||
|
orders = self.client.list_orders(page_size=page_size)
|
||||||
|
except SessionExpired as exc:
|
||||||
|
self._on_session_expired(str(exc))
|
||||||
|
continue
|
||||||
|
except (NetworkError, ApiError) as exc:
|
||||||
|
self._on_soft_error(exc)
|
||||||
|
continue
|
||||||
|
|
||||||
|
self._net_failures = 0
|
||||||
|
self.state.touch_poll()
|
||||||
|
self._process(orders, page_size)
|
||||||
|
self._save_state()
|
||||||
|
self._wait(self._next_interval())
|
||||||
|
except Exception as exc: # noqa: BLE001 - 主循环绝不能被单次异常打死
|
||||||
|
log.exception("主循环异常(已忽略并继续): %s", exc)
|
||||||
|
self._wait(10)
|
||||||
|
|
||||||
|
self._shutdown()
|
||||||
|
|
||||||
|
def _shutdown(self) -> None:
|
||||||
|
self.speaker.stop()
|
||||||
|
if self._admin:
|
||||||
|
self._admin.stop()
|
||||||
|
self._save_state(force=True)
|
||||||
|
log.info("监控已停止")
|
||||||
|
|
||||||
|
def _ensure_cookie(self) -> bool:
|
||||||
|
"""启动时确保 Cookie 可用;不可用则等待(不弹浏览器)。"""
|
||||||
|
if self._load_cookie_if_changed(force=True):
|
||||||
|
log.info("启动校验通过,复用已有 Cookie")
|
||||||
|
return True
|
||||||
|
|
||||||
|
cookies = self.read_cookies()
|
||||||
|
if cookies and self.client.check_cookie(cookies):
|
||||||
|
return self.apply_cookies(cookies, source="file")
|
||||||
|
|
||||||
|
self.state.cookie_valid = False
|
||||||
|
self.state.gap_since_ts = self.state.gap_since_ts or time.time()
|
||||||
|
self.state.save()
|
||||||
|
self.dispatcher.alert(
|
||||||
|
"cookie_need_login",
|
||||||
|
"【丰享监控】需要登录:Cookie 缺失或已失效。请在本机运行 fengxiang_scraper.py 完成登录,"
|
||||||
|
"脚本会自动上传 Cookie,服务器收到后自动恢复监控。",
|
||||||
|
)
|
||||||
|
return self._wait_for_new_cookie()
|
||||||
|
|
||||||
|
def _wait_for_new_cookie(self) -> bool:
|
||||||
|
"""等待新 Cookie 落地。返回是否拿到可用 Cookie。"""
|
||||||
|
baseline = self._cookie_sig_of_file()
|
||||||
|
log.warning("进入 Cookie 等待模式(等待 %s 更新)", self.cfg.paths.cookies)
|
||||||
|
last_log = 0.0
|
||||||
|
last_recheck = 0.0
|
||||||
|
while not self.stop_event.is_set():
|
||||||
|
self.stop_event.wait(COOKIE_WAIT_POLL_SEC)
|
||||||
|
if self.stop_event.is_set():
|
||||||
|
return False
|
||||||
|
|
||||||
|
sig = self._cookie_sig_of_file()
|
||||||
|
if sig and sig != baseline:
|
||||||
|
cookies = self.read_cookies()
|
||||||
|
if cookies and self.apply_cookies(cookies, source="file"):
|
||||||
|
self._cookie_sig = sig
|
||||||
|
return True
|
||||||
|
baseline = sig
|
||||||
|
log.warning("新 Cookie 仍不可用,继续等待")
|
||||||
|
|
||||||
|
# 兜底:文件没变化但可能是同一份 Cookie 恢复了(服务端续期)
|
||||||
|
now = time.time()
|
||||||
|
if now - last_recheck > COOKIE_RECHECK_SEC:
|
||||||
|
last_recheck = now
|
||||||
|
cookies = self.read_cookies()
|
||||||
|
if cookies and self.client.check_cookie(cookies):
|
||||||
|
if self.apply_cookies(cookies, source="recheck"):
|
||||||
|
return True
|
||||||
|
if now - last_log > 300:
|
||||||
|
last_log = now
|
||||||
|
log.warning("仍在等待 Cookie(已等待 %.0f 分钟)", (now - (self.state.gap_since_ts or now)) / 60)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _on_session_expired(self, reason: str) -> None:
|
||||||
|
log.error("会话失效: %s", reason)
|
||||||
|
self.state.cookie_valid = False
|
||||||
|
self.state.gap_since_ts = self.state.gap_since_ts or time.time()
|
||||||
|
self.state.save()
|
||||||
|
self.dispatcher.alert(
|
||||||
|
"cookie_expired",
|
||||||
|
"【丰享监控】登录已失效(Cookie 过期),监控暂停。"
|
||||||
|
"请在本机运行 fengxiang_scraper.py 重新登录,上传后自动恢复。",
|
||||||
|
)
|
||||||
|
self._wait_for_new_cookie()
|
||||||
|
|
||||||
|
def _on_soft_error(self, exc: FengxiangError) -> None:
|
||||||
|
self._net_failures += 1
|
||||||
|
backoff = min(60, 5 * (2 ** min(self._net_failures - 1, 4))) + random.uniform(0, 3)
|
||||||
|
log.warning("拉取订单失败(第 %d 次): %s,%.1f 秒后重试",
|
||||||
|
self._net_failures, exc, backoff)
|
||||||
|
if self._net_failures in (5, 20, 60):
|
||||||
|
self.dispatcher.alert(
|
||||||
|
f"net_fail_{self._net_failures}",
|
||||||
|
f"【丰享监控】连续 {self._net_failures} 次拉单失败,最近错误:{exc}",
|
||||||
|
)
|
||||||
|
self._wait(backoff)
|
||||||
|
|
||||||
|
def _bootstrap(self) -> None:
|
||||||
|
"""建立订单基线:取最新一单作为参考点,不推送。"""
|
||||||
|
if self.state.last_order_id:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
orders = self.client.list_orders(page_size=1)
|
||||||
|
except FengxiangError as exc:
|
||||||
|
log.warning("建立基线失败(下次轮询再试): %s", exc)
|
||||||
|
return
|
||||||
|
if orders:
|
||||||
|
self.state.last_order_id = str(orders[0].get("orderId"))
|
||||||
|
self.state.mark_pushed([self.state.last_order_id])
|
||||||
|
self.state.save()
|
||||||
|
log.info("已建立基线,当前最新订单 %s(不推送历史订单)", self.state.last_order_id)
|
||||||
|
|
||||||
|
def _process(self, orders: List[Dict[str, Any]], page_size: int) -> None:
|
||||||
|
if not orders:
|
||||||
|
log.debug("本次拉取为空")
|
||||||
|
return
|
||||||
|
|
||||||
|
new_orders: List[Dict[str, Any]] = []
|
||||||
|
for order in orders:
|
||||||
|
oid = str(order.get("orderId") or "")
|
||||||
|
if not oid:
|
||||||
|
continue
|
||||||
|
if self.state.last_order_id and oid == self.state.last_order_id:
|
||||||
|
break
|
||||||
|
if self.state.has_pushed(oid):
|
||||||
|
continue
|
||||||
|
new_orders.append(order)
|
||||||
|
|
||||||
|
if not new_orders:
|
||||||
|
log.debug("暂无新订单(最新=%s)", self.state.last_order_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
if len(new_orders) >= page_size:
|
||||||
|
log.warning("本次新订单数达到页大小 %d,可能仍有更早订单未拉取,建议临时调大 page_size",
|
||||||
|
page_size)
|
||||||
|
|
||||||
|
newest_id = str(new_orders[0].get("orderId"))
|
||||||
|
threshold = self.cfg.polling.bulk_summary_threshold
|
||||||
|
|
||||||
|
if len(new_orders) > threshold:
|
||||||
|
total = sum(int(o.get("amountPayable") or 0) for o in new_orders)
|
||||||
|
msg = (f"【丰享丰食】监控恢复,期间新增 {len(new_orders)} 笔订单,"
|
||||||
|
f"合计 {fmt_money(total)}(已合并提醒)")
|
||||||
|
log.info("积压 %d 单,发送汇总消息", len(new_orders))
|
||||||
|
self.dispatcher.notify(msg)
|
||||||
|
else:
|
||||||
|
log.info("发现 %d 笔新订单", len(new_orders))
|
||||||
|
for order in reversed(new_orders): # 从旧到新
|
||||||
|
msg = format_order_message(order)
|
||||||
|
self.dispatcher.notify(msg)
|
||||||
|
self.speaker.say(msg)
|
||||||
|
time.sleep(0.3)
|
||||||
|
|
||||||
|
self.state.mark_pushed([str(o.get("orderId")) for o in new_orders])
|
||||||
|
self.state.last_order_id = newest_id
|
||||||
|
self.state.save()
|
||||||
|
|
||||||
|
def _next_interval(self) -> float:
|
||||||
|
p = self.cfg.polling
|
||||||
|
return random.uniform(p.interval_min, p.interval_max)
|
||||||
|
|
||||||
|
def _wait(self, seconds: float) -> None:
|
||||||
|
"""可中断等待。"""
|
||||||
|
if seconds > 0:
|
||||||
|
self.stop_event.wait(seconds)
|
||||||
|
|
||||||
|
def _night_wait(self) -> None:
|
||||||
|
remaining = self.seconds_until_morning()
|
||||||
|
step = min(remaining, self.cfg.polling.night_check_sec)
|
||||||
|
if remaining == step:
|
||||||
|
log.info("夜间暂停,%.0f 分钟后恢复", remaining / 60)
|
||||||
|
# 分片休眠:便于感知 Cookie 更新和停止信号
|
||||||
|
waited = 0.0
|
||||||
|
while waited < remaining and not self.stop_event.is_set():
|
||||||
|
chunk = min(self.cfg.polling.night_check_sec, remaining - waited)
|
||||||
|
self.stop_event.wait(chunk)
|
||||||
|
waited += chunk
|
||||||
|
self._load_cookie_if_changed(force=False)
|
||||||
|
if not self.stop_event.is_set():
|
||||||
|
log.info("夜间结束,恢复监控")
|
||||||
|
self._bootstrap()
|
||||||
|
|
||||||
|
|
||||||
|
def build_monitor(cfg: Config) -> Monitor:
|
||||||
|
return Monitor(cfg)
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
"""通知通道。
|
||||||
|
|
||||||
|
设计要点:
|
||||||
|
- 通道可插拔(企业微信 / 飞书),单个通道失败不影响其他通道,也不影响主循环
|
||||||
|
- 告警(Cookie 失效、登录提示)带冷却,避免每 5 秒往群里刷一条
|
||||||
|
- 所有 webhook 从配置读取,源码里不再出现密钥
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from typing import Dict, List, Protocol, Tuple
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .config import Config
|
||||||
|
|
||||||
|
log = logging.getLogger("fengxiang.notify")
|
||||||
|
|
||||||
|
|
||||||
|
class Channel(Protocol):
|
||||||
|
name: str
|
||||||
|
|
||||||
|
def send(self, text: str) -> None: # pragma: no cover - 协议声明
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
class WecomChannel:
|
||||||
|
name = "wecom"
|
||||||
|
|
||||||
|
def __init__(self, webhook: str, timeout: int = 10):
|
||||||
|
self.webhook = webhook
|
||||||
|
self.timeout = timeout
|
||||||
|
|
||||||
|
def send(self, text: str) -> None:
|
||||||
|
payload = {"msgtype": "text", "text": {"content": text}}
|
||||||
|
resp = requests.post(self.webhook, json=payload, timeout=self.timeout)
|
||||||
|
data = resp.json()
|
||||||
|
if data.get("errcode") != 0:
|
||||||
|
raise RuntimeError(f"企业微信返回错误: {data}")
|
||||||
|
|
||||||
|
|
||||||
|
class FeishuChannel:
|
||||||
|
name = "feishu"
|
||||||
|
|
||||||
|
def __init__(self, webhook: str, timeout: int = 10):
|
||||||
|
self.webhook = webhook
|
||||||
|
self.timeout = timeout
|
||||||
|
|
||||||
|
def send(self, text: str) -> None:
|
||||||
|
payload = {"msg_type": "text", "content": {"text": text}}
|
||||||
|
resp = requests.post(self.webhook, json=payload, timeout=self.timeout)
|
||||||
|
data = resp.json()
|
||||||
|
# 飞书新老版本返回结构不同,统一取出成功标志
|
||||||
|
code = data.get("code", data.get("StatusCode"))
|
||||||
|
if code != 0:
|
||||||
|
raise RuntimeError(f"飞书返回错误: {data}")
|
||||||
|
|
||||||
|
|
||||||
|
def build_channels(cfg: Config) -> List[Channel]:
|
||||||
|
channels: List[Channel] = []
|
||||||
|
for name in cfg.notify.channels:
|
||||||
|
if name == "wecom" and cfg.notify.wecom_webhook:
|
||||||
|
channels.append(WecomChannel(cfg.notify.wecom_webhook))
|
||||||
|
elif name == "feishu" and cfg.notify.feishu_enabled and cfg.notify.feishu_webhook:
|
||||||
|
channels.append(FeishuChannel(cfg.notify.feishu_webhook))
|
||||||
|
else:
|
||||||
|
log.warning("通道 %s 已配置但缺少 webhook/token,跳过", name)
|
||||||
|
return channels
|
||||||
|
|
||||||
|
|
||||||
|
class Dispatcher:
|
||||||
|
def __init__(self, channels: List[Channel], alert_cooldown_sec: int = 1800):
|
||||||
|
self.channels = channels
|
||||||
|
self.alert_cooldown_sec = alert_cooldown_sec
|
||||||
|
self._last_alert: Dict[str, float] = {}
|
||||||
|
|
||||||
|
def notify(self, text: str) -> Dict[str, bool]:
|
||||||
|
"""广播一条消息,返回各通道成功与否。异常不外抛。"""
|
||||||
|
result: Dict[str, bool] = {}
|
||||||
|
for ch in self.channels:
|
||||||
|
try:
|
||||||
|
ch.send(text)
|
||||||
|
result[ch.name] = True
|
||||||
|
log.info("推送成功 [%s] %s", ch.name, text.replace("\n", " ")[:80])
|
||||||
|
except Exception as exc: # noqa: BLE001 - 推送失败绝不能让监控挂掉
|
||||||
|
result[ch.name] = False
|
||||||
|
log.error("推送失败 [%s]: %s", ch.name, exc)
|
||||||
|
if not self.channels:
|
||||||
|
log.warning("未配置任何推送通道,消息未发出: %s", text)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def alert(self, key: str, text: str) -> Tuple[bool, str]:
|
||||||
|
"""带冷却的告警。同一 key 在冷却期内不重复发送。"""
|
||||||
|
now = time.time()
|
||||||
|
last = self._last_alert.get(key, 0)
|
||||||
|
if now - last < self.alert_cooldown_sec:
|
||||||
|
log.debug("告警 %s 处于冷却期,跳过", key)
|
||||||
|
return False, "cooldown"
|
||||||
|
self._last_alert[key] = now
|
||||||
|
self.notify(text)
|
||||||
|
return True, "sent"
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
"""运行状态持久化。
|
||||||
|
|
||||||
|
解决原项目两个真实问题:
|
||||||
|
1. 进程重启后 last_order_id 丢失 → 靠「取当前最新」兜底,但拉单失败时会重推历史订单
|
||||||
|
2. 一次拉取超过 page_size 时,仅靠 orderId 断点会漏单
|
||||||
|
|
||||||
|
因此这里同时保存 last_order_id 和最近推送过的订单号集合(去重兜底)。
|
||||||
|
写入采用 tmp + os.replace 原子替换,避免断电/被杀留下半个 JSON。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, Iterable, List, Optional
|
||||||
|
|
||||||
|
log = logging.getLogger("fengxiang.store")
|
||||||
|
|
||||||
|
MAX_PUSHED_IDS = 500
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class State:
|
||||||
|
last_order_id: Optional[str] = None
|
||||||
|
pushed_ids: List[str] = field(default_factory=list)
|
||||||
|
last_poll_ts: float = 0.0
|
||||||
|
cookie_updated_ts: float = 0.0
|
||||||
|
cookie_valid: bool = False
|
||||||
|
gap_since_ts: float = 0.0 # 最近一次进入「会话失效」的时刻
|
||||||
|
total_pushed: int = 0
|
||||||
|
# 运行时字段,不落盘
|
||||||
|
_path: Optional[Path] = field(default=None, repr=False, compare=False)
|
||||||
|
|
||||||
|
# ---------------- 持久化 ----------------
|
||||||
|
@classmethod
|
||||||
|
def load(cls, path: Path) -> "State":
|
||||||
|
state = cls(_path=Path(path))
|
||||||
|
if Path(path).exists():
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
state.last_order_id = str(data["last_order_id"]) if data.get("last_order_id") else None
|
||||||
|
state.pushed_ids = [str(i) for i in data.get("pushed_ids", [])]
|
||||||
|
state.last_poll_ts = float(data.get("last_poll_ts") or 0)
|
||||||
|
state.cookie_updated_ts = float(data.get("cookie_updated_ts") or 0)
|
||||||
|
state.cookie_valid = bool(data.get("cookie_valid"))
|
||||||
|
state.gap_since_ts = float(data.get("gap_since_ts") or 0)
|
||||||
|
state.total_pushed = int(data.get("total_pushed") or 0)
|
||||||
|
log.info("已加载状态: last_order_id=%s 去重缓存=%d 条",
|
||||||
|
state.last_order_id, len(state.pushed_ids))
|
||||||
|
except (OSError, ValueError, KeyError, TypeError) as exc:
|
||||||
|
log.warning("状态文件损坏,按全新状态启动: %s", exc)
|
||||||
|
return state
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"last_order_id": self.last_order_id,
|
||||||
|
"pushed_ids": self.pushed_ids[-MAX_PUSHED_IDS:],
|
||||||
|
"last_poll_ts": self.last_poll_ts,
|
||||||
|
"cookie_updated_ts": self.cookie_updated_ts,
|
||||||
|
"cookie_valid": self.cookie_valid,
|
||||||
|
"gap_since_ts": self.gap_since_ts,
|
||||||
|
"total_pushed": self.total_pushed,
|
||||||
|
}
|
||||||
|
|
||||||
|
def save(self, path: Optional[Path] = None) -> None:
|
||||||
|
target = Path(path or self._path or "state.json")
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
tmp = target.with_suffix(target.suffix + ".tmp")
|
||||||
|
with open(tmp, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(self.to_dict(), f, ensure_ascii=False, indent=2)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
os.replace(tmp, target)
|
||||||
|
|
||||||
|
# ---------------- 业务方法 ----------------
|
||||||
|
def has_pushed(self, order_id: str) -> bool:
|
||||||
|
return str(order_id) in self.pushed_ids
|
||||||
|
|
||||||
|
def mark_pushed(self, order_ids: Iterable[str]) -> None:
|
||||||
|
ids = [str(i) for i in order_ids]
|
||||||
|
self.pushed_ids.extend(ids)
|
||||||
|
self.total_pushed += len(ids)
|
||||||
|
if len(self.pushed_ids) > MAX_PUSHED_IDS:
|
||||||
|
self.pushed_ids = self.pushed_ids[-MAX_PUSHED_IDS:]
|
||||||
|
|
||||||
|
def touch_poll(self) -> None:
|
||||||
|
self.last_poll_ts = time.time()
|
||||||
|
|
||||||
|
|
||||||
|
def atomic_write_json(path: Path, data: Any) -> None:
|
||||||
|
"""供管理接口写 cookies 复用。"""
|
||||||
|
path = Path(path)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||||
|
with open(tmp, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
os.replace(tmp, path)
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""本地语音播报(仅本地 Windows 模式使用,容器内自动禁用)。
|
||||||
|
|
||||||
|
原来 speak() 是同步调用:IndexTTS2 首次加载模型要 1-2 分钟,合成每次几秒,
|
||||||
|
直接卡在轮询主循环里,导致监控间隔完全失真。这里改为后台线程 + 队列。
|
||||||
|
|
||||||
|
服务器(Linux/容器)没有声卡也不装 torch,所以此模块在非 Windows 上直接降级为 no-op。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import queue
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
log = logging.getLogger("fengxiang.tts")
|
||||||
|
|
||||||
|
|
||||||
|
class Speaker:
|
||||||
|
def __init__(self, voice_prompt: str = "", enabled: bool = True):
|
||||||
|
self.enabled = bool(enabled) and sys.platform == "win32"
|
||||||
|
self.voice_prompt = voice_prompt or None
|
||||||
|
self._queue: "queue.Queue[Optional[str]]" = queue.Queue(maxsize=20)
|
||||||
|
self._thread: Optional[threading.Thread] = None
|
||||||
|
self._impl = None
|
||||||
|
if enabled and not self.enabled:
|
||||||
|
log.info("当前平台 %s 不支持本地播报,已自动禁用 TTS", sys.platform)
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
if not self.enabled or self._thread:
|
||||||
|
return
|
||||||
|
self._thread = threading.Thread(target=self._worker, name="tts", daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
|
def say(self, text: str) -> None:
|
||||||
|
"""非阻塞投递,队列满则丢弃并告警(绝不阻塞监控)。"""
|
||||||
|
if not self.enabled:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self._queue.put_nowait(text)
|
||||||
|
except queue.Full:
|
||||||
|
log.warning("TTS 队列已满,丢弃本次播报")
|
||||||
|
|
||||||
|
def _worker(self) -> None:
|
||||||
|
while True:
|
||||||
|
text = self._queue.get()
|
||||||
|
if text is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if self._impl is None:
|
||||||
|
from local_tts import speak as local_speak # 延迟导入,避免无依赖时启动失败
|
||||||
|
self._impl = local_speak
|
||||||
|
self._impl(text, voice_prompt=self.voice_prompt)
|
||||||
|
log.info("语音播报完成: %s", text)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log.error("语音播报失败: %s", exc)
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
if not self.enabled:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self._queue.put_nowait(None)
|
||||||
|
except queue.Full:
|
||||||
|
pass
|
||||||
+105
-72
@@ -1,114 +1,147 @@
|
|||||||
"""
|
"""本机登录丰享商家端,拿到 Cookie 并(可选)上传到服务器。
|
||||||
丰享商家端数据抓取脚本
|
|
||||||
使用 Playwright 半自动登录 + requests 调用数据接口
|
为什么必须在本机跑:丰享登录有腾讯 TCaptcha 滑块/点选,无法纯接口绕过,
|
||||||
|
服务器上又是无桌面的容器,所以把「人工过验证码」这一步留在本机。
|
||||||
|
|
||||||
|
流程:
|
||||||
|
1. Playwright 打开登录页(有头模式),你手动输入账号密码 + 过验证码
|
||||||
|
2. 检测到跳转 MMS 后提取 Cookie → 保存到 ./data/cookies.json
|
||||||
|
3. --upload 时 POST 到服务器管理接口,监控进程立即热加载,无需重启
|
||||||
|
|
||||||
|
用法:
|
||||||
|
python fengxiang_scraper.py # 只登录并保存
|
||||||
|
python fengxiang_scraper.py --upload # 登录 + 上传(地址取环境变量)
|
||||||
|
python fengxiang_scraper.py --upload --server http://192.168.8.210:52100 --token xxx
|
||||||
|
|
||||||
|
环境变量:FX_SERVER / FX_ADMIN_TOKEN / FX_CONFIG
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
import json
|
import json
|
||||||
|
import sys
|
||||||
import time
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from playwright.sync_api import sync_playwright
|
|
||||||
|
|
||||||
# ============ 配置 ============
|
from fengxiang.config import load_config
|
||||||
LOGIN_URL = "https://fspass.szfx.com/ucenter/userlogin?platform=saas&redirect_url=https%3A%2F%2Ffs.szfx.com%2FMMS%23%2F&return_url=https%3A%2F%2Ffs.szfx.com%2Fsaasmerchant%2Fsetstoken"
|
|
||||||
DATA_API = "https://fs.szfx.com/saasmerchant/pcweb/order/quickpayorder/list"
|
|
||||||
MMS_BASE = "https://fs.szfx.com/MMS"
|
MMS_BASE = "https://fs.szfx.com/MMS"
|
||||||
SHOP_ID = "20434543575189"
|
LOGIN_TIMEOUT_MS = 600_000 # 10 分钟
|
||||||
# ==============================
|
|
||||||
|
|
||||||
|
|
||||||
def login_and_get_cookies():
|
def login_with_browser(login_url: str) -> dict[str, str] | None:
|
||||||
"""用 Playwright 打开登录页,等待用户手动登录,然后提取 Cookie"""
|
try:
|
||||||
print("[1/3] 启动浏览器,请手动完成登录(包括验证码)...")
|
from playwright.sync_api import sync_playwright
|
||||||
|
except ImportError:
|
||||||
|
print("[错误] 未安装 playwright:pip install playwright && playwright install chromium", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
print("[1/3] 启动浏览器,请在窗口中完成登录(账号密码 + 验证码)...")
|
||||||
with sync_playwright() as p:
|
with sync_playwright() as p:
|
||||||
browser = p.chromium.launch(headless=False, args=["--start-maximized"])
|
browser = p.chromium.launch(headless=False, args=["--start-maximized"])
|
||||||
context = browser.new_context(no_viewport=True)
|
context = browser.new_context(no_viewport=True)
|
||||||
page = context.new_page()
|
page = context.new_page()
|
||||||
|
page.goto(login_url)
|
||||||
|
|
||||||
page.goto(LOGIN_URL)
|
print("[2/3] 等待登录完成(最多 10 分钟)...")
|
||||||
|
|
||||||
# 等待用户登录成功(检测页面跳转到 MMS 首页)
|
|
||||||
print("[2/3] 等待登录完成...(请在浏览器中输入账号密码并完成验证码)")
|
|
||||||
try:
|
try:
|
||||||
page.wait_for_url("**/MMS**", timeout=300_000)
|
page.wait_for_url("**/MMS**", timeout=LOGIN_TIMEOUT_MS)
|
||||||
print(" 登录成功!正在提取 Cookie...")
|
print(" 登录成功,正在提取 Cookie...")
|
||||||
except Exception:
|
except Exception:
|
||||||
print(" 等待超时(5分钟),请重新运行脚本。")
|
print(" 等待超时,已退出。请重新运行。", file=sys.stderr)
|
||||||
browser.close()
|
browser.close()
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# 确保访问过目标页面(触发必要的 Cookie 设置)
|
# 访问一次首页,确保必要的 Cookie 都下发了
|
||||||
|
try:
|
||||||
page.goto(MMS_BASE)
|
page.goto(MMS_BASE)
|
||||||
page.wait_for_load_state("networkidle")
|
page.wait_for_load_state("networkidle", timeout=30_000)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
|
||||||
# 提取所有 Cookie
|
cookies = {c["name"]: c["value"] for c in context.cookies()}
|
||||||
playwright_cookies = context.cookies()
|
|
||||||
cookies = {c["name"]: c["value"] for c in playwright_cookies}
|
|
||||||
|
|
||||||
print(f" 获取到 {len(cookies)} 个 Cookie")
|
|
||||||
browser.close()
|
browser.close()
|
||||||
|
|
||||||
|
print(f"[3/3] 提取到 {len(cookies)} 个 Cookie")
|
||||||
return cookies
|
return cookies
|
||||||
|
|
||||||
|
|
||||||
def fetch_order_list(cookies, page=1, page_size=20):
|
def verify(cookies: dict[str, str]) -> bool:
|
||||||
"""调用快捷买单订单列表接口"""
|
"""本地先验一次,避免把坏 Cookie 推上去。"""
|
||||||
headers = {
|
import requests as _rq
|
||||||
|
resp = _rq.post(
|
||||||
|
"https://fs.szfx.com/saasmerchant/pcweb/order/quickpayorder/list",
|
||||||
|
json={"shopId": "20434543575189", "page": 1, "pageSize": 1},
|
||||||
|
headers={
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
"Referer": MMS_BASE,
|
||||||
"Referer": "https://fs.szfx.com/MMS",
|
|
||||||
"Origin": "https://fs.szfx.com",
|
"Origin": "https://fs.szfx.com",
|
||||||
}
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
|
||||||
|
},
|
||||||
payload = {
|
cookies=cookies,
|
||||||
"shopId": SHOP_ID,
|
timeout=20,
|
||||||
"page": page,
|
)
|
||||||
"pageSize": page_size,
|
|
||||||
}
|
|
||||||
|
|
||||||
print(f"[3/3] 正在请求订单数据(第{page}页)...")
|
|
||||||
resp = requests.post(DATA_API, json=payload, headers=headers, cookies=cookies, timeout=30)
|
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
|
|
||||||
if data.get("errno") == 0:
|
if data.get("errno") == 0:
|
||||||
print(" 请求成功!")
|
orders = (data.get("data") or {}).get("list") or []
|
||||||
return data.get("data")
|
latest = orders[0].get("orderId") if orders else None
|
||||||
else:
|
print(f" Cookie 校验通过(最新订单 {latest})")
|
||||||
print(f" 请求失败: errno={data.get('errno')}, errmsg={data.get('errmsg')}")
|
return True
|
||||||
return None
|
print(f" Cookie 校验失败:errno={data.get('errno')} {data.get('errmsg')}", file=sys.stderr)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def save_data(data, filename="order_data.json"):
|
def upload(server: str, token: str, cookies: dict[str, str]) -> bool:
|
||||||
"""保存数据到文件"""
|
url = server.rstrip("/") + "/api/cookies"
|
||||||
with open(filename, "w", encoding="utf-8") as f:
|
headers = {"Content-Type": "application/json"}
|
||||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
if token:
|
||||||
print(f" 数据已保存到 {filename}")
|
headers["X-Auth-Token"] = token
|
||||||
|
print(f" 上传到 {url} ...")
|
||||||
|
try:
|
||||||
|
resp = requests.post(url, json={"cookies": cookies}, headers=headers, timeout=20)
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
print(f" 上传失败(网络):{exc}", file=sys.stderr)
|
||||||
|
return False
|
||||||
|
print(f" HTTP {resp.status_code} {resp.text[:300]}")
|
||||||
|
return resp.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main() -> int:
|
||||||
# 第一步:登录获取 Cookie
|
parser = argparse.ArgumentParser(description="丰享商家端登录并同步 Cookie")
|
||||||
cookies = login_and_get_cookies()
|
parser.add_argument("--upload", action="store_true", help="登录成功后上传到服务器")
|
||||||
|
parser.add_argument("--server", default=None, help="服务器地址,如 http://192.168.8.210:52100")
|
||||||
|
parser.add_argument("--token", default=None, help="管理接口 token")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
cfg = load_config()
|
||||||
|
cookies = login_with_browser(cfg.api.login_url)
|
||||||
if not cookies:
|
if not cookies:
|
||||||
return
|
return 1
|
||||||
|
|
||||||
# 保存 Cookie 以便下次复用
|
if not verify(cookies):
|
||||||
with open("cookies.json", "w", encoding="utf-8") as f:
|
print("Cookie 不可用,未保存。", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
|
||||||
|
out = Path(cfg.paths.cookies)
|
||||||
|
out.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with open(out, "w", encoding="utf-8") as f:
|
||||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||||
print(" Cookie 已保存到 cookies.json(下次可直接使用)\n")
|
print(f" 已保存到 {out}")
|
||||||
|
|
||||||
# 第二步:获取订单数据
|
if args.upload:
|
||||||
result = fetch_order_list(cookies)
|
import os
|
||||||
if result:
|
server = args.server or os.environ.get("FX_SERVER")
|
||||||
save_data(result)
|
token = args.token or os.environ.get("FX_ADMIN_TOKEN") or cfg.admin.token
|
||||||
# 打印摘要
|
if not server:
|
||||||
if isinstance(result, dict):
|
print("[错误] 未指定服务器:用 --server 或环境变量 FX_SERVER", file=sys.stderr)
|
||||||
print(f"\n 数据摘要:")
|
return 3
|
||||||
for k, v in result.items():
|
return 0 if upload(server, token, cookies) else 4
|
||||||
if not isinstance(v, (list, dict)):
|
return 0
|
||||||
print(f" {k}: {v}")
|
|
||||||
elif isinstance(v, list):
|
|
||||||
print(f" {k}: 共 {len(v)} 条记录")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
sys.exit(main())
|
||||||
+47
-39
@@ -1,52 +1,60 @@
|
|||||||
|
"""命令行工具:复用 Cookie 拉取订单列表并打印。
|
||||||
|
|
||||||
|
python fetch_orders.py # 第 1 页,20 条
|
||||||
|
python fetch_orders.py 2 50 # 第 2 页,50 条
|
||||||
|
python fetch_orders.py --json # 输出原始 JSON
|
||||||
"""
|
"""
|
||||||
丰享商家端数据抓取 - Cookie 复用模式
|
|
||||||
已有 cookies.json 时直接调用接口,Cookie 过期再运行主脚本重新登录
|
from __future__ import annotations
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
import sys
|
import sys
|
||||||
import requests
|
|
||||||
|
|
||||||
DATA_API = "https://fs.szfx.com/saasmerchant/pcweb/order/quickpayorder/list"
|
from fengxiang.client import ApiError, FengxiangClient, NetworkError, SessionExpired
|
||||||
SHOP_ID = "20434543575189"
|
from fengxiang.config import load_config
|
||||||
|
from fengxiang.logger import setup_logging
|
||||||
|
|
||||||
|
|
||||||
def load_cookies():
|
def main(argv: list[str]) -> int:
|
||||||
|
cfg = load_config()
|
||||||
|
setup_logging(cfg.paths.logs, cfg.log.level, cfg.log.max_bytes, cfg.log.backup_count)
|
||||||
|
logging.getLogger("fengxiang").setLevel(logging.WARNING)
|
||||||
|
|
||||||
|
as_json = "--json" in argv
|
||||||
|
nums = [a for a in argv if a.isdigit()]
|
||||||
|
page = int(nums[0]) if len(nums) > 0 else 1
|
||||||
|
page_size = int(nums[1]) if len(nums) > 1 else 20
|
||||||
|
|
||||||
|
monitor_cookies = None
|
||||||
|
if cfg.paths.cookies.exists():
|
||||||
|
with open(cfg.paths.cookies, "r", encoding="utf-8") as f:
|
||||||
|
monitor_cookies = json.load(f)
|
||||||
|
if not monitor_cookies:
|
||||||
|
print(f"未找到 Cookie:{cfg.paths.cookies}\n请先运行 fengxiang_scraper.py 完成登录", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
client = FengxiangClient(cfg)
|
||||||
|
client.set_cookies(monitor_cookies)
|
||||||
try:
|
try:
|
||||||
with open("cookies.json", "r", encoding="utf-8") as f:
|
orders = client.list_orders(page_size=page_size, page=page)
|
||||||
return json.load(f)
|
except SessionExpired:
|
||||||
except FileNotFoundError:
|
print("Cookie 已失效,请重新运行 fengxiang_scraper.py", file=sys.stderr)
|
||||||
print("未找到 cookies.json,请先运行 fengxiang_scraper.py 完成登录")
|
return 2
|
||||||
sys.exit(1)
|
except (ApiError, NetworkError) as exc:
|
||||||
|
print(f"请求失败:{exc}", file=sys.stderr)
|
||||||
|
return 3
|
||||||
|
|
||||||
|
if as_json:
|
||||||
def fetch_order_list(cookies, page=1, page_size=20):
|
print(json.dumps(orders, ensure_ascii=False, indent=2))
|
||||||
headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
|
||||||
"Referer": "https://fs.szfx.com/MMS",
|
|
||||||
"Origin": "https://fs.szfx.com",
|
|
||||||
}
|
|
||||||
payload = {"shopId": SHOP_ID, "page": page, "pageSize": page_size}
|
|
||||||
resp = requests.post(DATA_API, json=payload, headers=headers, cookies=cookies, timeout=30)
|
|
||||||
return resp.json()
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
cookies = load_cookies()
|
|
||||||
print(f"已加载 {len(cookies)} 个 Cookie")
|
|
||||||
|
|
||||||
page = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
|
||||||
result = fetch_order_list(cookies, page=page)
|
|
||||||
|
|
||||||
if result.get("errno") == 0:
|
|
||||||
data = result.get("data")
|
|
||||||
print(json.dumps(data, ensure_ascii=False, indent=2))
|
|
||||||
elif result.get("errno") == 110003:
|
|
||||||
print("Cookie 已过期,请重新运行 fengxiang_scraper.py 完成登录")
|
|
||||||
else:
|
else:
|
||||||
print(f"请求失败: {result}")
|
print(f"共 {len(orders)} 条(第 {page} 页,每页 {page_size})")
|
||||||
|
for o in orders:
|
||||||
|
cents = o.get("amountPayable") or 0
|
||||||
|
print(f" {o.get('orderId')} {cents / 100:>8.2f}元 "
|
||||||
|
f"{o.get('shopName', '')} {o.get('payTypeName', '')}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
sys.exit(main(sys.argv[1:]))
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""容器健康检查:判断进程是否还"在干活",而不只是端口通。
|
||||||
|
|
||||||
|
规则:
|
||||||
|
- 夜间暂停 / 尚未建立 Cookie 校验 -> 视为健康(属于预期状态)
|
||||||
|
- 最近一次成功轮询距今超过 15 分钟(且不是夜间)-> 不健康,交给 Docker 重启
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen("http://127.0.0.1:8089/healthz", timeout=5) as resp:
|
||||||
|
data = json.load(resp)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
print(f"healthz 不可达: {exc}")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
mode = data.get("mode")
|
||||||
|
age = data.get("last_poll_age_sec")
|
||||||
|
print(json.dumps(data, ensure_ascii=False))
|
||||||
|
|
||||||
|
if mode == "night":
|
||||||
|
return 0
|
||||||
|
if age is None:
|
||||||
|
# 启动阶段还没跑出第一轮,给 15 分钟宽限
|
||||||
|
return 0 if (data.get("uptime_sec") or 0) < 900 else 1
|
||||||
|
return 0 if age < 900 else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
+37
-35
@@ -1,66 +1,68 @@
|
|||||||
"""
|
"""本地 TTS 语音播报(IndexTTS2),仅 Windows 本地模式使用。
|
||||||
本地TTS语音播报模块 - 基于IndexTTS2
|
|
||||||
|
服务器/容器不会启用(无 torch、无声卡),由 fengxiang.tts.Speaker 在非 win32 平台直接跳过。
|
||||||
|
|
||||||
|
路径可通过环境变量覆盖,不再写死 E:\\:
|
||||||
|
FX_INDEXTTS_HOME IndexTTS2 工程目录
|
||||||
|
FX_INDEXTTS_VOICE 参考音色 wav 路径
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import time
|
|
||||||
import tempfile
|
import tempfile
|
||||||
import winsound
|
import time
|
||||||
|
|
||||||
# IndexTTS2 路径配置
|
_INDEXTTS_HOME = os.environ.get("FX_INDEXTTS_HOME", r"E:\2025Code\python\IndexTT\index-tts")
|
||||||
_INDEXTTS_HOME = r"E:\2025Code\python\IndexTT\index-tts"
|
|
||||||
_INDEXTTS_MODEL_DIR = os.path.join(_INDEXTTS_HOME, "checkpoints")
|
_INDEXTTS_MODEL_DIR = os.path.join(_INDEXTTS_HOME, "checkpoints")
|
||||||
_INDEXTTS_CFG = os.path.join(_INDEXTTS_MODEL_DIR, "config.yaml")
|
_INDEXTTS_CFG = os.path.join(_INDEXTTS_MODEL_DIR, "config.yaml")
|
||||||
_INDEXTTS_VENV_PYTHON = os.path.join(_INDEXTTS_HOME, ".venv", "Scripts", "python.exe")
|
_DEFAULT_VOICE_PROMPT = os.environ.get(
|
||||||
|
"FX_INDEXTTS_VOICE", os.path.join(_INDEXTTS_HOME, "examples", "voice_01.wav")
|
||||||
|
)
|
||||||
|
|
||||||
# 默认语音样本
|
|
||||||
_DEFAULT_VOICE_PROMPT = os.path.join(_INDEXTTS_HOME, "examples", "voice_01.wav")
|
|
||||||
|
|
||||||
# 全局 TTS 实例(延迟初始化)
|
|
||||||
_tts_instance = None
|
_tts_instance = None
|
||||||
|
|
||||||
|
|
||||||
def _get_tts():
|
def _get_tts():
|
||||||
"""延迟初始化 IndexTTS2 实例"""
|
"""延迟初始化 IndexTTS2(首次加载模型 1-2 分钟)。"""
|
||||||
global _tts_instance
|
global _tts_instance
|
||||||
if _tts_instance is None:
|
if _tts_instance is None:
|
||||||
|
if not os.path.isdir(_INDEXTTS_HOME):
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"未找到 IndexTTS2 目录: {_INDEXTTS_HOME}(可用 FX_INDEXTTS_HOME 指定)"
|
||||||
|
)
|
||||||
sys.path.insert(0, _INDEXTTS_HOME)
|
sys.path.insert(0, _INDEXTTS_HOME)
|
||||||
from indextts.infer_v2 import IndexTTS2
|
from indextts.infer_v2 import IndexTTS2
|
||||||
print("[TTS] 正在加载 IndexTTS2 模型(首次加载较慢,请耐心等待)...")
|
|
||||||
|
print("[TTS] 正在加载 IndexTTS2 模型(首次较慢)...")
|
||||||
_tts_instance = IndexTTS2(
|
_tts_instance = IndexTTS2(
|
||||||
cfg_path=_INDEXTTS_CFG,
|
cfg_path=_INDEXTTS_CFG,
|
||||||
model_dir=_INDEXTTS_MODEL_DIR,
|
model_dir=_INDEXTTS_MODEL_DIR,
|
||||||
use_fp16=True,
|
use_fp16=True,
|
||||||
use_cuda_kernel=False,
|
use_cuda_kernel=False,
|
||||||
use_deepspeed=False
|
use_deepspeed=False,
|
||||||
)
|
)
|
||||||
print("[TTS] IndexTTS2 模型加载完成")
|
print("[TTS] 模型加载完成")
|
||||||
return _tts_instance
|
return _tts_instance
|
||||||
|
|
||||||
|
|
||||||
def speak(text, voice_prompt=None):
|
def speak(text: str, voice_prompt: str | None = None) -> str:
|
||||||
"""使用本地 IndexTTS2 合成语音并播放
|
"""合成并播放,返回生成的 wav 路径。"""
|
||||||
|
if sys.platform != "win32":
|
||||||
|
raise RuntimeError("本地 TTS 仅支持 Windows(依赖 winsound)")
|
||||||
|
|
||||||
Args:
|
import winsound
|
||||||
text: 要播报的文本
|
|
||||||
voice_prompt: 语音样本路径,默认使用 voice_01.wav
|
voice_prompt = voice_prompt or _DEFAULT_VOICE_PROMPT
|
||||||
"""
|
if not os.path.exists(voice_prompt):
|
||||||
if voice_prompt is None:
|
raise FileNotFoundError(f"参考音色不存在: {voice_prompt}")
|
||||||
voice_prompt = _DEFAULT_VOICE_PROMPT
|
|
||||||
|
|
||||||
tts = _get_tts()
|
tts = _get_tts()
|
||||||
output_path = os.path.join(tempfile.gettempdir(), f"fx_tts_{int(time.time() * 1000)}.wav")
|
out = os.path.join(tempfile.gettempdir(), f"fx_tts_{int(time.time() * 1000)}.wav")
|
||||||
|
tts.infer(spk_audio_prompt=voice_prompt, text=text, output_path=out, verbose=False)
|
||||||
tts.infer(
|
winsound.PlaySound(out, winsound.SND_FILENAME)
|
||||||
spk_audio_prompt=voice_prompt,
|
return out
|
||||||
text=text,
|
|
||||||
output_path=output_path,
|
|
||||||
verbose=False
|
|
||||||
)
|
|
||||||
|
|
||||||
# 播放生成的音频
|
|
||||||
winsound.PlaySound(output_path, winsound.SND_FILENAME)
|
|
||||||
return output_path
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
@echo off
|
||||||
|
chcp 65001 >nul
|
||||||
|
title 丰享登录并同步 Cookie
|
||||||
|
cd /d "%~dp0"
|
||||||
|
|
||||||
|
echo ============================================
|
||||||
|
echo 登录丰享商家端,并把 Cookie 同步到服务器
|
||||||
|
echo ============================================
|
||||||
|
echo.
|
||||||
|
|
||||||
|
set "PYTHON="
|
||||||
|
if exist ".venv\Scripts\python.exe" set "PYTHON=.venv\Scripts\python.exe"
|
||||||
|
if not defined PYTHON if defined FX_PYTHON set "PYTHON=%FX_PYTHON%"
|
||||||
|
if not defined PYTHON set "PYTHON=python"
|
||||||
|
|
||||||
|
"%PYTHON%" -c "import playwright" >nul 2>&1
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo [准备] 安装 Playwright...
|
||||||
|
"%PYTHON%" -m pip install -r requirements-local.txt
|
||||||
|
"%PYTHON%" -m playwright install chromium
|
||||||
|
)
|
||||||
|
|
||||||
|
:: 服务器地址与 token:优先用环境变量,也可直接改下面两行
|
||||||
|
if not defined FX_SERVER set "FX_SERVER=http://192.168.8.210:52100"
|
||||||
|
if not defined FX_ADMIN_TOKEN (
|
||||||
|
echo [错误] 请先设置管理接口 token,例如:
|
||||||
|
echo set FX_ADMIN_TOKEN=你的token
|
||||||
|
echo token 与服务器 config.yaml 里 admin.token 一致
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
echo [1/2] 打开浏览器登录丰享...
|
||||||
|
echo.
|
||||||
|
"%PYTHON%" fengxiang_scraper.py --upload --server "%FX_SERVER%"
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo [2/2] 完成。若提示上传失败,请检查服务器地址/token。
|
||||||
|
pause
|
||||||
+28
-295
@@ -1,307 +1,40 @@
|
|||||||
"""
|
"""丰享订单监控 v5 —— 统一入口(本地 Windows / 服务器容器共用)。
|
||||||
丰享订单监控 v4
|
|
||||||
- 优先使用 Cookie 文件请求 API,无需每次都打开浏览器
|
用法:
|
||||||
- Cookie 过期时自动打开浏览器提示重新登录
|
python order_monitor.py # 读 ./config.yaml(或 FX_CONFIG 指定)
|
||||||
- 晚上 21:00 到早上 7:40 自动暂停
|
FX_CONFIG=/app/config.yaml python order_monitor.py
|
||||||
- 高峰期缩短间隔,闲时拉长间隔
|
|
||||||
|
环境变量见 config.example.yaml 注释。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
from __future__ import annotations
|
||||||
import random
|
|
||||||
import time
|
|
||||||
import datetime
|
|
||||||
import requests
|
|
||||||
from pathlib import Path
|
|
||||||
from playwright.sync_api import sync_playwright
|
|
||||||
from local_tts import speak as _local_speak
|
|
||||||
|
|
||||||
# ============ 配置 ============
|
import logging
|
||||||
LOGIN_URL = "https://fspass.szfx.com/ucenter/userlogin?platform=saas&redirect_url=https%3A%2F%2Ffs.szfx.com%2FMMS%23%2F&return_url=https%3A%2F%2Ffs.szfx.com%2Fsaasmerchant%2Fsetstoken"
|
import os
|
||||||
DATA_API = "https://fs.szfx.com/saasmerchant/pcweb/order/quickpayorder/list"
|
import sys
|
||||||
SHOP_ID = "20434543575189"
|
|
||||||
WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=644ab6d9-3b66-4166-88e9-5a8a89e3731d"
|
|
||||||
FEISHU_WEBHOOK_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/oc_d5ef8b1abf66842c28ef57e1658dc096"
|
|
||||||
COOKIES_FILE = "cookies.json"
|
|
||||||
|
|
||||||
# 本地 TTS 配置(使用 IndexTTS2,无需额外配置)
|
from fengxiang import __version__
|
||||||
|
from fengxiang.config import load_config
|
||||||
# 高峰时段配置
|
from fengxiang.logger import setup_logging
|
||||||
PEAK_HOURS = [(11, 13), (17, 19)]
|
from fengxiang.monitor import Monitor
|
||||||
POLL_INTERVAL_MIN = 5
|
|
||||||
POLL_INTERVAL_MAX = 10
|
|
||||||
PEAK_PAGE_SIZE = 20
|
|
||||||
IDLE_PAGE_SIZE = 5
|
|
||||||
|
|
||||||
# 夜间暂停:21:00 ~ 07:40 不轮询
|
|
||||||
NIGHT_START_H = 21
|
|
||||||
NIGHT_END_H = 7
|
|
||||||
NIGHT_END_M = 40
|
|
||||||
|
|
||||||
KEEPALIVE_INTERVAL = 300 # 每5分钟保活一次
|
|
||||||
# ==============================
|
|
||||||
|
|
||||||
|
|
||||||
def fmt_money(cents):
|
def main() -> int:
|
||||||
return f"{cents / 100:.2f}元" if cents else "0.00元"
|
cfg_path = os.environ.get("FX_CONFIG") or "config.yaml"
|
||||||
|
if not os.path.exists(cfg_path):
|
||||||
|
print(f"[提示] 未找到配置文件 {cfg_path},使用内置默认值 + 环境变量", file=sys.stderr)
|
||||||
|
|
||||||
|
cfg = load_config(cfg_path)
|
||||||
|
setup_logging(cfg.paths.logs, cfg.log.level, cfg.log.max_bytes, cfg.log.backup_count)
|
||||||
|
log = logging.getLogger("fengxiang")
|
||||||
|
|
||||||
def log(msg):
|
if not cfg.notify.channels:
|
||||||
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
log.error("没有任何可用的推送通道,请配置 notify.wecom.webhook 或 FX_WECOM_WEBHOOK")
|
||||||
print(f"[{now}] {msg}")
|
|
||||||
|
|
||||||
|
log.info("版本 %s | Python %s", __version__, sys.version.split()[0])
|
||||||
def is_peak_hour():
|
Monitor(cfg).run()
|
||||||
hour = datetime.datetime.now().hour
|
return 0
|
||||||
return any(start <= hour < end for start, end in PEAK_HOURS)
|
|
||||||
|
|
||||||
|
|
||||||
def is_night_time():
|
|
||||||
"""是否在夜间暂停时段 (21:00 ~ 07:40)"""
|
|
||||||
now = datetime.datetime.now()
|
|
||||||
minutes = now.hour * 60 + now.minute
|
|
||||||
return minutes >= NIGHT_START_H * 60 or minutes < NIGHT_END_H * 60 + NIGHT_END_M
|
|
||||||
|
|
||||||
|
|
||||||
def seconds_until_morning():
|
|
||||||
"""距离明天早上 07:40 还有多少秒"""
|
|
||||||
now = datetime.datetime.now()
|
|
||||||
target = now.replace(hour=NIGHT_END_H, minute=NIGHT_END_M, second=0, microsecond=0)
|
|
||||||
if now.hour >= NIGHT_START_H:
|
|
||||||
target += datetime.timedelta(days=1)
|
|
||||||
return max(1, int((target - now).total_seconds()))
|
|
||||||
|
|
||||||
|
|
||||||
def get_poll_config():
|
|
||||||
if is_peak_hour():
|
|
||||||
return POLL_INTERVAL_MIN, POLL_INTERVAL_MAX, PEAK_PAGE_SIZE
|
|
||||||
return POLL_INTERVAL_MIN, POLL_INTERVAL_MAX, IDLE_PAGE_SIZE
|
|
||||||
|
|
||||||
|
|
||||||
def format_msg(order):
|
|
||||||
return f"【丰享丰食】订单收款成功,收款{fmt_money(order['amountPayable'])}"
|
|
||||||
|
|
||||||
|
|
||||||
def notify_all(text):
|
|
||||||
"""统一发送通知到企业微信 + 飞书"""
|
|
||||||
send_to_wecom(text)
|
|
||||||
send_to_feishu(text)
|
|
||||||
|
|
||||||
|
|
||||||
def send_to_wecom(text):
|
|
||||||
payload = {"msgtype": "text", "text": {"content": text}}
|
|
||||||
try:
|
|
||||||
resp = requests.post(WEBHOOK_URL, json=payload, timeout=10)
|
|
||||||
result = resp.json()
|
|
||||||
if result.get("errcode") == 0:
|
|
||||||
log("企业微信推送成功")
|
|
||||||
else:
|
|
||||||
log(f"企业微信推送失败: {result}")
|
|
||||||
except Exception as e:
|
|
||||||
log(f"企业微信推送异常: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
def send_to_feishu(text):
|
|
||||||
payload = {"msg_type": "text", "content": {"text": text}}
|
|
||||||
try:
|
|
||||||
resp = requests.post(FEISHU_WEBHOOK_URL, json=payload, timeout=10)
|
|
||||||
result = resp.json()
|
|
||||||
if result.get("code") == 0:
|
|
||||||
log("飞书推送成功")
|
|
||||||
else:
|
|
||||||
log(f"飞书推送失败: {result}")
|
|
||||||
except Exception as e:
|
|
||||||
log(f"飞书推送异常: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
def speak(text):
|
|
||||||
"""使用本地 IndexTTS2 语音播报"""
|
|
||||||
try:
|
|
||||||
_local_speak(text)
|
|
||||||
log("语音播报成功")
|
|
||||||
except Exception as e:
|
|
||||||
log(f"语音播报异常: {e}")
|
|
||||||
|
|
||||||
def load_cookies():
|
|
||||||
"""加载本地 Cookie 文件"""
|
|
||||||
cookie_path = Path(__file__).parent / COOKIES_FILE
|
|
||||||
if cookie_path.exists():
|
|
||||||
with open(cookie_path, "r", encoding="utf-8") as f:
|
|
||||||
return json.load(f)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def save_cookies(cookiejar):
|
|
||||||
"""把浏览器 Cookie 列表保存为 dict 到文件"""
|
|
||||||
cookie_dict = {c["name"]: c["value"] for c in cookiejar}
|
|
||||||
cookie_path = Path(__file__).parent / COOKIES_FILE
|
|
||||||
with open(cookie_path, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(cookie_dict, f, ensure_ascii=False, indent=2)
|
|
||||||
log("Cookie 已保存到 cookies.json")
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_orders_via_requests(cookies, page_size=5):
|
|
||||||
"""通过 requests + Cookie 拉取订单列表,返回 (订单列表 / SESSION_EXPIRED / None)"""
|
|
||||||
headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
|
||||||
"Referer": "https://fs.szfx.com/MMS",
|
|
||||||
"Origin": "https://fs.szfx.com",
|
|
||||||
}
|
|
||||||
payload = {"shopId": SHOP_ID, "page": 1, "pageSize": page_size}
|
|
||||||
try:
|
|
||||||
resp = requests.post(DATA_API, json=payload, headers=headers, cookies=cookies, timeout=30)
|
|
||||||
data = resp.json()
|
|
||||||
if data.get("errno") == 0:
|
|
||||||
return data["data"]["list"]
|
|
||||||
elif data.get("errno") in (110003, 10009):
|
|
||||||
return "SESSION_EXPIRED"
|
|
||||||
else:
|
|
||||||
log(f"API 异常: errno={data.get('errno')}, errmsg={data.get('errmsg')}")
|
|
||||||
return None
|
|
||||||
except Exception as e:
|
|
||||||
log(f"请求异常: {e}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def browser_login():
|
|
||||||
"""打开浏览器让用户手动登录,返回 Cookie dict"""
|
|
||||||
log("启动浏览器,请手动登录...")
|
|
||||||
pw = sync_playwright().start()
|
|
||||||
browser = pw.chromium.launch(headless=False, args=["--start-maximized"])
|
|
||||||
context = browser.new_context(no_viewport=True)
|
|
||||||
page = context.new_page()
|
|
||||||
page.goto(LOGIN_URL)
|
|
||||||
|
|
||||||
log("等待登录完成(10分钟超时)...")
|
|
||||||
try:
|
|
||||||
page.wait_for_url("**/MMS**", timeout=600_000)
|
|
||||||
log("登录成功!提取 Cookie...")
|
|
||||||
except Exception:
|
|
||||||
log("登录超时")
|
|
||||||
browser.close()
|
|
||||||
pw.stop()
|
|
||||||
return None
|
|
||||||
|
|
||||||
time.sleep(2)
|
|
||||||
cookiejar = context.cookies()
|
|
||||||
save_cookies(cookiejar)
|
|
||||||
|
|
||||||
browser.close()
|
|
||||||
pw.stop()
|
|
||||||
log("浏览器已关闭")
|
|
||||||
return {c["name"]: c["value"] for c in cookiejar}
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
# 1. 尝试加载已有 Cookie
|
|
||||||
cookies = load_cookies()
|
|
||||||
|
|
||||||
if cookies:
|
|
||||||
log("检测到已有 Cookie,验证有效性...")
|
|
||||||
test_result = fetch_orders_via_requests(cookies, page_size=1)
|
|
||||||
if test_result == "SESSION_EXPIRED" or test_result is None:
|
|
||||||
log("Cookie 已过期,需要重新登录")
|
|
||||||
cookies = None
|
|
||||||
else:
|
|
||||||
log("Cookie 有效,无需打开浏览器")
|
|
||||||
|
|
||||||
# 2. 没有有效 Cookie → 打开浏览器登录
|
|
||||||
if not cookies:
|
|
||||||
notify_all("【监控通知】需要登录丰享平台,请查看电脑浏览器完成登录")
|
|
||||||
cookies = browser_login()
|
|
||||||
if not cookies:
|
|
||||||
log("登录失败,退出")
|
|
||||||
return
|
|
||||||
|
|
||||||
# 3. 获取初始最新订单号
|
|
||||||
log("获取初始订单...")
|
|
||||||
_, _, page_size = get_poll_config()
|
|
||||||
last_order_id = None
|
|
||||||
orders = fetch_orders_via_requests(cookies, page_size)
|
|
||||||
if orders and orders != "SESSION_EXPIRED" and len(orders) > 0:
|
|
||||||
last_order_id = orders[0]["orderId"]
|
|
||||||
log(f"当前最新订单号: {last_order_id}")
|
|
||||||
|
|
||||||
last_keepalive = time.time()
|
|
||||||
mode = "高峰期" if is_peak_hour() else ("夜间暂停" if is_night_time() else "闲时")
|
|
||||||
log(f"开始监控(当前模式: {mode})")
|
|
||||||
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
# 夜间暂停:到点就睡,天亮再起
|
|
||||||
if is_night_time():
|
|
||||||
sleep_secs = seconds_until_morning()
|
|
||||||
until = datetime.datetime.now() + datetime.timedelta(seconds=sleep_secs)
|
|
||||||
log(f"夜间模式,暂停监控至 {until.strftime('%H:%M:%S')}(约 {sleep_secs // 60} 分钟)")
|
|
||||||
time.sleep(sleep_secs)
|
|
||||||
log("恢复监控...")
|
|
||||||
# 验证 Cookie 是否还活着
|
|
||||||
test = fetch_orders_via_requests(cookies, page_size=1)
|
|
||||||
if test == "SESSION_EXPIRED":
|
|
||||||
log("Cookie 在夜间过期,需要重新登录")
|
|
||||||
notify_all("【监控通知】Cookie 过期,请查看电脑浏览器完成登录")
|
|
||||||
cookies = browser_login()
|
|
||||||
if not cookies:
|
|
||||||
log("登录失败,退出")
|
|
||||||
return
|
|
||||||
last_keepalive = time.time()
|
|
||||||
continue
|
|
||||||
|
|
||||||
# 轮询
|
|
||||||
interval_min, interval_max, page_size = get_poll_config()
|
|
||||||
wait = random.randint(interval_min, interval_max)
|
|
||||||
mode = "高峰期" if is_peak_hour() else "闲时"
|
|
||||||
log(f"[{mode}] 等待 {wait} 秒,拉取 {page_size} 条...")
|
|
||||||
time.sleep(wait)
|
|
||||||
|
|
||||||
# 定期保活(一次 API 请求即可维持 Cookie)
|
|
||||||
if time.time() - last_keepalive > KEEPALIVE_INTERVAL:
|
|
||||||
fetch_orders_via_requests(cookies, page_size=1)
|
|
||||||
last_keepalive = time.time()
|
|
||||||
|
|
||||||
# 拉取订单
|
|
||||||
orders = fetch_orders_via_requests(cookies, page_size)
|
|
||||||
|
|
||||||
# Cookie 过期 → 浏览器重新登录
|
|
||||||
if orders == "SESSION_EXPIRED":
|
|
||||||
log("Cookie 已过期!")
|
|
||||||
notify_all("【监控异常】Cookie 已过期,请查看电脑浏览器完成登录")
|
|
||||||
cookies = browser_login()
|
|
||||||
if not cookies:
|
|
||||||
notify_all("登录超时,监控已退出。请手动重新运行。")
|
|
||||||
return
|
|
||||||
send_to_wecom("重新登录成功,监控已恢复")
|
|
||||||
last_keepalive = time.time()
|
|
||||||
orders = fetch_orders_via_requests(cookies, page_size)
|
|
||||||
if orders and orders != "SESSION_EXPIRED" and len(orders) > 0:
|
|
||||||
last_order_id = orders[0]["orderId"]
|
|
||||||
continue
|
|
||||||
|
|
||||||
if not orders or orders == "SESSION_EXPIRED":
|
|
||||||
continue
|
|
||||||
|
|
||||||
# 找出所有新订单(orderId > last_order_id)
|
|
||||||
new_orders = []
|
|
||||||
for o in orders:
|
|
||||||
if o["orderId"] == last_order_id:
|
|
||||||
break
|
|
||||||
new_orders.append(o)
|
|
||||||
|
|
||||||
if new_orders:
|
|
||||||
log(f"发现 {len(new_orders)} 条新订单!")
|
|
||||||
# 从旧到新依次推送
|
|
||||||
for o in reversed(new_orders):
|
|
||||||
msg = format_msg(o)
|
|
||||||
notify_all(msg)
|
|
||||||
speak(msg)
|
|
||||||
time.sleep(0.5)
|
|
||||||
last_order_id = new_orders[0]["orderId"]
|
|
||||||
else:
|
|
||||||
log(f"暂无新订单(最新: {last_order_id})")
|
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
log("监控已停止")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
sys.exit(main())
|
||||||
+68
-69
@@ -1,91 +1,90 @@
|
|||||||
"""获取最新一条订单并推送到企业微信群"""
|
"""手动推送最新一单(用于验证通道 / 补发)。
|
||||||
|
|
||||||
|
python push_latest_order.py # 拉最新一单,推送到已配置通道
|
||||||
|
python push_latest_order.py --dry # 只打印不推送
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
|
||||||
import datetime
|
import datetime
|
||||||
import requests
|
import json
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
DATA_API = "https://fs.szfx.com/saasmerchant/pcweb/order/quickpayorder/list"
|
from fengxiang.client import FengxiangClient, FengxiangError
|
||||||
SHOP_ID = "20434543575189"
|
from fengxiang.config import load_config
|
||||||
WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=644ab6d9-3b66-4166-88e9-5a8a89e3731d"
|
from fengxiang.logger import setup_logging
|
||||||
|
from fengxiang.notify import Dispatcher, build_channels
|
||||||
|
|
||||||
STATUS_MAP = {1: "已完成", 3: "已退款", 4: "退款中", 5: "已关闭"}
|
STATUS_MAP = {1: "已完成", 2: "待支付", 3: "已退款", 4: "退款中", 5: "已关闭"}
|
||||||
|
|
||||||
|
|
||||||
def fmt_ts(ts):
|
def fmt_ts(ts) -> str:
|
||||||
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") if ts else "-"
|
try:
|
||||||
|
return datetime.datetime.fromtimestamp(int(ts)).strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
except (TypeError, ValueError, OSError):
|
||||||
|
return "-"
|
||||||
|
|
||||||
|
|
||||||
def fmt_money(cents):
|
def fmt_money(cents) -> str:
|
||||||
return f"{cents / 100:.2f}元" if cents else "0.00元"
|
try:
|
||||||
|
return f"{int(cents) / 100:.2f}元"
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return "0.00元"
|
||||||
|
|
||||||
|
|
||||||
def load_cookies():
|
def format_order(o: dict) -> str:
|
||||||
with open("cookies.json", "r", encoding="utf-8") as f:
|
|
||||||
return json.load(f)
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_latest_order():
|
|
||||||
cookies = load_cookies()
|
|
||||||
headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
|
||||||
"Referer": "https://fs.szfx.com/MMS",
|
|
||||||
"Origin": "https://fs.szfx.com",
|
|
||||||
}
|
|
||||||
payload = {"shopId": SHOP_ID, "page": 1, "pageSize": 1}
|
|
||||||
resp = requests.post(DATA_API, json=payload, headers=headers, cookies=cookies, timeout=30)
|
|
||||||
data = resp.json()
|
|
||||||
if data.get("errno") != 0:
|
|
||||||
print(f"请求失败: {data}")
|
|
||||||
return None
|
|
||||||
return data["data"]["list"][0]
|
|
||||||
|
|
||||||
|
|
||||||
def format_order(order):
|
|
||||||
status = STATUS_MAP.get(order["status"], str(order["status"]))
|
|
||||||
return (
|
return (
|
||||||
f"【新订单通知】\n"
|
"【丰享订单详情】\n"
|
||||||
f"订单号:{order['orderId']}\n"
|
f"订单号:{o.get('orderId', '-')}\n"
|
||||||
f"店铺:{order['shopName']}\n"
|
f"店铺:{o.get('shopName', '-')}\n"
|
||||||
f"城市:{order['city']}\n"
|
f"城市:{o.get('city', '-')} / {o.get('largeAreaName', '-')}\n"
|
||||||
f"大区:{order['largeAreaName']}\n"
|
f"企业:{o.get('companyName', '-')}\n"
|
||||||
f"企业:{order['companyName']}\n"
|
f"用餐地点:{o.get('workplaceName', '-')}\n"
|
||||||
f"用餐地点:{order['workplaceName']}\n"
|
f"下单时间:{fmt_ts(o.get('createTime'))}\n"
|
||||||
f"下单时间:{fmt_ts(order['createTime'])}\n"
|
f"支付时间:{fmt_ts(o.get('payTime'))}\n"
|
||||||
f"支付时间:{fmt_ts(order['payTime'])}\n"
|
f"订单金额:{fmt_money(o.get('allPrice'))}\n"
|
||||||
f"完成时间:{fmt_ts(order['finishTime'])}\n"
|
f"实付金额:{fmt_money(o.get('amountPayable'))}\n"
|
||||||
f"订单金额:{fmt_money(order['allPrice'])}\n"
|
f"支付方式:{o.get('payTypeName', '-')}\n"
|
||||||
f"实付金额:{fmt_money(order['amountPayable'])}\n"
|
f"状态:{STATUS_MAP.get(o.get('status'), str(o.get('status', '-')))}\n"
|
||||||
f"支付方式:{order['payTypeName']}\n"
|
|
||||||
f"订单来源:{order['orderSourceName']}\n"
|
|
||||||
f"状态:{status}"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def send_to_wecom(text):
|
def main(argv: list[str]) -> int:
|
||||||
payload = {
|
cfg = load_config()
|
||||||
"msgtype": "text",
|
setup_logging(cfg.paths.logs, cfg.log.level, cfg.log.max_bytes, cfg.log.backup_count)
|
||||||
"text": {"content": text}
|
logging.getLogger("fengxiang").setLevel(logging.WARNING)
|
||||||
}
|
dry = "--dry" in argv
|
||||||
resp = requests.post(WEBHOOK_URL, json=payload, timeout=10)
|
|
||||||
result = resp.json()
|
|
||||||
if result.get("errcode") == 0:
|
|
||||||
print("推送成功!")
|
|
||||||
else:
|
|
||||||
print(f"推送失败: {result}")
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
if not cfg.paths.cookies.exists():
|
||||||
|
print(f"未找到 Cookie:{cfg.paths.cookies}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
with open(cfg.paths.cookies, "r", encoding="utf-8") as f:
|
||||||
|
cookies = json.load(f)
|
||||||
|
|
||||||
def main():
|
client = FengxiangClient(cfg)
|
||||||
order = fetch_latest_order()
|
client.set_cookies(cookies)
|
||||||
if not order:
|
try:
|
||||||
return
|
orders = client.list_orders(page_size=1)
|
||||||
|
except FengxiangError as exc:
|
||||||
|
print(f"拉取失败:{exc}", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
if not orders:
|
||||||
|
print("没有订单数据", file=sys.stderr)
|
||||||
|
return 3
|
||||||
|
|
||||||
|
order = orders[0]
|
||||||
msg = format_order(order)
|
msg = format_order(order)
|
||||||
print(msg)
|
print(msg)
|
||||||
print("\n--- 正在推送到企业微信群 ---\n")
|
if dry:
|
||||||
send_to_wecom(msg)
|
print("[dry-run] 未推送")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
dispatcher = Dispatcher(build_channels(cfg), cfg.notify.alert_cooldown_sec)
|
||||||
|
result = dispatcher.notify(msg)
|
||||||
|
print(f"推送结果:{result}")
|
||||||
|
return 0 if all(result.values()) or not result else 4
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
sys.exit(main(sys.argv[1:]))
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# 本机(Windows)额外依赖:只有 fengxiang_scraper.py 的浏览器登录需要
|
||||||
|
-r requirements.txt
|
||||||
|
playwright>=1.40.0
|
||||||
|
|
||||||
|
# 装完后还要执行: playwright install chromium
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
requests>=2.31.0
|
||||||
|
PyYAML>=6.0.1
|
||||||
|
tzdata>=2024.1
|
||||||
@@ -1,40 +1,38 @@
|
|||||||
@echo off
|
@echo off
|
||||||
chcp 65001 >nul
|
chcp 65001 >nul
|
||||||
title 丰享订单监控
|
title 丰享订单监控 v5
|
||||||
|
|
||||||
echo ============================================
|
|
||||||
echo 丰享订单监控系统 v4
|
|
||||||
echo 推送: 企业微信 + 本地TTS语音播报
|
|
||||||
echo ============================================
|
|
||||||
echo.
|
|
||||||
|
|
||||||
cd /d "%~dp0"
|
cd /d "%~dp0"
|
||||||
|
|
||||||
:: Python路径(IndexTTS虚拟环境)
|
echo ============================================
|
||||||
set PYTHON=E:\2025Code\python\IndexTT\index-tts\.venv\Scripts\python.exe
|
echo 丰享订单监控 v5
|
||||||
|
echo 推送: 企业微信(TTS 可选,见 config.yaml)
|
||||||
:: 检查Python是否存在
|
echo ============================================
|
||||||
if not exist "%PYTHON%" (
|
|
||||||
echo [错误] 未找到Python: %PYTHON%
|
|
||||||
echo 请确认IndexTTS已正确安装
|
|
||||||
pause
|
|
||||||
exit /b 1
|
|
||||||
)
|
|
||||||
|
|
||||||
:: 检查cookie文件
|
|
||||||
if not exist "cookies.json" (
|
|
||||||
echo [提示] 未检测到登录Cookie,首次运行将自动打开浏览器
|
|
||||||
echo 请在浏览器中手动完成登录(含验证码)
|
|
||||||
echo.
|
|
||||||
)
|
|
||||||
|
|
||||||
echo [启动] 正在启动订单监控...
|
|
||||||
echo.
|
echo.
|
||||||
|
|
||||||
|
:: 依次尝试:项目内虚拟环境 -> FX_PYTHON -> IndexTTS2 环境 -> 系统 python
|
||||||
|
set "PYTHON="
|
||||||
|
if exist ".venv\Scripts\python.exe" set "PYTHON=.venv\Scripts\python.exe"
|
||||||
|
if not defined PYTHON if defined FX_PYTHON set "PYTHON=%FX_PYTHON%"
|
||||||
|
if not defined PYTHON if exist "E:\2025Code\python\IndexTT\index-tts\.venv\Scripts\python.exe" set "PYTHON=E:\2025Code\python\IndexTT\index-tts\.venv\Scripts\python.exe"
|
||||||
|
if not defined PYTHON set "PYTHON=python"
|
||||||
|
|
||||||
|
echo [环境] Python: %PYTHON%
|
||||||
|
"%PYTHON%" -c "import requests, yaml" >nul 2>&1
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo [准备] 缺少依赖,正在安装...
|
||||||
|
"%PYTHON%" -m pip install -r requirements.txt
|
||||||
|
)
|
||||||
|
|
||||||
|
if not exist "config.yaml" (
|
||||||
|
echo [提示] 未找到 config.yaml,将使用默认配置
|
||||||
|
echo 建议复制 config.example.yaml 为 config.yaml 后填写企业微信 webhook
|
||||||
|
echo.
|
||||||
|
)
|
||||||
|
|
||||||
|
echo [启动] 启动监控(Ctrl+C 退出)...
|
||||||
|
echo.
|
||||||
"%PYTHON%" order_monitor.py
|
"%PYTHON%" order_monitor.py
|
||||||
|
|
||||||
if %errorlevel% neq 0 (
|
echo.
|
||||||
echo.
|
echo [结束] 进程已退出,错误码: %errorlevel%
|
||||||
echo [异常] 监控程序异常退出,错误码: %errorlevel%
|
pause
|
||||||
pause
|
|
||||||
)
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
@echo off
|
|
||||||
title Fengxiang Order Monitor
|
|
||||||
cd /d d:\coding\fengxiang
|
|
||||||
echo =========================================
|
|
||||||
echo Fengxiang Order Monitor v3
|
|
||||||
echo %date% %time%
|
|
||||||
echo =========================================
|
|
||||||
echo.
|
|
||||||
python order_monitor.py
|
|
||||||
echo.
|
|
||||||
echo Monitor stopped. Press any key to close...
|
|
||||||
pause >nul
|
|
||||||
+22
-20
@@ -1,31 +1,33 @@
|
|||||||
# 设置丰享订单监控开机自启
|
# 设置丰享订单监控开机自启(Windows 任务计划)
|
||||||
# 右键此文件 → "使用 PowerShell 运行",或在管理员 PowerShell 中执行
|
# 用法:右键 -> 使用 PowerShell 运行;或在管理员 PowerShell 中执行
|
||||||
|
# 路径全部基于本脚本所在目录,不再写死盘符
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
$taskName = "丰享订单监控"
|
$taskName = "丰享订单监控"
|
||||||
$scriptPath = "d:\coding\fengxiang\run_monitor.bat"
|
$root = $PSScriptRoot
|
||||||
$taskExists = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
|
$bat = Join-Path $root "run.bat"
|
||||||
|
|
||||||
if ($taskExists) {
|
if (-not (Test-Path $bat)) {
|
||||||
|
Write-Host "[错误] 未找到 $bat" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
$existing = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
|
||||||
|
if ($existing) {
|
||||||
Write-Host "检测到已有任务,正在更新..."
|
Write-Host "检测到已有任务,正在更新..."
|
||||||
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
|
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
|
||||||
}
|
}
|
||||||
|
|
||||||
# 创建任务:用户登录时自动运行
|
$action = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c `"$bat`"" -WorkingDirectory $root
|
||||||
$action = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c `"$scriptPath`""
|
|
||||||
$trigger = New-ScheduledTaskTrigger -AtLogOn
|
$trigger = New-ScheduledTaskTrigger -AtLogOn
|
||||||
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel Highest
|
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel Highest
|
||||||
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew
|
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
|
||||||
|
-StartWhenAvailable -MultipleInstances IgnoreNew -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)
|
||||||
|
|
||||||
Register-ScheduledTask -TaskName $taskName `
|
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger `
|
||||||
-Action $action `
|
-Principal $principal -Settings $settings `
|
||||||
-Trigger $trigger `
|
-Description "丰享订单监控 - 登录后自动启动,监控新订单并推送企业微信" | Out-Null
|
||||||
-Principal $principal `
|
|
||||||
-Settings $settings `
|
|
||||||
-Description "丰享订单监控 - 开机自动启动,监控新订单并推送到企业微信和小爱音箱"
|
|
||||||
|
|
||||||
Write-Host "✓ 开机自启设置成功!"
|
Write-Host "✓ 开机自启已设置:$taskName"
|
||||||
Write-Host " 任务名称: $taskName"
|
Write-Host " 启动脚本: $bat"
|
||||||
Write-Host " 下次登录 Windows 时将自动运行"
|
Write-Host " 立即测试: Start-ScheduledTask -TaskName '$taskName'"
|
||||||
Write-Host ""
|
|
||||||
Write-Host "立即测试运行?运行以下命令:"
|
|
||||||
Write-Host " Start-ScheduledTask -TaskName '$taskName'"
|
|
||||||
-128
@@ -1,128 +0,0 @@
|
|||||||
"""
|
|
||||||
测试脚本:验证企业微信推送 + 小爱音箱播报
|
|
||||||
- 拉取最新订单,推送到企业微信和小爱音箱
|
|
||||||
- 显示 API 返回结果,方便排查问题
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
import requests
|
|
||||||
import asyncio
|
|
||||||
from pathlib import Path
|
|
||||||
from aiohttp import ClientSession
|
|
||||||
from miservice import MiAccount, MiNAService
|
|
||||||
|
|
||||||
WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=644ab6d9-3b66-4166-88e9-5a8a89e3731d"
|
|
||||||
DATA_API = "https://fs.szfx.com/saasmerchant/pcweb/order/quickpayorder/list"
|
|
||||||
SHOP_ID = "20434543575189"
|
|
||||||
|
|
||||||
XIAOMI_USER_ID = "1136458602"
|
|
||||||
XIAOMI_TOKEN_PATH = str(Path.home() / ".mi.token")
|
|
||||||
XIAOMI_SPEAKER_DID = "3ba2c1e8-d8cb-45c5-b88a-15624e7a02f3"
|
|
||||||
|
|
||||||
|
|
||||||
def fmt_money(cents):
|
|
||||||
return f"{cents / 100:.2f}元" if cents else "0.00元"
|
|
||||||
|
|
||||||
|
|
||||||
def fmt_ts(ts):
|
|
||||||
import datetime
|
|
||||||
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") if ts else "-"
|
|
||||||
|
|
||||||
|
|
||||||
def load_cookies():
|
|
||||||
with open("cookies.json", "r", encoding="utf-8") as f:
|
|
||||||
return json.load(f)
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_latest_order():
|
|
||||||
"""使用 cookies.json 拉取最新订单"""
|
|
||||||
cookies = load_cookies()
|
|
||||||
headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
|
||||||
"Referer": "https://fs.szfx.com/MMS",
|
|
||||||
"Origin": "https://fs.szfx.com",
|
|
||||||
}
|
|
||||||
payload = {"shopId": SHOP_ID, "page": 1, "pageSize": 1}
|
|
||||||
resp = requests.post(DATA_API, json=payload, headers=headers, cookies=cookies, timeout=30)
|
|
||||||
data = resp.json()
|
|
||||||
if data.get("errno") != 0:
|
|
||||||
print(f"[FAIL] API error: errno={data.get('errno')}, errmsg={data.get('errmsg')}")
|
|
||||||
return None
|
|
||||||
return data["data"]["list"][0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_wecom(msg):
|
|
||||||
"""发送到企业微信"""
|
|
||||||
print("\n--- Test: WeChat Work ---")
|
|
||||||
payload = {"msgtype": "text", "text": {"content": msg}}
|
|
||||||
try:
|
|
||||||
resp = requests.post(WEBHOOK_URL, json=payload, timeout=10)
|
|
||||||
result = resp.json()
|
|
||||||
print(f" Response: {json.dumps(result, ensure_ascii=False)}")
|
|
||||||
if result.get("errcode") == 0:
|
|
||||||
print(" [OK] WeChat push success")
|
|
||||||
else:
|
|
||||||
print(" [FAIL] WeChat push failed")
|
|
||||||
except Exception as e:
|
|
||||||
print(f" [FAIL] Exception: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
async def _tts(text):
|
|
||||||
async with ClientSession() as session:
|
|
||||||
account = MiAccount(session, XIAOMI_USER_ID, None, XIAOMI_TOKEN_PATH)
|
|
||||||
mina = MiNAService(account)
|
|
||||||
return await mina.text_to_speech(XIAOMI_SPEAKER_DID, text)
|
|
||||||
|
|
||||||
|
|
||||||
def test_speaker(msg):
|
|
||||||
"""发送到小爱音箱"""
|
|
||||||
print("\n--- Test: Xiaomi Speaker ---")
|
|
||||||
print(f" Text: {msg}")
|
|
||||||
try:
|
|
||||||
result = asyncio.run(_tts(msg))
|
|
||||||
print(f" Response: {json.dumps(result, ensure_ascii=False)}")
|
|
||||||
if result and result.get("code") == 0:
|
|
||||||
print(" [OK] Speaker TTS success")
|
|
||||||
else:
|
|
||||||
print(" [FAIL] Speaker TTS failed - token may be expired, run setup_xiaomi.py")
|
|
||||||
except Exception as e:
|
|
||||||
print(f" [FAIL] Exception: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
print("=" * 50)
|
|
||||||
print(" Fengxiang Order Monitor - Test Script")
|
|
||||||
print("=" * 50)
|
|
||||||
|
|
||||||
# 1. Fetch latest order
|
|
||||||
print("\n1. Fetch latest order...")
|
|
||||||
order = fetch_latest_order()
|
|
||||||
if not order:
|
|
||||||
print("[FAIL] Cannot fetch order, check cookies.json")
|
|
||||||
return
|
|
||||||
|
|
||||||
print(f" orderId: {order['orderId']}")
|
|
||||||
print(f" shopName: {order['shopName']}")
|
|
||||||
print(f" allPrice: {fmt_money(order['allPrice'])}")
|
|
||||||
print(f" amountPayable: {fmt_money(order['amountPayable'])}")
|
|
||||||
print(f" payTime: {fmt_ts(order['payTime'])}")
|
|
||||||
|
|
||||||
# 2. Format message
|
|
||||||
msg = f"【丰享丰食】订单收款成功,收款{fmt_money(order['amountPayable'])}"
|
|
||||||
print(f"\n2. Message to send:\n {msg}")
|
|
||||||
|
|
||||||
# 3. Test WeChat and Speaker
|
|
||||||
test_wecom(msg)
|
|
||||||
test_speaker(msg)
|
|
||||||
|
|
||||||
print("\n" + "=" * 50)
|
|
||||||
print(" Test complete. Check:")
|
|
||||||
print(" - WeChat: open the enterprise WeChat group")
|
|
||||||
print(" - Speaker: the L15A speaker in the shop")
|
|
||||||
print("=" * 50)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
"""核心逻辑单元测试(不联网,全部用假客户端/假通道)。
|
||||||
|
|
||||||
|
运行:python -m unittest discover -s tests -v
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from dataclasses import replace
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from fengxiang.config import load_config # noqa: E402
|
||||||
|
from fengxiang.monitor import Monitor, fmt_money # noqa: E402
|
||||||
|
from fengxiang.store import State # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- 假对象
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, orders=None):
|
||||||
|
self.orders = orders or []
|
||||||
|
self.cookies = {}
|
||||||
|
self.cookie_ok = True
|
||||||
|
|
||||||
|
def set_cookies(self, cookies):
|
||||||
|
self.cookies = dict(cookies)
|
||||||
|
|
||||||
|
def check_cookie(self, cookies):
|
||||||
|
return self.cookie_ok and bool(cookies)
|
||||||
|
|
||||||
|
def list_orders(self, page_size=5, page=1):
|
||||||
|
return self.orders[:page_size]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeDispatcher:
|
||||||
|
def __init__(self):
|
||||||
|
self.messages = []
|
||||||
|
self.alerts = []
|
||||||
|
self.channels = []
|
||||||
|
|
||||||
|
def notify(self, text):
|
||||||
|
self.messages.append(text)
|
||||||
|
return {"fake": True}
|
||||||
|
|
||||||
|
def alert(self, key, text):
|
||||||
|
self.alerts.append((key, text))
|
||||||
|
return True, "sent"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSpeaker:
|
||||||
|
def __init__(self):
|
||||||
|
self.said = []
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def say(self, text):
|
||||||
|
self.said.append(text)
|
||||||
|
|
||||||
|
|
||||||
|
def make_order(oid: str, cents: int = 2400):
|
||||||
|
return {"orderId": oid, "amountPayable": cents, "shopName": "益选便利店"}
|
||||||
|
|
||||||
|
|
||||||
|
class BaseCase(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.tmp.cleanup)
|
||||||
|
self._env_backup = dict(os.environ)
|
||||||
|
os.environ["FX_DATA_DIR"] = self.tmp.name
|
||||||
|
os.environ["FX_CONFIG"] = str(Path(self.tmp.name) / "none.yaml")
|
||||||
|
os.environ["FX_WECOM_WEBHOOK"] = "https://example.invalid/hook"
|
||||||
|
self.cfg = load_config()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
os.environ.clear()
|
||||||
|
os.environ.update(self._env_backup)
|
||||||
|
|
||||||
|
def build(self, orders=None, **kwargs):
|
||||||
|
client = FakeClient(orders)
|
||||||
|
dispatcher = FakeDispatcher()
|
||||||
|
speaker = FakeSpeaker()
|
||||||
|
mon = Monitor(self.cfg, client=client, dispatcher=dispatcher, speaker=speaker, **kwargs)
|
||||||
|
return mon, client, dispatcher, speaker
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- 配置
|
||||||
|
class TestConfig(BaseCase):
|
||||||
|
def test_defaults(self):
|
||||||
|
self.assertEqual(self.cfg.shop_id, "20434543575189")
|
||||||
|
self.assertIn("wecom", self.cfg.notify.channels)
|
||||||
|
|
||||||
|
def test_feishu_disabled_by_default(self):
|
||||||
|
self.assertFalse(self.cfg.notify.feishu_enabled)
|
||||||
|
self.assertNotIn("feishu", self.cfg.notify.channels)
|
||||||
|
|
||||||
|
def test_env_wecom_only_channel(self):
|
||||||
|
self.assertEqual(len(self.cfg.notify.channels), 1)
|
||||||
|
|
||||||
|
def test_paths_point_to_data_dir(self):
|
||||||
|
self.assertTrue(str(self.cfg.paths.cookies).startswith(self.tmp.name))
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- 状态
|
||||||
|
class TestState(BaseCase):
|
||||||
|
def test_roundtrip(self):
|
||||||
|
s = State(last_order_id="100", pushed_ids=["100"])
|
||||||
|
s.mark_pushed(["101", "102"])
|
||||||
|
s.save(self.cfg.paths.state)
|
||||||
|
|
||||||
|
loaded = State.load(self.cfg.paths.state)
|
||||||
|
self.assertEqual(loaded.last_order_id, "100")
|
||||||
|
self.assertEqual(loaded.pushed_ids, ["100", "101", "102"])
|
||||||
|
self.assertEqual(loaded.total_pushed, 2) # 初始 pushed_ids 不计入累计
|
||||||
|
|
||||||
|
def test_pushed_ids_bounded(self):
|
||||||
|
s = State()
|
||||||
|
s.mark_pushed([str(i) for i in range(700)])
|
||||||
|
self.assertEqual(len(s.pushed_ids), 500)
|
||||||
|
self.assertTrue(s.has_pushed("699"))
|
||||||
|
self.assertFalse(s.has_pushed("0"))
|
||||||
|
|
||||||
|
def test_corrupt_file_is_tolerated(self):
|
||||||
|
Path(self.cfg.paths.state).write_text("{not json", encoding="utf-8")
|
||||||
|
s = State.load(self.cfg.paths.state)
|
||||||
|
self.assertIsNone(s.last_order_id)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- 主循环业务
|
||||||
|
class TestProcess(BaseCase):
|
||||||
|
def test_bootstrap_does_not_push_history(self):
|
||||||
|
mon, client, dispatcher, _ = self.build([make_order("A3"), make_order("A2")])
|
||||||
|
mon._bootstrap()
|
||||||
|
self.assertEqual(dispatcher.messages, [])
|
||||||
|
self.assertEqual(mon.state.last_order_id, "A3")
|
||||||
|
self.assertTrue(mon.state.has_pushed("A3"))
|
||||||
|
|
||||||
|
def test_new_orders_pushed_old_to_new(self):
|
||||||
|
mon, _, dispatcher, speaker = self.build()
|
||||||
|
mon.state.last_order_id = "A3"
|
||||||
|
mon._process([make_order("A5", 3000), make_order("A4", 2000), make_order("A3", 1000)], 10)
|
||||||
|
self.assertEqual(len(dispatcher.messages), 2)
|
||||||
|
self.assertIn("20.00元", dispatcher.messages[0])
|
||||||
|
self.assertIn("30.00元", dispatcher.messages[1])
|
||||||
|
self.assertEqual(mon.state.last_order_id, "A5")
|
||||||
|
self.assertEqual(len(speaker.said), 2)
|
||||||
|
|
||||||
|
def test_dedupe_after_restart(self):
|
||||||
|
mon, _, dispatcher, _ = self.build()
|
||||||
|
mon.state.last_order_id = "A3"
|
||||||
|
mon.state.mark_pushed(["A4"]) # A4 已在重启前推过
|
||||||
|
mon._process([make_order("A5"), make_order("A4"), make_order("A3")], 50)
|
||||||
|
self.assertEqual(len(dispatcher.messages), 1)
|
||||||
|
self.assertIn("24.00", dispatcher.messages[0])
|
||||||
|
|
||||||
|
def test_no_new_orders_silent(self):
|
||||||
|
mon, _, dispatcher, _ = self.build()
|
||||||
|
mon.state.last_order_id = "A9"
|
||||||
|
mon._process([make_order("A9")], 10)
|
||||||
|
self.assertEqual(dispatcher.messages, [])
|
||||||
|
|
||||||
|
def test_bulk_summary_instead_of_spam(self):
|
||||||
|
mon, _, dispatcher, _ = self.build()
|
||||||
|
mon.state.last_order_id = "A0"
|
||||||
|
orders = [make_order(f"A{i}", 1000) for i in range(8, 0, -1)]
|
||||||
|
mon._process(orders, 20)
|
||||||
|
self.assertEqual(len(dispatcher.messages), 1)
|
||||||
|
self.assertIn("8 笔订单", dispatcher.messages[0])
|
||||||
|
self.assertIn("80.00元", dispatcher.messages[0])
|
||||||
|
|
||||||
|
def test_missing_order_id_ignored(self):
|
||||||
|
mon, _, dispatcher, _ = self.build()
|
||||||
|
mon.state.last_order_id = "A1"
|
||||||
|
mon._process([{"amountPayable": 100}, make_order("A1")], 10)
|
||||||
|
self.assertEqual(dispatcher.messages, [])
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- 时间窗口
|
||||||
|
class TestWindows(BaseCase):
|
||||||
|
def _at(self, hh, mm=0):
|
||||||
|
mon, *_ = self.build()
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
fixed = datetime.datetime(2026, 11, 16, hh, mm)
|
||||||
|
mon._now_impl = lambda: fixed
|
||||||
|
return mon
|
||||||
|
|
||||||
|
def test_night_true_after_21(self):
|
||||||
|
mon = self._at(22, 30)
|
||||||
|
self.assertTrue(mon.is_night())
|
||||||
|
|
||||||
|
def test_night_true_before_0740(self):
|
||||||
|
mon = self._at(3, 0)
|
||||||
|
self.assertTrue(mon.is_night())
|
||||||
|
|
||||||
|
def test_daytime_not_night(self):
|
||||||
|
mon = self._at(12, 0)
|
||||||
|
self.assertFalse(mon.is_night())
|
||||||
|
self.assertTrue(mon.is_peak())
|
||||||
|
|
||||||
|
def test_offpeak(self):
|
||||||
|
mon = self._at(15, 0)
|
||||||
|
self.assertFalse(mon.is_peak())
|
||||||
|
self.assertFalse(mon.is_night())
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- 金额
|
||||||
|
class TestMoney(unittest.TestCase):
|
||||||
|
def test_formats(self):
|
||||||
|
self.assertEqual(fmt_money(2400), "24.00元")
|
||||||
|
self.assertEqual(fmt_money(0), "0.00元")
|
||||||
|
self.assertEqual(fmt_money(None), "0.00元")
|
||||||
|
self.assertEqual(fmt_money("x"), "0.00元")
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- 管理接口
|
||||||
|
class TestAdminAPI(BaseCase):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.cfg = replace(self.cfg, admin=replace(self.cfg.admin, port=0, token="t0k"))
|
||||||
|
|
||||||
|
def _start(self):
|
||||||
|
from fengxiang.admin import AdminServer
|
||||||
|
mon, client, dispatcher, speaker = self.build()
|
||||||
|
mon.update_cookies = lambda cookies: bool(cookies) # 避免真实校验
|
||||||
|
mon.status = lambda: {"cookie_valid": True, "mode": "idle", "last_poll_age_sec": 1}
|
||||||
|
srv = AdminServer(self.cfg, mon)
|
||||||
|
port = srv.httpd.server_address[1]
|
||||||
|
srv.start()
|
||||||
|
self.addCleanup(srv.stop)
|
||||||
|
return mon, port
|
||||||
|
|
||||||
|
def _post(self, port, path, body, token=None):
|
||||||
|
req = urllib.request.Request(
|
||||||
|
f"http://127.0.0.1:{port}{path}",
|
||||||
|
data=json.dumps(body).encode(),
|
||||||
|
headers={"Content-Type": "application/json",
|
||||||
|
**({"X-Auth-Token": token} if token else {})},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(req, timeout=5) as resp:
|
||||||
|
return resp.status, json.load(resp)
|
||||||
|
|
||||||
|
def _get(self, port, path):
|
||||||
|
with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=5) as resp:
|
||||||
|
return resp.status, json.load(resp)
|
||||||
|
|
||||||
|
def test_healthz_no_auth(self):
|
||||||
|
_, port = self._start()
|
||||||
|
status, data = self._get(port, "/healthz")
|
||||||
|
self.assertEqual(status, 200)
|
||||||
|
self.assertTrue(data["cookie_valid"])
|
||||||
|
|
||||||
|
def test_post_cookies_requires_token(self):
|
||||||
|
_, port = self._start()
|
||||||
|
with self.assertRaises(urllib.error.HTTPError) as ctx:
|
||||||
|
self._post(port, "/api/cookies", {"cookies": {"USS": "x"}})
|
||||||
|
self.assertEqual(ctx.exception.code, 401)
|
||||||
|
|
||||||
|
def test_post_cookies_with_token(self):
|
||||||
|
_, port = self._start()
|
||||||
|
status, data = self._post(port, "/api/cookies", {"cookies": {"USS": "x"}}, token="t0k")
|
||||||
|
self.assertEqual(status, 200)
|
||||||
|
self.assertTrue(data["ok"])
|
||||||
|
|
||||||
|
def test_post_bad_body(self):
|
||||||
|
_, port = self._start()
|
||||||
|
req = urllib.request.Request(
|
||||||
|
f"http://127.0.0.1:{port}/api/cookies",
|
||||||
|
data=b"[]",
|
||||||
|
headers={"Content-Type": "application/json", "X-Auth-Token": "t0k"},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
with self.assertRaises(urllib.error.HTTPError) as ctx:
|
||||||
|
urllib.request.urlopen(req, timeout=5)
|
||||||
|
self.assertEqual(ctx.exception.code, 400)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main(verbosity=2)
|
||||||
Reference in new issue
Block a user