chore: 行尾统一为 LF
- 新增 .gitattributes:* text=auto eol=lf,二进制类型显式标 binary - 24 个 CRLF 文件归一为 LF(内容零变化,忽略行尾后 diff 只有本文件与 .gitignore) - .gitignore 补 temp/、.pytest_cache/、token_config.txt.old-bak、scripts/.pack_baseline.json 等
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
# 统一行尾:仓库内容一律 LF,检出也保持 LF。
|
||||
# 编辑器(Windows)往文件里写 CRLF 时,git 会在提交时归一化,
|
||||
# 不会再出现"改一行、diff 一万行"的情况。
|
||||
* text=auto eol=lf
|
||||
|
||||
# 二进制:不要做任何文本转换
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.ico binary
|
||||
*.exe binary
|
||||
*.zip binary
|
||||
*.db binary
|
||||
*.db-wal binary
|
||||
*.db-shm binary
|
||||
*.pem binary
|
||||
*.crt binary
|
||||
*.key binary
|
||||
@@ -12,3 +12,11 @@ server_config.json
|
||||
.reasonix/
|
||||
*.zip
|
||||
*.log
|
||||
temp/
|
||||
.pytest_cache/
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
downloads/*.exe
|
||||
token_config.txt.old-bak
|
||||
scripts/.pack_baseline.json
|
||||
update.zip
|
||||
@@ -1,153 +1,153 @@
|
||||
# 小白超人电动车地图
|
||||
|
||||
基于 Flask 的共享电动车位置追踪与租赁管理系统。通过微信小程序接口采集车辆位置,提供地图展示、历史轨迹、数据分析与租赁到期提醒功能。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- **车辆位置采集**:自适应频率调用微信小程序接口抓取车辆数据(白天 5-10 分钟/次,夜间 30-60 分钟/次)
|
||||
- **地图展示**:按车辆状态(可用 / 使用中 / 已锁定 / 已预约 / 低电量)分色标记
|
||||
- **地图共享快照**:同一车辆类型的全局地图请求共用 60 秒快照,SQLite 租约合并跨线程/进程的并发刷新;失败也在同一窗口退避,不把过期成功结果当新数据返回。页面按快照到期时间自动刷新,返回前台时立即补刷,更新时间来自当前地图快照。
|
||||
- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹
|
||||
- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图
|
||||
- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知)
|
||||
- **自动清理**:3 天前历史数据自动归档,定期 VACUUM 释放空间
|
||||
|
||||
## 技术栈
|
||||
|
||||
- **后端**:Flask + SQLite(原生 `sqlite3`)
|
||||
- **架构**:Blueprint 分模块(auth / map_api / rental / admin)
|
||||
- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`)
|
||||
- **采集调度**:threading 后台线程 + 自适应间隔
|
||||
- **通知**:SMTP 邮件 + 内部计时器
|
||||
- **前端**:Jinja2 模板 + Leaflet 地图 + ECharts 图表
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
xbniu_map/
|
||||
├── app.py # 应用入口 + 数据采集调度 + 分析 API
|
||||
├── db.py # SQLite 连接与表初始化
|
||||
├── wechat.py # 微信小程序接口封装
|
||||
├── email_utils.py # 邮件发送
|
||||
├── timer.py # 订单到期计时器管理
|
||||
├── generate_icons.py # 地图标记图标生成
|
||||
├── routes/
|
||||
│ ├── auth.py # 用户注册 / 登录 / 微信授权
|
||||
│ ├── map_api.py # 地图数据接口
|
||||
│ ├── rental.py # 租赁 / 提醒
|
||||
│ └── admin.py # 后台管理
|
||||
├── templates/
|
||||
│ ├── map.html # 主地图页
|
||||
│ ├── analysis.html # 数据分析页
|
||||
│ ├── admin.html # 后台管理页
|
||||
│ └── ring_progress.html # 状态环形图组件
|
||||
├── static/ # 地图标记图标(分色)
|
||||
└── requirements.txt
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
启动前需准备以下敏感文件(不上传到 Git,已在 `.gitignore` 排除):
|
||||
|
||||
| 文件 | 用途 | 示例 |
|
||||
|------|------|------|
|
||||
| `token_config.txt` | 全局默认微信 token | `token_id=1234567` |
|
||||
| `key.pem` / `private.key` | HTTPS 私钥 | `/BEGIN PRIVATE KEY/` |
|
||||
| `cert.pem` / `certificate.crt` / `ca_bundle.crt` | HTTPS 证书链 | `/BEGIN CERTIFICATE/` |
|
||||
|
||||
用户级授权凭据(`token_id` + `wx_signature`)存储在 `users.db` 的 `users` 表中,通过登录后从微信小程序抓包获取。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 1. 安装依赖
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 2. 准备敏感文件(见上方配置说明)
|
||||
|
||||
# 3. 启动服务
|
||||
python app.py
|
||||
# 默认监听 127.0.0.1:98,对外由 nginx 反代提供 HTTPS
|
||||
```
|
||||
|
||||
## 打包分发
|
||||
|
||||
```bash
|
||||
# 重新生成 1.zip(仅源码、模板、必要静态资源、测试和脚本)
|
||||
pwsh -File scripts/pack_zip.ps1
|
||||
```
|
||||
|
||||
打包排除证书/密钥/token/数据库/备份/缓存,以及安装包、截图和运行日志;打包脚本会自动
|
||||
校验关键文件是否在位(campus/alerts/subscribe/export 等新模块缺失会直接报错)。
|
||||
|
||||
## 抓包工具下载
|
||||
|
||||
「填写凭证」等弹窗里的下载按钮指向 `/download/capture-tool.exe`,对应磁盘文件
|
||||
`downloads/xbniu-capture-tool.exe`(约 160MB,不在版本库及源码包 1.zip 中,部署时另行提供)。
|
||||
|
||||
- 公开访问,无需登录:用户注册前就要先拿到工具,否则形成死循环。
|
||||
- 路由带 `conditional=True` 并显式返回 `Accept-Ranges: bytes`,支持断点续传。
|
||||
- 文件缺失时返回 `404 {"rtn_code": 404, "message": "安装包暂未上传"}`。
|
||||
- 微信/QQ/支付宝/钉钉/微博/抖音等内置浏览器会拦截 exe 下载,前端改为弹出
|
||||
「复制链接到外部浏览器」提示。
|
||||
|
||||
**nginx 注意**:大文件经 `proxy_pass` 下载时,若带宽较低可能被默认的
|
||||
`proxy_read_timeout 60s` 中断,建议在对应 `location` 上放宽:
|
||||
|
||||
```nginx
|
||||
location /download/ {
|
||||
proxy_pass http://127.0.0.1:98;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_max_temp_file_size 0; # 不缓冲大文件,直接透传
|
||||
}
|
||||
```
|
||||
|
||||
## 数据库表结构
|
||||
|
||||
| 表 | 用途 |
|
||||
|----|------|
|
||||
| `users` | 用户账号、微信授权凭据 |
|
||||
| `sessions` | 登录会话 token |
|
||||
| `reminders` | 租赁提醒订阅 |
|
||||
| `rentals` | 租车记录 + 多级通知状态(notified_10/5/3/2/1/0)|
|
||||
| `bike_history` | 车辆位置历史(含状态、电量)|
|
||||
| `snapshots` | 整体快照(总数、状态分布)|
|
||||
|
||||
## 核心机制
|
||||
|
||||
### 自适应采集
|
||||
|
||||
```python
|
||||
def get_adaptive_interval():
|
||||
# 夜间(23:00-07:00):1800-3600s(30-60 分钟)
|
||||
# 白天:300-600s(5-10 分钟)
|
||||
```
|
||||
|
||||
后台线程循环执行 `snapshot_bike_positions()`,调用 `/project/map?type=3` 拉取全部车辆,写入 `bike_history`。
|
||||
|
||||
### 数据清理
|
||||
|
||||
每 23 小时执行一次:删除 3 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
||||
|
||||
### 订单到期提醒
|
||||
|
||||
`timer.py` 在启动时恢复未到期的计时器(`restore_active_timers`),并在到期前 10/5/3/2/1/0 分钟触发邮件通知。每条 `rentals` 记录的 `notified_*` 字段标记对应级别是否已发送,避免重复通知。
|
||||
|
||||
## 主要接口
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| POST | `/api/collect_now` | 手动触发一次采集 |
|
||||
| GET | `/api/bike_history?code=xxx` | 查询指定车辆历史轨迹 |
|
||||
| GET | `/api/analysis/overview` | 状态分布 + 时段分布 + Top10 |
|
||||
| GET | `/api/analysis/heatmap?code=xxx` | 热力图数据 |
|
||||
|
||||
具体路由详见 `routes/*.py`。
|
||||
|
||||
## 注意事项
|
||||
|
||||
- `token_id` 与 `wx_signature` 来自微信小程序抓包,**修改后需重启服务或通过后台保存**
|
||||
- `users.db` 包含用户授权信息与历史轨迹,**不可公开**
|
||||
- HTTPS 证书文件(`*.pem` `*.crt` `*.key`)若损坏会导致小程序接口无法访问
|
||||
- 服务监听端口默认 98(非特权端口)
|
||||
|
||||
# 小白超人电动车地图
|
||||
|
||||
基于 Flask 的共享电动车位置追踪与租赁管理系统。通过微信小程序接口采集车辆位置,提供地图展示、历史轨迹、数据分析与租赁到期提醒功能。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- **车辆位置采集**:自适应频率调用微信小程序接口抓取车辆数据(白天 5-10 分钟/次,夜间 30-60 分钟/次)
|
||||
- **地图展示**:按车辆状态(可用 / 使用中 / 已锁定 / 已预约 / 低电量)分色标记
|
||||
- **地图共享快照**:同一车辆类型的全局地图请求共用 60 秒快照,SQLite 租约合并跨线程/进程的并发刷新;失败也在同一窗口退避,不把过期成功结果当新数据返回。页面按快照到期时间自动刷新,返回前台时立即补刷,更新时间来自当前地图快照。
|
||||
- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹
|
||||
- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图
|
||||
- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知)
|
||||
- **自动清理**:3 天前历史数据自动归档,定期 VACUUM 释放空间
|
||||
|
||||
## 技术栈
|
||||
|
||||
- **后端**:Flask + SQLite(原生 `sqlite3`)
|
||||
- **架构**:Blueprint 分模块(auth / map_api / rental / admin)
|
||||
- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`)
|
||||
- **采集调度**:threading 后台线程 + 自适应间隔
|
||||
- **通知**:SMTP 邮件 + 内部计时器
|
||||
- **前端**:Jinja2 模板 + Leaflet 地图 + ECharts 图表
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
xbniu_map/
|
||||
├── app.py # 应用入口 + 数据采集调度 + 分析 API
|
||||
├── db.py # SQLite 连接与表初始化
|
||||
├── wechat.py # 微信小程序接口封装
|
||||
├── email_utils.py # 邮件发送
|
||||
├── timer.py # 订单到期计时器管理
|
||||
├── generate_icons.py # 地图标记图标生成
|
||||
├── routes/
|
||||
│ ├── auth.py # 用户注册 / 登录 / 微信授权
|
||||
│ ├── map_api.py # 地图数据接口
|
||||
│ ├── rental.py # 租赁 / 提醒
|
||||
│ └── admin.py # 后台管理
|
||||
├── templates/
|
||||
│ ├── map.html # 主地图页
|
||||
│ ├── analysis.html # 数据分析页
|
||||
│ ├── admin.html # 后台管理页
|
||||
│ └── ring_progress.html # 状态环形图组件
|
||||
├── static/ # 地图标记图标(分色)
|
||||
└── requirements.txt
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
启动前需准备以下敏感文件(不上传到 Git,已在 `.gitignore` 排除):
|
||||
|
||||
| 文件 | 用途 | 示例 |
|
||||
|------|------|------|
|
||||
| `token_config.txt` | 全局默认微信 token | `token_id=1234567` |
|
||||
| `key.pem` / `private.key` | HTTPS 私钥 | `/BEGIN PRIVATE KEY/` |
|
||||
| `cert.pem` / `certificate.crt` / `ca_bundle.crt` | HTTPS 证书链 | `/BEGIN CERTIFICATE/` |
|
||||
|
||||
用户级授权凭据(`token_id` + `wx_signature`)存储在 `users.db` 的 `users` 表中,通过登录后从微信小程序抓包获取。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 1. 安装依赖
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 2. 准备敏感文件(见上方配置说明)
|
||||
|
||||
# 3. 启动服务
|
||||
python app.py
|
||||
# 默认监听 127.0.0.1:98,对外由 nginx 反代提供 HTTPS
|
||||
```
|
||||
|
||||
## 打包分发
|
||||
|
||||
```bash
|
||||
# 重新生成 1.zip(仅源码、模板、必要静态资源、测试和脚本)
|
||||
pwsh -File scripts/pack_zip.ps1
|
||||
```
|
||||
|
||||
打包排除证书/密钥/token/数据库/备份/缓存,以及安装包、截图和运行日志;打包脚本会自动
|
||||
校验关键文件是否在位(campus/alerts/subscribe/export 等新模块缺失会直接报错)。
|
||||
|
||||
## 抓包工具下载
|
||||
|
||||
「填写凭证」等弹窗里的下载按钮指向 `/download/capture-tool.exe`,对应磁盘文件
|
||||
`downloads/xbniu-capture-tool.exe`(约 160MB,不在版本库及源码包 1.zip 中,部署时另行提供)。
|
||||
|
||||
- 公开访问,无需登录:用户注册前就要先拿到工具,否则形成死循环。
|
||||
- 路由带 `conditional=True` 并显式返回 `Accept-Ranges: bytes`,支持断点续传。
|
||||
- 文件缺失时返回 `404 {"rtn_code": 404, "message": "安装包暂未上传"}`。
|
||||
- 微信/QQ/支付宝/钉钉/微博/抖音等内置浏览器会拦截 exe 下载,前端改为弹出
|
||||
「复制链接到外部浏览器」提示。
|
||||
|
||||
**nginx 注意**:大文件经 `proxy_pass` 下载时,若带宽较低可能被默认的
|
||||
`proxy_read_timeout 60s` 中断,建议在对应 `location` 上放宽:
|
||||
|
||||
```nginx
|
||||
location /download/ {
|
||||
proxy_pass http://127.0.0.1:98;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_max_temp_file_size 0; # 不缓冲大文件,直接透传
|
||||
}
|
||||
```
|
||||
|
||||
## 数据库表结构
|
||||
|
||||
| 表 | 用途 |
|
||||
|----|------|
|
||||
| `users` | 用户账号、微信授权凭据 |
|
||||
| `sessions` | 登录会话 token |
|
||||
| `reminders` | 租赁提醒订阅 |
|
||||
| `rentals` | 租车记录 + 多级通知状态(notified_10/5/3/2/1/0)|
|
||||
| `bike_history` | 车辆位置历史(含状态、电量)|
|
||||
| `snapshots` | 整体快照(总数、状态分布)|
|
||||
|
||||
## 核心机制
|
||||
|
||||
### 自适应采集
|
||||
|
||||
```python
|
||||
def get_adaptive_interval():
|
||||
# 夜间(23:00-07:00):1800-3600s(30-60 分钟)
|
||||
# 白天:300-600s(5-10 分钟)
|
||||
```
|
||||
|
||||
后台线程循环执行 `snapshot_bike_positions()`,调用 `/project/map?type=3` 拉取全部车辆,写入 `bike_history`。
|
||||
|
||||
### 数据清理
|
||||
|
||||
每 23 小时执行一次:删除 3 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
||||
|
||||
### 订单到期提醒
|
||||
|
||||
`timer.py` 在启动时恢复未到期的计时器(`restore_active_timers`),并在到期前 10/5/3/2/1/0 分钟触发邮件通知。每条 `rentals` 记录的 `notified_*` 字段标记对应级别是否已发送,避免重复通知。
|
||||
|
||||
## 主要接口
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| POST | `/api/collect_now` | 手动触发一次采集 |
|
||||
| GET | `/api/bike_history?code=xxx` | 查询指定车辆历史轨迹 |
|
||||
| GET | `/api/analysis/overview` | 状态分布 + 时段分布 + Top10 |
|
||||
| GET | `/api/analysis/heatmap?code=xxx` | 热力图数据 |
|
||||
|
||||
具体路由详见 `routes/*.py`。
|
||||
|
||||
## 注意事项
|
||||
|
||||
- `token_id` 与 `wx_signature` 来自微信小程序抓包,**修改后需重启服务或通过后台保存**
|
||||
- `users.db` 包含用户授权信息与历史轨迹,**不可公开**
|
||||
- HTTPS 证书文件(`*.pem` `*.crt` `*.key`)若损坏会导致小程序接口无法访问
|
||||
- 服务监听端口默认 98(非特权端口)
|
||||
|
||||
|
||||
+48
-48
@@ -1,48 +1,48 @@
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page()
|
||||
page.goto('http://127.0.0.1:5000/analysis')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug1.png')
|
||||
print("Page loaded, took debug1.png")
|
||||
|
||||
# 点击加载轨迹
|
||||
page.click('button:has-text("加载轨迹")')
|
||||
page.wait_for_timeout(4000)
|
||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug2.png')
|
||||
print("After loading trajectory, took debug2.png")
|
||||
|
||||
# 检查 traj-map 容器内的 DOM 结构
|
||||
html = page.evaluate('''() => {
|
||||
const el = document.getElementById("traj-map");
|
||||
if (!el) return "NOT FOUND";
|
||||
let info = "children: " + el.children.length + "\\n";
|
||||
let canvas = el.querySelectorAll("canvas");
|
||||
let mapdiv = el.querySelectorAll("div");
|
||||
info += "canvas count: " + canvas.length + "\\n";
|
||||
info += "div count: " + mapdiv.length + "\\n";
|
||||
for (let c of canvas) {
|
||||
info += " canvas: " + c.width + "x" + c.height + "\\n";
|
||||
}
|
||||
// 检查 pointer-events
|
||||
let allEls = Array.from(el.querySelectorAll("*"));
|
||||
let blocking = [];
|
||||
for (let e of allEls) {
|
||||
let style = window.getComputedStyle(e);
|
||||
let rect = e.getBoundingClientRect();
|
||||
if (rect.width > 0 && rect.height > 0) {
|
||||
let pe = style.pointerEvents;
|
||||
let vis = style.visibility;
|
||||
let op = style.opacity;
|
||||
let z = style.zIndex;
|
||||
let disp = style.display;
|
||||
blocking.push(e.className + " ptr:" + pe + " vis:" + vis + " z:" + z + " op:" + op + " disp:" + disp);
|
||||
}
|
||||
}
|
||||
return info + "\\nall elements:\\n" + blocking.join("\\n");
|
||||
}''')
|
||||
print(html)
|
||||
|
||||
browser.close()
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page()
|
||||
page.goto('http://127.0.0.1:5000/analysis')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug1.png')
|
||||
print("Page loaded, took debug1.png")
|
||||
|
||||
# 点击加载轨迹
|
||||
page.click('button:has-text("加载轨迹")')
|
||||
page.wait_for_timeout(4000)
|
||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug2.png')
|
||||
print("After loading trajectory, took debug2.png")
|
||||
|
||||
# 检查 traj-map 容器内的 DOM 结构
|
||||
html = page.evaluate('''() => {
|
||||
const el = document.getElementById("traj-map");
|
||||
if (!el) return "NOT FOUND";
|
||||
let info = "children: " + el.children.length + "\\n";
|
||||
let canvas = el.querySelectorAll("canvas");
|
||||
let mapdiv = el.querySelectorAll("div");
|
||||
info += "canvas count: " + canvas.length + "\\n";
|
||||
info += "div count: " + mapdiv.length + "\\n";
|
||||
for (let c of canvas) {
|
||||
info += " canvas: " + c.width + "x" + c.height + "\\n";
|
||||
}
|
||||
// 检查 pointer-events
|
||||
let allEls = Array.from(el.querySelectorAll("*"));
|
||||
let blocking = [];
|
||||
for (let e of allEls) {
|
||||
let style = window.getComputedStyle(e);
|
||||
let rect = e.getBoundingClientRect();
|
||||
if (rect.width > 0 && rect.height > 0) {
|
||||
let pe = style.pointerEvents;
|
||||
let vis = style.visibility;
|
||||
let op = style.opacity;
|
||||
let z = style.zIndex;
|
||||
let disp = style.display;
|
||||
blocking.push(e.className + " ptr:" + pe + " vis:" + vis + " z:" + z + " op:" + op + " disp:" + disp);
|
||||
}
|
||||
}
|
||||
return info + "\\nall elements:\\n" + blocking.join("\\n");
|
||||
}''')
|
||||
print(html)
|
||||
|
||||
browser.close()
|
||||
|
||||
+134
-134
@@ -1,134 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""注册/重置密码邮箱验证码:服务端 60 秒冷却、10 分钟有效期、5 次错误作废。
|
||||
内存存储(单进程部署足够);重启后验证码失效,用户重新发送即可。
|
||||
purpose 区分用途(register / reset),不同用途互不通用。"""
|
||||
import hashlib
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
import rate_limit
|
||||
from email_utils import render_email_safe, send_email
|
||||
|
||||
CODE_TTL_SECONDS = 10 * 60
|
||||
CODE_SEND_COOLDOWN = 60 # 同一邮箱两次发送的最小间隔(服务端强制)
|
||||
CODE_MAX_ATTEMPTS = 5
|
||||
SEND_IP_MAX_PER_HOUR = 10 # 同一 IP 每小时最多请求验证码次数
|
||||
|
||||
PURPOSES = ("register", "reset")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_codes: dict = {} # email -> {"hash": sha256hex, "expires": ts, "attempts": n, "sent_at": ts, "purpose": str}
|
||||
|
||||
# purpose -> (邮件主题, 页面标题, 首段说明, 顶部 kicker, 主题色)
|
||||
_PURPOSE_TITLES = {
|
||||
"register": (
|
||||
"【小白超人】注册验证码",
|
||||
"注册验证码",
|
||||
"你正在注册小白超人电动车地图账号,请在页面中输入下面的验证码完成注册。",
|
||||
"小白超人 · 账号注册",
|
||||
"#2563eb",
|
||||
),
|
||||
"reset": (
|
||||
"【小白超人】重置密码验证码",
|
||||
"重置密码验证码",
|
||||
"你正在重置小白超人电动车地图的登录密码,请在页面中输入下面的验证码。",
|
||||
"小白超人 · 重置密码",
|
||||
"#dc2626",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _now() -> float:
|
||||
return time.time()
|
||||
|
||||
|
||||
def _code_hash(code: str, email: str) -> str:
|
||||
return hashlib.sha256(f"{email.lower()}:{code}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _cleanup_locked(now: float):
|
||||
for email in [e for e, v in _codes.items() if v["expires"] <= now]:
|
||||
_codes.pop(email, None)
|
||||
|
||||
|
||||
def send_code(email: str, purpose: str = "register") -> tuple:
|
||||
"""发送验证码到邮箱。返回 (ok, message)。受 60s 邮箱冷却与每小时 IP 上限约束。"""
|
||||
email = (email or "").strip().lower()
|
||||
if purpose not in PURPOSES:
|
||||
purpose = "register"
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||
wait = int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||
return False, f"发送过于频繁,请 {wait} 秒后再试"
|
||||
code = f"{secrets.randbelow(1000000):06d}"
|
||||
subject, title, lead, kicker, accent = _PURPOSE_TITLES.get(
|
||||
purpose, _PURPOSE_TITLES["register"])
|
||||
ttl_minutes = CODE_TTL_SECONDS // 60
|
||||
# 纯文本版本保留(无 HTML 能力的客户端);HTML 版本走统一模板。
|
||||
plain = (f"{title}\n\n{lead}\n\n验证码:{code}\n\n"
|
||||
f"{ttl_minutes} 分钟内有效。若不是你本人操作,请忽略本邮件。")
|
||||
html_body = render_email_safe(
|
||||
kicker=kicker, title=title,
|
||||
lead=f"请在页面中输入下面的验证码,{ttl_minutes} 分钟内有效。",
|
||||
code=code, accent=accent,
|
||||
details=[("有效期", f"{ttl_minutes} 分钟"),
|
||||
("用途", "账号注册" if purpose == "register" else "重置登录密码")],
|
||||
footnote="若不是你本人操作,请忽略本邮件,你的账号不会受到任何影响。",
|
||||
)
|
||||
ok = send_email(email, subject, plain, html_body)
|
||||
if not ok:
|
||||
return False, "验证码邮件发送失败,请稍后重试"
|
||||
with _lock:
|
||||
_codes[email] = {
|
||||
"hash": _code_hash(code, email),
|
||||
"expires": now + CODE_TTL_SECONDS,
|
||||
"attempts": 0,
|
||||
"sent_at": now,
|
||||
"purpose": purpose,
|
||||
}
|
||||
return True, "验证码已发送"
|
||||
|
||||
|
||||
def check_send_cooldown(email: str) -> int:
|
||||
"""返回还需等待的秒数(0 = 可发送)。供接口在未真正发送前返回通用响应。"""
|
||||
email = (email or "").strip().lower()
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||
return int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||
return 0
|
||||
|
||||
|
||||
def verify_code(email: str, code: str, purpose: str = "register") -> bool:
|
||||
"""校验验证码;成功即作废,连续错误 5 次作废。purpose 必须与发送时一致。"""
|
||||
email = (email or "").strip().lower()
|
||||
code = (code or "").strip()
|
||||
if purpose not in PURPOSES:
|
||||
purpose = "register"
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if not entry or entry["expires"] <= now or entry["attempts"] >= CODE_MAX_ATTEMPTS:
|
||||
return False
|
||||
if entry.get("purpose", "register") != purpose:
|
||||
# 用途不匹配(例如拿注册验证码去重置密码):按错误处理并计数
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
if not (len(code) == 6 and code.isdigit()):
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
if secrets.compare_digest(entry["hash"], _code_hash(code, email)):
|
||||
_codes.pop(email, None)
|
||||
return True
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
|
||||
|
||||
def ip_send_allowed(ip: str) -> bool:
|
||||
"""同一 IP 每小时验证码发送次数上限。"""
|
||||
return rate_limit.hit(("send_code", ip), SEND_IP_MAX_PER_HOUR, 3600)
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""注册/重置密码邮箱验证码:服务端 60 秒冷却、10 分钟有效期、5 次错误作废。
|
||||
内存存储(单进程部署足够);重启后验证码失效,用户重新发送即可。
|
||||
purpose 区分用途(register / reset),不同用途互不通用。"""
|
||||
import hashlib
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
import rate_limit
|
||||
from email_utils import render_email_safe, send_email
|
||||
|
||||
CODE_TTL_SECONDS = 10 * 60
|
||||
CODE_SEND_COOLDOWN = 60 # 同一邮箱两次发送的最小间隔(服务端强制)
|
||||
CODE_MAX_ATTEMPTS = 5
|
||||
SEND_IP_MAX_PER_HOUR = 10 # 同一 IP 每小时最多请求验证码次数
|
||||
|
||||
PURPOSES = ("register", "reset")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_codes: dict = {} # email -> {"hash": sha256hex, "expires": ts, "attempts": n, "sent_at": ts, "purpose": str}
|
||||
|
||||
# purpose -> (邮件主题, 页面标题, 首段说明, 顶部 kicker, 主题色)
|
||||
_PURPOSE_TITLES = {
|
||||
"register": (
|
||||
"【小白超人】注册验证码",
|
||||
"注册验证码",
|
||||
"你正在注册小白超人电动车地图账号,请在页面中输入下面的验证码完成注册。",
|
||||
"小白超人 · 账号注册",
|
||||
"#2563eb",
|
||||
),
|
||||
"reset": (
|
||||
"【小白超人】重置密码验证码",
|
||||
"重置密码验证码",
|
||||
"你正在重置小白超人电动车地图的登录密码,请在页面中输入下面的验证码。",
|
||||
"小白超人 · 重置密码",
|
||||
"#dc2626",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _now() -> float:
|
||||
return time.time()
|
||||
|
||||
|
||||
def _code_hash(code: str, email: str) -> str:
|
||||
return hashlib.sha256(f"{email.lower()}:{code}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _cleanup_locked(now: float):
|
||||
for email in [e for e, v in _codes.items() if v["expires"] <= now]:
|
||||
_codes.pop(email, None)
|
||||
|
||||
|
||||
def send_code(email: str, purpose: str = "register") -> tuple:
|
||||
"""发送验证码到邮箱。返回 (ok, message)。受 60s 邮箱冷却与每小时 IP 上限约束。"""
|
||||
email = (email or "").strip().lower()
|
||||
if purpose not in PURPOSES:
|
||||
purpose = "register"
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||
wait = int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||
return False, f"发送过于频繁,请 {wait} 秒后再试"
|
||||
code = f"{secrets.randbelow(1000000):06d}"
|
||||
subject, title, lead, kicker, accent = _PURPOSE_TITLES.get(
|
||||
purpose, _PURPOSE_TITLES["register"])
|
||||
ttl_minutes = CODE_TTL_SECONDS // 60
|
||||
# 纯文本版本保留(无 HTML 能力的客户端);HTML 版本走统一模板。
|
||||
plain = (f"{title}\n\n{lead}\n\n验证码:{code}\n\n"
|
||||
f"{ttl_minutes} 分钟内有效。若不是你本人操作,请忽略本邮件。")
|
||||
html_body = render_email_safe(
|
||||
kicker=kicker, title=title,
|
||||
lead=f"请在页面中输入下面的验证码,{ttl_minutes} 分钟内有效。",
|
||||
code=code, accent=accent,
|
||||
details=[("有效期", f"{ttl_minutes} 分钟"),
|
||||
("用途", "账号注册" if purpose == "register" else "重置登录密码")],
|
||||
footnote="若不是你本人操作,请忽略本邮件,你的账号不会受到任何影响。",
|
||||
)
|
||||
ok = send_email(email, subject, plain, html_body)
|
||||
if not ok:
|
||||
return False, "验证码邮件发送失败,请稍后重试"
|
||||
with _lock:
|
||||
_codes[email] = {
|
||||
"hash": _code_hash(code, email),
|
||||
"expires": now + CODE_TTL_SECONDS,
|
||||
"attempts": 0,
|
||||
"sent_at": now,
|
||||
"purpose": purpose,
|
||||
}
|
||||
return True, "验证码已发送"
|
||||
|
||||
|
||||
def check_send_cooldown(email: str) -> int:
|
||||
"""返回还需等待的秒数(0 = 可发送)。供接口在未真正发送前返回通用响应。"""
|
||||
email = (email or "").strip().lower()
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||
return int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||
return 0
|
||||
|
||||
|
||||
def verify_code(email: str, code: str, purpose: str = "register") -> bool:
|
||||
"""校验验证码;成功即作废,连续错误 5 次作废。purpose 必须与发送时一致。"""
|
||||
email = (email or "").strip().lower()
|
||||
code = (code or "").strip()
|
||||
if purpose not in PURPOSES:
|
||||
purpose = "register"
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if not entry or entry["expires"] <= now or entry["attempts"] >= CODE_MAX_ATTEMPTS:
|
||||
return False
|
||||
if entry.get("purpose", "register") != purpose:
|
||||
# 用途不匹配(例如拿注册验证码去重置密码):按错误处理并计数
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
if not (len(code) == 6 and code.isdigit()):
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
if secrets.compare_digest(entry["hash"], _code_hash(code, email)):
|
||||
_codes.pop(email, None)
|
||||
return True
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
|
||||
|
||||
def ip_send_allowed(ip: str) -> bool:
|
||||
"""同一 IP 每小时验证码发送次数上限。"""
|
||||
return rate_limit.hit(("send_code", ip), SEND_IP_MAX_PER_HOUR, 3600)
|
||||
|
||||
+55
-55
@@ -1,55 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
"""生成车辆标记图标"""
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import os
|
||||
|
||||
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
||||
os.makedirs(STATIC_DIR, exist_ok=True)
|
||||
|
||||
# 状态颜色 (R, G, B)
|
||||
COLORS = {
|
||||
"green": "#4CAF50",
|
||||
"pink": "#E91E8C",
|
||||
"orange": "#FF9800",
|
||||
"gray": "#9E9E9E",
|
||||
"red": "#F44336",
|
||||
}
|
||||
|
||||
def make_icon(color_hex, label="", size=36):
|
||||
"""生成圆形标记图标,label=文字(如百分比或状态符)"""
|
||||
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
r = size // 2
|
||||
cx, cy = r, r
|
||||
# 填充圆
|
||||
draw.ellipse([2, 2, size-3, size-3], fill=color_hex + "E0") # 带透明度
|
||||
# 边框
|
||||
draw.ellipse([2, 2, size-3, size-3], outline=color_hex, width=2)
|
||||
|
||||
if label:
|
||||
# 文字居中
|
||||
try:
|
||||
font_size = 11 if len(label) <= 2 else 9
|
||||
font = ImageFont.truetype("arial.ttf", font_size)
|
||||
except Exception:
|
||||
font = ImageFont.load_default()
|
||||
bbox = draw.textbbox((0, 0), label, font=font)
|
||||
tw = bbox[2] - bbox[0]
|
||||
th = bbox[3] - bbox[1]
|
||||
tx = cx - tw // 2 - bbox[0]
|
||||
ty = cy - th // 2 - bbox[1]
|
||||
# 白色文字
|
||||
draw.text((tx, ty), label, fill="#FFFFFF", font=font)
|
||||
|
||||
path = os.path.join(STATIC_DIR, f"marker_{color_hex[1:]}.png")
|
||||
img.save(path, "PNG")
|
||||
print(f" {path}")
|
||||
return path
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("生成标记图标...")
|
||||
for name, color in COLORS.items():
|
||||
make_icon(color)
|
||||
print("完成!")
|
||||
#!/usr/bin/env python3
|
||||
"""生成车辆标记图标"""
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import os
|
||||
|
||||
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
||||
os.makedirs(STATIC_DIR, exist_ok=True)
|
||||
|
||||
# 状态颜色 (R, G, B)
|
||||
COLORS = {
|
||||
"green": "#4CAF50",
|
||||
"pink": "#E91E8C",
|
||||
"orange": "#FF9800",
|
||||
"gray": "#9E9E9E",
|
||||
"red": "#F44336",
|
||||
}
|
||||
|
||||
def make_icon(color_hex, label="", size=36):
|
||||
"""生成圆形标记图标,label=文字(如百分比或状态符)"""
|
||||
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
r = size // 2
|
||||
cx, cy = r, r
|
||||
# 填充圆
|
||||
draw.ellipse([2, 2, size-3, size-3], fill=color_hex + "E0") # 带透明度
|
||||
# 边框
|
||||
draw.ellipse([2, 2, size-3, size-3], outline=color_hex, width=2)
|
||||
|
||||
if label:
|
||||
# 文字居中
|
||||
try:
|
||||
font_size = 11 if len(label) <= 2 else 9
|
||||
font = ImageFont.truetype("arial.ttf", font_size)
|
||||
except Exception:
|
||||
font = ImageFont.load_default()
|
||||
bbox = draw.textbbox((0, 0), label, font=font)
|
||||
tw = bbox[2] - bbox[0]
|
||||
th = bbox[3] - bbox[1]
|
||||
tx = cx - tw // 2 - bbox[0]
|
||||
ty = cy - th // 2 - bbox[1]
|
||||
# 白色文字
|
||||
draw.text((tx, ty), label, fill="#FFFFFF", font=font)
|
||||
|
||||
path = os.path.join(STATIC_DIR, f"marker_{color_hex[1:]}.png")
|
||||
img.save(path, "PNG")
|
||||
print(f" {path}")
|
||||
return path
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("生成标记图标...")
|
||||
for name, color in COLORS.items():
|
||||
make_icon(color)
|
||||
print("完成!")
|
||||
|
||||
+1226
-1226
File diff suppressed because it is too large
Load Diff
+743
-743
File diff suppressed because it is too large
Load Diff
+412
-412
@@ -1,412 +1,412 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""地图数据、寻车、分析等路由"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
import hashlib
|
||||
import threading
|
||||
import asyncio
|
||||
import aiohttp
|
||||
from pathlib import Path
|
||||
from flask import Blueprint, current_app, jsonify, request, render_template
|
||||
|
||||
from db import get_db, get_user_display_name, get_user_auth
|
||||
from routes.auth import get_current_user
|
||||
from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS
|
||||
|
||||
bp = Blueprint("map_api", __name__)
|
||||
|
||||
# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放
|
||||
BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
|
||||
|
||||
# 并行寻车任务
|
||||
ring_tasks: dict = {}
|
||||
_ring_lock = threading.Lock()
|
||||
|
||||
|
||||
async def ring_single_bike_async(session, bike_code, school_id=10):
|
||||
try:
|
||||
headers = {**SEARCH_HEADERS, **get_signature_headers()}
|
||||
async with session.post(
|
||||
SEARCH_BIKE_URL,
|
||||
json={"code": bike_code, "school_id": school_id},
|
||||
headers=headers,
|
||||
timeout=aiohttp.ClientTimeout(total=5)
|
||||
) as resp:
|
||||
data = await resp.json()
|
||||
return data.get("rtn_code") == 0 or data.get("success") is True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def run_ring_task(task_id: str):
|
||||
global ring_tasks
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return
|
||||
bikes = task["bikes"]
|
||||
total = len(bikes)
|
||||
task["total"] = total
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop)
|
||||
try:
|
||||
async def run_session():
|
||||
semaphore = asyncio.Semaphore(20)
|
||||
async with aiohttp.ClientSession(connector=connector) as session:
|
||||
async def ring_one(idx, code):
|
||||
async with semaphore:
|
||||
if task["cancelled"]:
|
||||
return False
|
||||
result = await ring_single_bike_async(session, code, 10)
|
||||
with _ring_lock:
|
||||
task["done"] += 1
|
||||
if result:
|
||||
task["success"] += 1
|
||||
else:
|
||||
task["failed"] += 1
|
||||
task["last_update"] = time.time()
|
||||
return result
|
||||
batch_size = 20
|
||||
for i in range(0, len(bikes), batch_size):
|
||||
if task["cancelled"]:
|
||||
break
|
||||
batch = bikes[i:i + batch_size]
|
||||
await asyncio.gather(
|
||||
*[ring_one(i + j, b["code"]) for j, b in enumerate(batch)],
|
||||
return_exceptions=True
|
||||
)
|
||||
await asyncio.sleep(0.1)
|
||||
loop.run_until_complete(run_session())
|
||||
finally:
|
||||
with _ring_lock:
|
||||
task["status"] = "completed" if not task["cancelled"] else "cancelled"
|
||||
task["done"] = total
|
||||
loop.close()
|
||||
|
||||
|
||||
@bp.route("/api/ring_all", methods=["POST"])
|
||||
def api_ring_all():
|
||||
global ring_tasks
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
if user["email"] not in BATCH_RING_ALLOWED_EMAILS:
|
||||
return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"})
|
||||
data = request.get_json() or {}
|
||||
codes = data.get("codes", [])
|
||||
if isinstance(codes, str):
|
||||
codes = [codes]
|
||||
if not codes:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}")
|
||||
task_id = str(uuid.uuid4())[:8]
|
||||
task = {
|
||||
"status": "running", "total": len(codes), "done": 0,
|
||||
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
|
||||
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
|
||||
}
|
||||
with _ring_lock:
|
||||
ring_tasks[task_id] = task
|
||||
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
|
||||
t.start()
|
||||
return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes),
|
||||
"message": f"任务已启动,共 {len(codes)} 辆车"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_status/<task_id>")
|
||||
def api_ring_status(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
|
||||
"done": task["done"], "success": task["success"], "failed": task["failed"]})
|
||||
|
||||
|
||||
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
|
||||
def api_ring_cancel(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
if task["status"] != "running":
|
||||
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
|
||||
task["cancelled"] = True
|
||||
task["status"] = "cancelling"
|
||||
return jsonify({"rtn_code": 0, "message": "取消请求已发送"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_progress/<task_id>")
|
||||
def api_ring_progress(task_id):
|
||||
from flask import Response as FlaskResponse
|
||||
global ring_tasks
|
||||
def _sse(obj):
|
||||
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
||||
def generate():
|
||||
last_done = -1
|
||||
last_status = None
|
||||
tick = 0
|
||||
while True:
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
|
||||
yield _sse({"type": "error", "message": "任务不存在或已结束"})
|
||||
return
|
||||
done = task["done"]
|
||||
status = task["status"]
|
||||
if done != last_done or status != last_status:
|
||||
last_done = done
|
||||
last_status = status
|
||||
yield _sse({
|
||||
"type": "progress",
|
||||
"status": status,
|
||||
"done": done,
|
||||
"total": task["total"],
|
||||
"success": task["success"],
|
||||
"failed": task["failed"],
|
||||
})
|
||||
if status in ("completed", "cancelled"):
|
||||
# 已结束,补发一条 done 事件后关闭
|
||||
yield _sse({"type": "done", "status": status})
|
||||
return
|
||||
tick += 1
|
||||
if tick >= 20: # 约 10s 一次心跳,避免代理/连接超时被判定为断开
|
||||
tick = 0
|
||||
yield ": ping\n\n"
|
||||
time.sleep(0.5)
|
||||
return FlaskResponse(
|
||||
generate(),
|
||||
mimetype="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
|
||||
def api_ring_status_clear(task_id):
|
||||
with _ring_lock:
|
||||
ring_tasks.pop(task_id, None)
|
||||
return jsonify({"rtn_code": 0, "message": "已清除"})
|
||||
|
||||
|
||||
@bp.route("/api/map")
|
||||
def api_map():
|
||||
# 非登录人员不能使用:地图数据需登录后查看
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
bike_type = request.args.get("type", "1").strip()
|
||||
from map_cache import MAP_TYPES
|
||||
if bike_type not in MAP_TYPES:
|
||||
return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400
|
||||
result = request_api("GET", "/project/map", params={"type": bike_type})
|
||||
# 上游错误文案统一翻译(成功响应原样透传)
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
response = jsonify(result)
|
||||
# Only the server snapshot is cached; browsers must ask the server on refresh.
|
||||
response.headers["Cache-Control"] = "private, no-store"
|
||||
response.headers["Vary"] = "Authorization"
|
||||
response.headers["X-Map-Server-Time"] = str(time.time())
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/api/bicycle", methods=["GET", "POST"])
|
||||
def api_bicycle():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
code = data.get("code", "")
|
||||
if not code:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}")
|
||||
result = request_api("POST", "/project/bicycle", data={"code": code})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/find_bike", methods=["POST"])
|
||||
def api_find_bike():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
keyword = (data.get("keyword") or data.get("code") or "").strip()
|
||||
if not keyword:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少关键字"})
|
||||
school_id = data.get("school_id", 10)
|
||||
result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/config")
|
||||
def api_config():
|
||||
return jsonify({
|
||||
"center_lat": 36.531820, "center_lng": 116.780180,
|
||||
"scale": 17, "school_name": "山东管理学院",
|
||||
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
|
||||
})
|
||||
|
||||
|
||||
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
|
||||
@bp.route("/api/map/freshness")
|
||||
def api_map_freshness():
|
||||
"""优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。
|
||||
|
||||
只读取缓存元数据,不会为了查询时间额外请求上游。
|
||||
"""
|
||||
from map_cache import shared_map_cache
|
||||
snapshot = shared_map_cache.freshness(request.args.get("type", "3"))
|
||||
if snapshot is not None:
|
||||
response = jsonify({"rtn_code": 0, "data": snapshot})
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone()
|
||||
conn.close()
|
||||
latest = row["latest"] if row else None
|
||||
if not latest:
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}})
|
||||
|
||||
import datetime as dt
|
||||
import sqlite3
|
||||
# recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源
|
||||
try:
|
||||
naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S")
|
||||
latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
|
||||
now = dt.datetime.now(latest_dt.tzinfo)
|
||||
stale = max(0, int((now - latest_dt).total_seconds()))
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": None,
|
||||
"interval_hint": "时间格式异常"}})
|
||||
|
||||
hint = "白天 5-10 分钟 / 夜间 30-60 分钟"
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": stale, "interval_hint": hint}})
|
||||
|
||||
|
||||
@bp.route("/api/campus/locations")
|
||||
def campus_locations():
|
||||
"""校园地点(单点模型)。
|
||||
|
||||
- kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」;
|
||||
- kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。
|
||||
|
||||
返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。
|
||||
"""
|
||||
from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations
|
||||
result = []
|
||||
for loc in load_locations():
|
||||
item = {
|
||||
"id": loc["id"],
|
||||
"name": loc["name"],
|
||||
"kind": loc.get("kind") or "poi",
|
||||
"latitude": loc.get("latitude"),
|
||||
"longitude": loc.get("longitude"),
|
||||
"radius": loc.get("radius") or (
|
||||
DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None),
|
||||
"bd09": None,
|
||||
}
|
||||
if loc.get("latitude") is not None and loc.get("longitude") is not None:
|
||||
bd = gcj02_to_bd09(loc["longitude"], loc["latitude"])
|
||||
item["bd09"] = {"lat": bd[1], "lng": bd[0]}
|
||||
result.append(item)
|
||||
return jsonify({"rtn_code": 0, "data": result})
|
||||
|
||||
|
||||
# ========== 用户信息 API ==========
|
||||
@bp.route("/api/user/info")
|
||||
def api_user_info():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
from wechat import request_with_user_auth
|
||||
token_id, access_token = get_user_auth(user["id"])
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"})
|
||||
|
||||
result = request_with_user_auth(user["id"], "GET", "/user/info")
|
||||
if result.get("rtn_code") != 0:
|
||||
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")})
|
||||
|
||||
data = result.get("data", {})
|
||||
non_deal = data.get("nonDealOrder")
|
||||
true_name = ""
|
||||
account = data.get("account", {})
|
||||
if isinstance(account, str):
|
||||
try:
|
||||
account = json.loads(account)
|
||||
except Exception:
|
||||
account = {}
|
||||
true_name = account.get("trueName", "") if isinstance(account, dict) else ""
|
||||
|
||||
out_money = data.get("bus_account", {}).get("outMoneyBus", 0)
|
||||
save_money = data.get("bus_account", {}).get("saveMoneyBus", 0)
|
||||
|
||||
return jsonify({
|
||||
"rtn_code": 0, "has_auth": True,
|
||||
"data": {
|
||||
"true_name": true_name, "out_money": out_money,
|
||||
"save_money": save_money, "has_auth": True,
|
||||
"nonDealOrder": non_deal,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
# ========== 首页路由 ==========
|
||||
MAP_ASSETS = (
|
||||
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
|
||||
"js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
|
||||
"js/settings-pages.js", "js/map.js",
|
||||
)
|
||||
|
||||
|
||||
def _map_asset_version():
|
||||
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
|
||||
digest = hashlib.sha256()
|
||||
for filename in MAP_ASSETS:
|
||||
digest.update(filename.encode())
|
||||
try:
|
||||
digest.update((Path(current_app.static_folder) / filename).read_bytes())
|
||||
except FileNotFoundError:
|
||||
digest.update(b"missing")
|
||||
return digest.hexdigest()[:16]
|
||||
|
||||
|
||||
@bp.route("/")
|
||||
def index():
|
||||
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/analysis.html")
|
||||
def analysis_page():
|
||||
return render_template("analysis.html")
|
||||
|
||||
|
||||
@bp.route("/ring_progress.html")
|
||||
def ring_progress():
|
||||
return render_template("ring_progress.html")
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""地图数据、寻车、分析等路由"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
import hashlib
|
||||
import threading
|
||||
import asyncio
|
||||
import aiohttp
|
||||
from pathlib import Path
|
||||
from flask import Blueprint, current_app, jsonify, request, render_template
|
||||
|
||||
from db import get_db, get_user_display_name, get_user_auth
|
||||
from routes.auth import get_current_user
|
||||
from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS
|
||||
|
||||
bp = Blueprint("map_api", __name__)
|
||||
|
||||
# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放
|
||||
BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
|
||||
|
||||
# 并行寻车任务
|
||||
ring_tasks: dict = {}
|
||||
_ring_lock = threading.Lock()
|
||||
|
||||
|
||||
async def ring_single_bike_async(session, bike_code, school_id=10):
|
||||
try:
|
||||
headers = {**SEARCH_HEADERS, **get_signature_headers()}
|
||||
async with session.post(
|
||||
SEARCH_BIKE_URL,
|
||||
json={"code": bike_code, "school_id": school_id},
|
||||
headers=headers,
|
||||
timeout=aiohttp.ClientTimeout(total=5)
|
||||
) as resp:
|
||||
data = await resp.json()
|
||||
return data.get("rtn_code") == 0 or data.get("success") is True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def run_ring_task(task_id: str):
|
||||
global ring_tasks
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return
|
||||
bikes = task["bikes"]
|
||||
total = len(bikes)
|
||||
task["total"] = total
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop)
|
||||
try:
|
||||
async def run_session():
|
||||
semaphore = asyncio.Semaphore(20)
|
||||
async with aiohttp.ClientSession(connector=connector) as session:
|
||||
async def ring_one(idx, code):
|
||||
async with semaphore:
|
||||
if task["cancelled"]:
|
||||
return False
|
||||
result = await ring_single_bike_async(session, code, 10)
|
||||
with _ring_lock:
|
||||
task["done"] += 1
|
||||
if result:
|
||||
task["success"] += 1
|
||||
else:
|
||||
task["failed"] += 1
|
||||
task["last_update"] = time.time()
|
||||
return result
|
||||
batch_size = 20
|
||||
for i in range(0, len(bikes), batch_size):
|
||||
if task["cancelled"]:
|
||||
break
|
||||
batch = bikes[i:i + batch_size]
|
||||
await asyncio.gather(
|
||||
*[ring_one(i + j, b["code"]) for j, b in enumerate(batch)],
|
||||
return_exceptions=True
|
||||
)
|
||||
await asyncio.sleep(0.1)
|
||||
loop.run_until_complete(run_session())
|
||||
finally:
|
||||
with _ring_lock:
|
||||
task["status"] = "completed" if not task["cancelled"] else "cancelled"
|
||||
task["done"] = total
|
||||
loop.close()
|
||||
|
||||
|
||||
@bp.route("/api/ring_all", methods=["POST"])
|
||||
def api_ring_all():
|
||||
global ring_tasks
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
if user["email"] not in BATCH_RING_ALLOWED_EMAILS:
|
||||
return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"})
|
||||
data = request.get_json() or {}
|
||||
codes = data.get("codes", [])
|
||||
if isinstance(codes, str):
|
||||
codes = [codes]
|
||||
if not codes:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}")
|
||||
task_id = str(uuid.uuid4())[:8]
|
||||
task = {
|
||||
"status": "running", "total": len(codes), "done": 0,
|
||||
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
|
||||
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
|
||||
}
|
||||
with _ring_lock:
|
||||
ring_tasks[task_id] = task
|
||||
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
|
||||
t.start()
|
||||
return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes),
|
||||
"message": f"任务已启动,共 {len(codes)} 辆车"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_status/<task_id>")
|
||||
def api_ring_status(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
|
||||
"done": task["done"], "success": task["success"], "failed": task["failed"]})
|
||||
|
||||
|
||||
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
|
||||
def api_ring_cancel(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
if task["status"] != "running":
|
||||
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
|
||||
task["cancelled"] = True
|
||||
task["status"] = "cancelling"
|
||||
return jsonify({"rtn_code": 0, "message": "取消请求已发送"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_progress/<task_id>")
|
||||
def api_ring_progress(task_id):
|
||||
from flask import Response as FlaskResponse
|
||||
global ring_tasks
|
||||
def _sse(obj):
|
||||
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
||||
def generate():
|
||||
last_done = -1
|
||||
last_status = None
|
||||
tick = 0
|
||||
while True:
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
|
||||
yield _sse({"type": "error", "message": "任务不存在或已结束"})
|
||||
return
|
||||
done = task["done"]
|
||||
status = task["status"]
|
||||
if done != last_done or status != last_status:
|
||||
last_done = done
|
||||
last_status = status
|
||||
yield _sse({
|
||||
"type": "progress",
|
||||
"status": status,
|
||||
"done": done,
|
||||
"total": task["total"],
|
||||
"success": task["success"],
|
||||
"failed": task["failed"],
|
||||
})
|
||||
if status in ("completed", "cancelled"):
|
||||
# 已结束,补发一条 done 事件后关闭
|
||||
yield _sse({"type": "done", "status": status})
|
||||
return
|
||||
tick += 1
|
||||
if tick >= 20: # 约 10s 一次心跳,避免代理/连接超时被判定为断开
|
||||
tick = 0
|
||||
yield ": ping\n\n"
|
||||
time.sleep(0.5)
|
||||
return FlaskResponse(
|
||||
generate(),
|
||||
mimetype="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
|
||||
def api_ring_status_clear(task_id):
|
||||
with _ring_lock:
|
||||
ring_tasks.pop(task_id, None)
|
||||
return jsonify({"rtn_code": 0, "message": "已清除"})
|
||||
|
||||
|
||||
@bp.route("/api/map")
|
||||
def api_map():
|
||||
# 非登录人员不能使用:地图数据需登录后查看
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
bike_type = request.args.get("type", "1").strip()
|
||||
from map_cache import MAP_TYPES
|
||||
if bike_type not in MAP_TYPES:
|
||||
return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400
|
||||
result = request_api("GET", "/project/map", params={"type": bike_type})
|
||||
# 上游错误文案统一翻译(成功响应原样透传)
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
response = jsonify(result)
|
||||
# Only the server snapshot is cached; browsers must ask the server on refresh.
|
||||
response.headers["Cache-Control"] = "private, no-store"
|
||||
response.headers["Vary"] = "Authorization"
|
||||
response.headers["X-Map-Server-Time"] = str(time.time())
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/api/bicycle", methods=["GET", "POST"])
|
||||
def api_bicycle():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
code = data.get("code", "")
|
||||
if not code:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}")
|
||||
result = request_api("POST", "/project/bicycle", data={"code": code})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/find_bike", methods=["POST"])
|
||||
def api_find_bike():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
keyword = (data.get("keyword") or data.get("code") or "").strip()
|
||||
if not keyword:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少关键字"})
|
||||
school_id = data.get("school_id", 10)
|
||||
result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/config")
|
||||
def api_config():
|
||||
return jsonify({
|
||||
"center_lat": 36.531820, "center_lng": 116.780180,
|
||||
"scale": 17, "school_name": "山东管理学院",
|
||||
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
|
||||
})
|
||||
|
||||
|
||||
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
|
||||
@bp.route("/api/map/freshness")
|
||||
def api_map_freshness():
|
||||
"""优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。
|
||||
|
||||
只读取缓存元数据,不会为了查询时间额外请求上游。
|
||||
"""
|
||||
from map_cache import shared_map_cache
|
||||
snapshot = shared_map_cache.freshness(request.args.get("type", "3"))
|
||||
if snapshot is not None:
|
||||
response = jsonify({"rtn_code": 0, "data": snapshot})
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone()
|
||||
conn.close()
|
||||
latest = row["latest"] if row else None
|
||||
if not latest:
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}})
|
||||
|
||||
import datetime as dt
|
||||
import sqlite3
|
||||
# recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源
|
||||
try:
|
||||
naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S")
|
||||
latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
|
||||
now = dt.datetime.now(latest_dt.tzinfo)
|
||||
stale = max(0, int((now - latest_dt).total_seconds()))
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": None,
|
||||
"interval_hint": "时间格式异常"}})
|
||||
|
||||
hint = "白天 5-10 分钟 / 夜间 30-60 分钟"
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": stale, "interval_hint": hint}})
|
||||
|
||||
|
||||
@bp.route("/api/campus/locations")
|
||||
def campus_locations():
|
||||
"""校园地点(单点模型)。
|
||||
|
||||
- kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」;
|
||||
- kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。
|
||||
|
||||
返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。
|
||||
"""
|
||||
from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations
|
||||
result = []
|
||||
for loc in load_locations():
|
||||
item = {
|
||||
"id": loc["id"],
|
||||
"name": loc["name"],
|
||||
"kind": loc.get("kind") or "poi",
|
||||
"latitude": loc.get("latitude"),
|
||||
"longitude": loc.get("longitude"),
|
||||
"radius": loc.get("radius") or (
|
||||
DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None),
|
||||
"bd09": None,
|
||||
}
|
||||
if loc.get("latitude") is not None and loc.get("longitude") is not None:
|
||||
bd = gcj02_to_bd09(loc["longitude"], loc["latitude"])
|
||||
item["bd09"] = {"lat": bd[1], "lng": bd[0]}
|
||||
result.append(item)
|
||||
return jsonify({"rtn_code": 0, "data": result})
|
||||
|
||||
|
||||
# ========== 用户信息 API ==========
|
||||
@bp.route("/api/user/info")
|
||||
def api_user_info():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
from wechat import request_with_user_auth
|
||||
token_id, access_token = get_user_auth(user["id"])
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"})
|
||||
|
||||
result = request_with_user_auth(user["id"], "GET", "/user/info")
|
||||
if result.get("rtn_code") != 0:
|
||||
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")})
|
||||
|
||||
data = result.get("data", {})
|
||||
non_deal = data.get("nonDealOrder")
|
||||
true_name = ""
|
||||
account = data.get("account", {})
|
||||
if isinstance(account, str):
|
||||
try:
|
||||
account = json.loads(account)
|
||||
except Exception:
|
||||
account = {}
|
||||
true_name = account.get("trueName", "") if isinstance(account, dict) else ""
|
||||
|
||||
out_money = data.get("bus_account", {}).get("outMoneyBus", 0)
|
||||
save_money = data.get("bus_account", {}).get("saveMoneyBus", 0)
|
||||
|
||||
return jsonify({
|
||||
"rtn_code": 0, "has_auth": True,
|
||||
"data": {
|
||||
"true_name": true_name, "out_money": out_money,
|
||||
"save_money": save_money, "has_auth": True,
|
||||
"nonDealOrder": non_deal,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
# ========== 首页路由 ==========
|
||||
MAP_ASSETS = (
|
||||
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
|
||||
"js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
|
||||
"js/settings-pages.js", "js/map.js",
|
||||
)
|
||||
|
||||
|
||||
def _map_asset_version():
|
||||
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
|
||||
digest = hashlib.sha256()
|
||||
for filename in MAP_ASSETS:
|
||||
digest.update(filename.encode())
|
||||
try:
|
||||
digest.update((Path(current_app.static_folder) / filename).read_bytes())
|
||||
except FileNotFoundError:
|
||||
digest.update(b"missing")
|
||||
return digest.hexdigest()[:16]
|
||||
|
||||
|
||||
@bp.route("/")
|
||||
def index():
|
||||
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/analysis.html")
|
||||
def analysis_page():
|
||||
return render_template("analysis.html")
|
||||
|
||||
|
||||
@bp.route("/ring_progress.html")
|
||||
def ring_progress():
|
||||
return render_template("ring_progress.html")
|
||||
|
||||
+1493
-1493
File diff suppressed because it is too large
Load Diff
+932
-932
File diff suppressed because it is too large
Load Diff
@@ -62,4 +62,4 @@ try {
|
||||
Write-Host "1.zip 完成:$($names.Count) 个文件,$sizeKB KB(仅源码与必要资源)"
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $pendingZip) { Remove-Item -LiteralPath $pendingZip -Force }
|
||||
}
|
||||
}
|
||||
|
||||
+279
-279
@@ -1,279 +1,279 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""冒烟测试:验证应用可启动、路由无冲突、关键接口可响应。"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根
|
||||
|
||||
# 注意: app.py 导入时会重新包装 sys.stdout, 这里不能自己再包一层,
|
||||
# 否则旧包装器被 GC 时会关闭底层 buffer。编码由 PYTHONIOENCODING 控制。
|
||||
_ORIG_STDOUT = sys.stdout # 持有引用, 防止被 GC 后关闭底层流
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
PASS, FAIL = [], []
|
||||
|
||||
|
||||
def check(name, fn):
|
||||
try:
|
||||
detail = fn()
|
||||
PASS.append((name, detail))
|
||||
print(f" [PASS] {name}" + (f" — {detail}" if detail else ""))
|
||||
except Exception as e:
|
||||
FAIL.append((name, f"{type(e).__name__}: {e}"))
|
||||
print(f" [FAIL] {name} — {type(e).__name__}: {e}")
|
||||
|
||||
|
||||
print("=" * 60)
|
||||
print("1) 模块导入检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def import_app():
|
||||
import app as app_module
|
||||
return f"app 模块导入成功, 蓝图 {len(app_module.app.blueprints)} 个: {', '.join(app_module.app.blueprints)}"
|
||||
|
||||
|
||||
check("导入 app.py 及全部依赖 (db/wechat/timer/routes.*)", import_app)
|
||||
|
||||
|
||||
def import_side_modules():
|
||||
import rental_mail, email_utils, generate_icons # noqa: F401
|
||||
return "rental_mail / email_utils / generate_icons 导入成功"
|
||||
|
||||
|
||||
check("导入其余业务模块", import_side_modules)
|
||||
|
||||
app_obj = None
|
||||
try:
|
||||
import app as app_module
|
||||
app_obj = app_module.app
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("2) 路由冲突检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def route_conflicts():
|
||||
rules = defaultdict(list)
|
||||
for r in app_obj.url_map.iter_rules():
|
||||
if r.endpoint == "static":
|
||||
continue
|
||||
methods = sorted(m for m in r.methods if m not in ("HEAD", "OPTIONS"))
|
||||
for m in methods:
|
||||
rules[(m, r.rule)].append(r.endpoint)
|
||||
dupes = {k: v for k, v in rules.items() if len(v) > 1}
|
||||
if dupes:
|
||||
raise AssertionError(f"发现 {len(dupes)} 处路由冲突: {dupes}")
|
||||
return f"共 {len(rules)} 条 (method, path) 规则, 无重复注册"
|
||||
|
||||
|
||||
check("检查重复路由 (Flask 静默覆盖, 需显式检测)", route_conflicts)
|
||||
|
||||
|
||||
def route_summary():
|
||||
rules = sorted(r.rule for r in app_obj.url_map.iter_rules() if r.endpoint != "static")
|
||||
return f"{len(rules)} 条路由"
|
||||
|
||||
|
||||
check("路由注册成功", route_summary)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("3) 数据库连通性")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def db_check():
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
p = Path("users.db")
|
||||
if not p.exists():
|
||||
raise AssertionError("users.db 不存在")
|
||||
conn = sqlite3.connect(str(p))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
tables = [r[0] for r in cur.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
|
||||
counts = {}
|
||||
for t in ("users", "rentals", "bike_history", "sessions"):
|
||||
if t in tables:
|
||||
counts[t] = cur.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
|
||||
cur.execute("PRAGMA integrity_check")
|
||||
integrity = cur.fetchone()[0]
|
||||
conn.close()
|
||||
if integrity != "ok":
|
||||
raise AssertionError(f"数据库完整性异常: {integrity}")
|
||||
return f"表 {len(tables)} 张, 行数: {counts}"
|
||||
|
||||
|
||||
check("users.db 完整性与核心表", db_check)
|
||||
|
||||
|
||||
def db_init_check():
|
||||
"""init_db() 应可重复执行(幂等)而不报错 —— 用临时库验证。"""
|
||||
import db, tempfile, os
|
||||
from pathlib import Path
|
||||
fd, tmp = tempfile.mkstemp(suffix=".db")
|
||||
os.close(fd)
|
||||
old = db.DB_PATH
|
||||
db.DB_PATH = Path(tmp)
|
||||
try:
|
||||
db.init_db()
|
||||
db.init_db() # 二次调用验证幂等
|
||||
return "init_db 在临时库上执行两次均成功(幂等)"
|
||||
finally:
|
||||
db.DB_PATH = old
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
check("init_db 幂等性 (临时库)", db_init_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("4) 模板与静态资源")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def templates_check():
|
||||
from pathlib import Path
|
||||
tdir = Path("templates")
|
||||
files = sorted(p.name for p in tdir.glob("*.html"))
|
||||
if not files:
|
||||
raise AssertionError("templates 目录为空")
|
||||
return f"{len(files)} 个模板: {', '.join(files)}"
|
||||
|
||||
|
||||
check("模板文件存在", templates_check)
|
||||
|
||||
|
||||
def static_check():
|
||||
from pathlib import Path
|
||||
sdir = Path("static")
|
||||
total = sum(1 for _ in sdir.rglob("*") if _.is_file())
|
||||
if total == 0:
|
||||
raise AssertionError("static 目录为空")
|
||||
return f"{total} 个静态文件"
|
||||
|
||||
|
||||
check("静态资源存在", static_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("5) 关键接口冒烟 (Flask test client, 不真正监听端口)")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def client():
|
||||
app_obj.config["TESTING"] = True
|
||||
return app_obj.test_client()
|
||||
|
||||
|
||||
c = client()
|
||||
|
||||
EXPECTED = {
|
||||
# (path): 说明。允许 200/3xx;404 属于页面/路由缺失
|
||||
"/": "主页(地图)",
|
||||
"/admin": "管理后台(未登录应跳转登录)",
|
||||
"/admin/login": "管理员登录页",
|
||||
"/analysis.html": "数据分析页",
|
||||
"/rental/email-return": "邮件还车页",
|
||||
"/ring_progress.html": "寻车进度页",
|
||||
}
|
||||
|
||||
|
||||
def page(path):
|
||||
def fn():
|
||||
r = c.get(path)
|
||||
if r.status_code in (200, 301, 302, 304):
|
||||
return f"{path} -> {r.status_code}"
|
||||
if r.status_code == 404:
|
||||
raise AssertionError(f"{path} -> 404 (页面/路由缺失)")
|
||||
raise AssertionError(f"{path} -> {r.status_code}")
|
||||
return fn
|
||||
|
||||
|
||||
for path, name in EXPECTED.items():
|
||||
check(f"页面 {name} {path}", page(path))
|
||||
|
||||
# API 类: 401/400 = 接口在且鉴权/校验正常; 404/500 = 有问题
|
||||
API_ALLOW = {200, 400, 401, 302, 301}
|
||||
APIS = [
|
||||
("/api/bike_history", "无参数应返回400"),
|
||||
("/api/analysis/overview", "分析总览"),
|
||||
("/api/analysis/heatmap", "热力图"),
|
||||
("/api/history/stats", "历史统计"),
|
||||
("/api/history/bikes", "历史车辆列表"),
|
||||
("/api/history/heatmap", "历史热力图"),
|
||||
("/api/history/all_trajectory", "全量轨迹"),
|
||||
]
|
||||
|
||||
|
||||
def api(path):
|
||||
def fn():
|
||||
r = c.get(path)
|
||||
if r.status_code in API_ALLOW:
|
||||
return f"{path} -> {r.status_code}"
|
||||
raise AssertionError(f"{path} -> {r.status_code}")
|
||||
return fn
|
||||
|
||||
|
||||
for path, desc in APIS:
|
||||
check(f"API {desc} {path}", api(path))
|
||||
|
||||
|
||||
def protected_api_check():
|
||||
"""未登录访问受保护接口应返回 401(或明确拒绝) 而不是 500/404"""
|
||||
paths = (
|
||||
"/api/auth/rental_settings", "/api/rental/status",
|
||||
"/api/share/active", "/api/auth/profile", "/api/order/status",
|
||||
)
|
||||
for path in paths:
|
||||
r = c.get(path)
|
||||
if r.status_code == 404:
|
||||
raise AssertionError(f"{path} -> 404, 接口不存在")
|
||||
if r.status_code >= 500:
|
||||
raise AssertionError(f"{path} -> {r.status_code}, 服务端错误")
|
||||
if r.status_code == 200:
|
||||
body = r.get_json(silent=True) or {}
|
||||
if body.get("rtn_code") not in (401, 403):
|
||||
raise AssertionError(
|
||||
f"{path} 未登录返回 200 且 rtn_code={body.get('rtn_code')}, 疑似未鉴权")
|
||||
return "受保护接口未登录时均正确拒绝(无 500/404/越权)"
|
||||
|
||||
|
||||
check("受保护接口鉴权兜底", protected_api_check)
|
||||
|
||||
|
||||
def login_flow_check():
|
||||
"""登录接口对错误凭据应返回明确失败而非 500"""
|
||||
r = c.post("/api/auth/login",
|
||||
json={"email": "smoke_nonexist@example.test", "password": "wrong"})
|
||||
if r.status_code >= 500:
|
||||
raise AssertionError(f"/api/auth/login -> {r.status_code}")
|
||||
body = r.get_json(silent=True) or {}
|
||||
if r.status_code == 200 and body.get("rtn_code") == 0:
|
||||
raise AssertionError("错误凭据竟然登录成功!")
|
||||
return f"/api/auth/login 错误凭据 -> {r.status_code} rtn_code={body.get('rtn_code')} (拒绝正常)"
|
||||
|
||||
|
||||
check("登录接口错误凭据处理", login_flow_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("冒烟测试结果汇总")
|
||||
print("=" * 60)
|
||||
print(f"通过: {len(PASS)} 失败: {len(FAIL)}")
|
||||
if FAIL:
|
||||
print("\n失败项:")
|
||||
for name, err in FAIL:
|
||||
print(f" - {name}: {err}")
|
||||
sys.exit(1)
|
||||
print("全部通过 ✅")
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""冒烟测试:验证应用可启动、路由无冲突、关键接口可响应。"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根
|
||||
|
||||
# 注意: app.py 导入时会重新包装 sys.stdout, 这里不能自己再包一层,
|
||||
# 否则旧包装器被 GC 时会关闭底层 buffer。编码由 PYTHONIOENCODING 控制。
|
||||
_ORIG_STDOUT = sys.stdout # 持有引用, 防止被 GC 后关闭底层流
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
PASS, FAIL = [], []
|
||||
|
||||
|
||||
def check(name, fn):
|
||||
try:
|
||||
detail = fn()
|
||||
PASS.append((name, detail))
|
||||
print(f" [PASS] {name}" + (f" — {detail}" if detail else ""))
|
||||
except Exception as e:
|
||||
FAIL.append((name, f"{type(e).__name__}: {e}"))
|
||||
print(f" [FAIL] {name} — {type(e).__name__}: {e}")
|
||||
|
||||
|
||||
print("=" * 60)
|
||||
print("1) 模块导入检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def import_app():
|
||||
import app as app_module
|
||||
return f"app 模块导入成功, 蓝图 {len(app_module.app.blueprints)} 个: {', '.join(app_module.app.blueprints)}"
|
||||
|
||||
|
||||
check("导入 app.py 及全部依赖 (db/wechat/timer/routes.*)", import_app)
|
||||
|
||||
|
||||
def import_side_modules():
|
||||
import rental_mail, email_utils, generate_icons # noqa: F401
|
||||
return "rental_mail / email_utils / generate_icons 导入成功"
|
||||
|
||||
|
||||
check("导入其余业务模块", import_side_modules)
|
||||
|
||||
app_obj = None
|
||||
try:
|
||||
import app as app_module
|
||||
app_obj = app_module.app
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("2) 路由冲突检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def route_conflicts():
|
||||
rules = defaultdict(list)
|
||||
for r in app_obj.url_map.iter_rules():
|
||||
if r.endpoint == "static":
|
||||
continue
|
||||
methods = sorted(m for m in r.methods if m not in ("HEAD", "OPTIONS"))
|
||||
for m in methods:
|
||||
rules[(m, r.rule)].append(r.endpoint)
|
||||
dupes = {k: v for k, v in rules.items() if len(v) > 1}
|
||||
if dupes:
|
||||
raise AssertionError(f"发现 {len(dupes)} 处路由冲突: {dupes}")
|
||||
return f"共 {len(rules)} 条 (method, path) 规则, 无重复注册"
|
||||
|
||||
|
||||
check("检查重复路由 (Flask 静默覆盖, 需显式检测)", route_conflicts)
|
||||
|
||||
|
||||
def route_summary():
|
||||
rules = sorted(r.rule for r in app_obj.url_map.iter_rules() if r.endpoint != "static")
|
||||
return f"{len(rules)} 条路由"
|
||||
|
||||
|
||||
check("路由注册成功", route_summary)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("3) 数据库连通性")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def db_check():
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
p = Path("users.db")
|
||||
if not p.exists():
|
||||
raise AssertionError("users.db 不存在")
|
||||
conn = sqlite3.connect(str(p))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
tables = [r[0] for r in cur.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
|
||||
counts = {}
|
||||
for t in ("users", "rentals", "bike_history", "sessions"):
|
||||
if t in tables:
|
||||
counts[t] = cur.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
|
||||
cur.execute("PRAGMA integrity_check")
|
||||
integrity = cur.fetchone()[0]
|
||||
conn.close()
|
||||
if integrity != "ok":
|
||||
raise AssertionError(f"数据库完整性异常: {integrity}")
|
||||
return f"表 {len(tables)} 张, 行数: {counts}"
|
||||
|
||||
|
||||
check("users.db 完整性与核心表", db_check)
|
||||
|
||||
|
||||
def db_init_check():
|
||||
"""init_db() 应可重复执行(幂等)而不报错 —— 用临时库验证。"""
|
||||
import db, tempfile, os
|
||||
from pathlib import Path
|
||||
fd, tmp = tempfile.mkstemp(suffix=".db")
|
||||
os.close(fd)
|
||||
old = db.DB_PATH
|
||||
db.DB_PATH = Path(tmp)
|
||||
try:
|
||||
db.init_db()
|
||||
db.init_db() # 二次调用验证幂等
|
||||
return "init_db 在临时库上执行两次均成功(幂等)"
|
||||
finally:
|
||||
db.DB_PATH = old
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
check("init_db 幂等性 (临时库)", db_init_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("4) 模板与静态资源")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def templates_check():
|
||||
from pathlib import Path
|
||||
tdir = Path("templates")
|
||||
files = sorted(p.name for p in tdir.glob("*.html"))
|
||||
if not files:
|
||||
raise AssertionError("templates 目录为空")
|
||||
return f"{len(files)} 个模板: {', '.join(files)}"
|
||||
|
||||
|
||||
check("模板文件存在", templates_check)
|
||||
|
||||
|
||||
def static_check():
|
||||
from pathlib import Path
|
||||
sdir = Path("static")
|
||||
total = sum(1 for _ in sdir.rglob("*") if _.is_file())
|
||||
if total == 0:
|
||||
raise AssertionError("static 目录为空")
|
||||
return f"{total} 个静态文件"
|
||||
|
||||
|
||||
check("静态资源存在", static_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("5) 关键接口冒烟 (Flask test client, 不真正监听端口)")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def client():
|
||||
app_obj.config["TESTING"] = True
|
||||
return app_obj.test_client()
|
||||
|
||||
|
||||
c = client()
|
||||
|
||||
EXPECTED = {
|
||||
# (path): 说明。允许 200/3xx;404 属于页面/路由缺失
|
||||
"/": "主页(地图)",
|
||||
"/admin": "管理后台(未登录应跳转登录)",
|
||||
"/admin/login": "管理员登录页",
|
||||
"/analysis.html": "数据分析页",
|
||||
"/rental/email-return": "邮件还车页",
|
||||
"/ring_progress.html": "寻车进度页",
|
||||
}
|
||||
|
||||
|
||||
def page(path):
|
||||
def fn():
|
||||
r = c.get(path)
|
||||
if r.status_code in (200, 301, 302, 304):
|
||||
return f"{path} -> {r.status_code}"
|
||||
if r.status_code == 404:
|
||||
raise AssertionError(f"{path} -> 404 (页面/路由缺失)")
|
||||
raise AssertionError(f"{path} -> {r.status_code}")
|
||||
return fn
|
||||
|
||||
|
||||
for path, name in EXPECTED.items():
|
||||
check(f"页面 {name} {path}", page(path))
|
||||
|
||||
# API 类: 401/400 = 接口在且鉴权/校验正常; 404/500 = 有问题
|
||||
API_ALLOW = {200, 400, 401, 302, 301}
|
||||
APIS = [
|
||||
("/api/bike_history", "无参数应返回400"),
|
||||
("/api/analysis/overview", "分析总览"),
|
||||
("/api/analysis/heatmap", "热力图"),
|
||||
("/api/history/stats", "历史统计"),
|
||||
("/api/history/bikes", "历史车辆列表"),
|
||||
("/api/history/heatmap", "历史热力图"),
|
||||
("/api/history/all_trajectory", "全量轨迹"),
|
||||
]
|
||||
|
||||
|
||||
def api(path):
|
||||
def fn():
|
||||
r = c.get(path)
|
||||
if r.status_code in API_ALLOW:
|
||||
return f"{path} -> {r.status_code}"
|
||||
raise AssertionError(f"{path} -> {r.status_code}")
|
||||
return fn
|
||||
|
||||
|
||||
for path, desc in APIS:
|
||||
check(f"API {desc} {path}", api(path))
|
||||
|
||||
|
||||
def protected_api_check():
|
||||
"""未登录访问受保护接口应返回 401(或明确拒绝) 而不是 500/404"""
|
||||
paths = (
|
||||
"/api/auth/rental_settings", "/api/rental/status",
|
||||
"/api/share/active", "/api/auth/profile", "/api/order/status",
|
||||
)
|
||||
for path in paths:
|
||||
r = c.get(path)
|
||||
if r.status_code == 404:
|
||||
raise AssertionError(f"{path} -> 404, 接口不存在")
|
||||
if r.status_code >= 500:
|
||||
raise AssertionError(f"{path} -> {r.status_code}, 服务端错误")
|
||||
if r.status_code == 200:
|
||||
body = r.get_json(silent=True) or {}
|
||||
if body.get("rtn_code") not in (401, 403):
|
||||
raise AssertionError(
|
||||
f"{path} 未登录返回 200 且 rtn_code={body.get('rtn_code')}, 疑似未鉴权")
|
||||
return "受保护接口未登录时均正确拒绝(无 500/404/越权)"
|
||||
|
||||
|
||||
check("受保护接口鉴权兜底", protected_api_check)
|
||||
|
||||
|
||||
def login_flow_check():
|
||||
"""登录接口对错误凭据应返回明确失败而非 500"""
|
||||
r = c.post("/api/auth/login",
|
||||
json={"email": "smoke_nonexist@example.test", "password": "wrong"})
|
||||
if r.status_code >= 500:
|
||||
raise AssertionError(f"/api/auth/login -> {r.status_code}")
|
||||
body = r.get_json(silent=True) or {}
|
||||
if r.status_code == 200 and body.get("rtn_code") == 0:
|
||||
raise AssertionError("错误凭据竟然登录成功!")
|
||||
return f"/api/auth/login 错误凭据 -> {r.status_code} rtn_code={body.get('rtn_code')} (拒绝正常)"
|
||||
|
||||
|
||||
check("登录接口错误凭据处理", login_flow_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("冒烟测试结果汇总")
|
||||
print("=" * 60)
|
||||
print(f"通过: {len(PASS)} 失败: {len(FAIL)}")
|
||||
if FAIL:
|
||||
print("\n失败项:")
|
||||
for name, err in FAIL:
|
||||
print(f" - {name}: {err}")
|
||||
sys.exit(1)
|
||||
print("全部通过 ✅")
|
||||
|
||||
+2706
-2706
File diff suppressed because it is too large
Load Diff
+5347
-5347
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -12,7 +12,7 @@
|
||||
- 判定用最近 20 分钟内的采集点(每车取最新一条),坐标系与车辆一致(GCJ02)。
|
||||
"""
|
||||
import datetime as dt
|
||||
import math
|
||||
import math
|
||||
import sqlite3
|
||||
import random
|
||||
import threading
|
||||
|
||||
+928
-928
File diff suppressed because it is too large
Load Diff
+1473
-1473
File diff suppressed because it is too large
Load Diff
+1003
-1003
File diff suppressed because it is too large
Load Diff
+259
-259
@@ -1,263 +1,263 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>全车寻铃进度</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: #1a1a2e;
|
||||
color: #eee;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
.container {
|
||||
background: #16213e;
|
||||
border-radius: 16px;
|
||||
padding: 32px;
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
|
||||
}
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
.header h1 {
|
||||
font-size: 22px;
|
||||
margin-bottom: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.header p {
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 12px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.stat {
|
||||
background: #0f3460;
|
||||
border-radius: 12px;
|
||||
padding: 16px 12px;
|
||||
text-align: center;
|
||||
}
|
||||
.stat-value {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
color: #e94560;
|
||||
}
|
||||
.stat-value.success { color: #4ade80; }
|
||||
.stat-value.failed { color: #f87171; }
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.progress-bar {
|
||||
background: #0f3460;
|
||||
border-radius: 10px;
|
||||
height: 20px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #e94560, #ff6b6b);
|
||||
border-radius: 10px;
|
||||
transition: width 0.2s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding-right: 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
min-width: 40px;
|
||||
}
|
||||
.progress-fill.done { background: linear-gradient(90deg, #4ade80, #22c55e); }
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
.btn {
|
||||
flex: 1;
|
||||
padding: 14px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-cancel {
|
||||
background: #e94560;
|
||||
color: white;
|
||||
}
|
||||
.btn-cancel:hover { background: #d63850; }
|
||||
.btn-close {
|
||||
background: #333;
|
||||
color: #ccc;
|
||||
}
|
||||
.btn-close:hover { background: #444; }
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.log {
|
||||
margin-top: 20px;
|
||||
background: #0a0a1a;
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
max-height: 120px;
|
||||
overflow-y: auto;
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
}
|
||||
.log-entry { margin-bottom: 4px; }
|
||||
.log-entry.success { color: #4ade80; }
|
||||
.log-entry.failed { color: #f87171; }
|
||||
</style>
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>全车寻铃进度</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: #1a1a2e;
|
||||
color: #eee;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
.container {
|
||||
background: #16213e;
|
||||
border-radius: 16px;
|
||||
padding: 32px;
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
|
||||
}
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
.header h1 {
|
||||
font-size: 22px;
|
||||
margin-bottom: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.header p {
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 12px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.stat {
|
||||
background: #0f3460;
|
||||
border-radius: 12px;
|
||||
padding: 16px 12px;
|
||||
text-align: center;
|
||||
}
|
||||
.stat-value {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
color: #e94560;
|
||||
}
|
||||
.stat-value.success { color: #4ade80; }
|
||||
.stat-value.failed { color: #f87171; }
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.progress-bar {
|
||||
background: #0f3460;
|
||||
border-radius: 10px;
|
||||
height: 20px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #e94560, #ff6b6b);
|
||||
border-radius: 10px;
|
||||
transition: width 0.2s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding-right: 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
min-width: 40px;
|
||||
}
|
||||
.progress-fill.done { background: linear-gradient(90deg, #4ade80, #22c55e); }
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
.btn {
|
||||
flex: 1;
|
||||
padding: 14px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-cancel {
|
||||
background: #e94560;
|
||||
color: white;
|
||||
}
|
||||
.btn-cancel:hover { background: #d63850; }
|
||||
.btn-close {
|
||||
background: #333;
|
||||
color: #ccc;
|
||||
}
|
||||
.btn-close:hover { background: #444; }
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.log {
|
||||
margin-top: 20px;
|
||||
background: #0a0a1a;
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
max-height: 120px;
|
||||
overflow-y: auto;
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
}
|
||||
.log-entry { margin-bottom: 4px; }
|
||||
.log-entry.success { color: #4ade80; }
|
||||
.log-entry.failed { color: #f87171; }
|
||||
</style>
|
||||
<link rel="stylesheet" href="/static/css/ui-system.css">
|
||||
<script defer src="/static/js/ui-motion.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>
|
||||
<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
全车寻铃
|
||||
</h1>
|
||||
<p id="status-text">正在连接...</p>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat">
|
||||
<div class="stat-value" id="done-count">0</div>
|
||||
<div class="stat-label">已完成</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value success" id="success-count">0</div>
|
||||
<div class="stat-label">成功</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value failed" id="failed-count">0</div>
|
||||
<div class="stat-label">失败</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill" id="progress-fill" style="width: 0%">
|
||||
<span id="progress-text">0%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn btn-cancel" id="cancel-btn" onclick="cancelTask()">取消任务</button>
|
||||
<button class="btn btn-close" onclick="closeWindow()">关闭</button>
|
||||
</div>
|
||||
|
||||
<div class="log" id="log"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const taskId = params.get('task_id');
|
||||
const total = parseInt(params.get('total') || '0');
|
||||
|
||||
document.getElementById('status-text').textContent = `共 ${total} 辆车`;
|
||||
|
||||
let cancelled = false;
|
||||
let completed = false;
|
||||
|
||||
function addLog(msg, type = '') {
|
||||
const log = document.getElementById('log');
|
||||
const entry = document.createElement('div');
|
||||
entry.className = 'log-entry ' + type;
|
||||
entry.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
|
||||
log.appendChild(entry);
|
||||
log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function updateUI(data) {
|
||||
const { status, done, total, success, failed } = data;
|
||||
|
||||
document.getElementById('done-count').textContent = done;
|
||||
document.getElementById('success-count').textContent = success;
|
||||
document.getElementById('failed-count').textContent = failed;
|
||||
|
||||
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
|
||||
const fill = document.getElementById('progress-fill');
|
||||
fill.style.width = pct + '%';
|
||||
document.getElementById('progress-text').textContent = pct + '%';
|
||||
|
||||
if (pct >= 100 || status === 'completed' || status === 'cancelled') {
|
||||
fill.classList.add('done');
|
||||
document.getElementById('cancel-btn').disabled = true;
|
||||
completed = true;
|
||||
}
|
||||
|
||||
if (status === 'cancelled') {
|
||||
document.getElementById('status-text').textContent = '❌ 已取消';
|
||||
addLog('任务已取消', '');
|
||||
} else if (status === 'completed') {
|
||||
document.getElementById('status-text').textContent = '✅ 全部完成';
|
||||
addLog(`完成!成功:${success} 失败:${failed}`, '');
|
||||
}
|
||||
}
|
||||
|
||||
function cancelTask() {
|
||||
if (cancelled || completed) return;
|
||||
cancelled = true;
|
||||
document.getElementById('cancel-btn').disabled = true;
|
||||
document.getElementById('cancel-btn').textContent = '取消中...';
|
||||
fetch(`/api/ring_cancel/${taskId}`, { method: 'POST' })
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
addLog(d.message || '取消请求已发送', '');
|
||||
})
|
||||
.catch(() => addLog('取消请求失败', 'failed'));
|
||||
}
|
||||
|
||||
function closeWindow() {
|
||||
if (!completed && !cancelled) {
|
||||
if (!confirm('任务还在运行,确定要关闭吗?')) return;
|
||||
}
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>
|
||||
<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
全车寻铃
|
||||
</h1>
|
||||
<p id="status-text">正在连接...</p>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat">
|
||||
<div class="stat-value" id="done-count">0</div>
|
||||
<div class="stat-label">已完成</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value success" id="success-count">0</div>
|
||||
<div class="stat-label">成功</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value failed" id="failed-count">0</div>
|
||||
<div class="stat-label">失败</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill" id="progress-fill" style="width: 0%">
|
||||
<span id="progress-text">0%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn btn-cancel" id="cancel-btn" onclick="cancelTask()">取消任务</button>
|
||||
<button class="btn btn-close" onclick="closeWindow()">关闭</button>
|
||||
</div>
|
||||
|
||||
<div class="log" id="log"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const taskId = params.get('task_id');
|
||||
const total = parseInt(params.get('total') || '0');
|
||||
|
||||
document.getElementById('status-text').textContent = `共 ${total} 辆车`;
|
||||
|
||||
let cancelled = false;
|
||||
let completed = false;
|
||||
|
||||
function addLog(msg, type = '') {
|
||||
const log = document.getElementById('log');
|
||||
const entry = document.createElement('div');
|
||||
entry.className = 'log-entry ' + type;
|
||||
entry.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
|
||||
log.appendChild(entry);
|
||||
log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function updateUI(data) {
|
||||
const { status, done, total, success, failed } = data;
|
||||
|
||||
document.getElementById('done-count').textContent = done;
|
||||
document.getElementById('success-count').textContent = success;
|
||||
document.getElementById('failed-count').textContent = failed;
|
||||
|
||||
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
|
||||
const fill = document.getElementById('progress-fill');
|
||||
fill.style.width = pct + '%';
|
||||
document.getElementById('progress-text').textContent = pct + '%';
|
||||
|
||||
if (pct >= 100 || status === 'completed' || status === 'cancelled') {
|
||||
fill.classList.add('done');
|
||||
document.getElementById('cancel-btn').disabled = true;
|
||||
completed = true;
|
||||
}
|
||||
|
||||
if (status === 'cancelled') {
|
||||
document.getElementById('status-text').textContent = '❌ 已取消';
|
||||
addLog('任务已取消', '');
|
||||
} else if (status === 'completed') {
|
||||
document.getElementById('status-text').textContent = '✅ 全部完成';
|
||||
addLog(`完成!成功:${success} 失败:${failed}`, '');
|
||||
}
|
||||
}
|
||||
|
||||
function cancelTask() {
|
||||
if (cancelled || completed) return;
|
||||
cancelled = true;
|
||||
document.getElementById('cancel-btn').disabled = true;
|
||||
document.getElementById('cancel-btn').textContent = '取消中...';
|
||||
fetch(`/api/ring_cancel/${taskId}`, { method: 'POST' })
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
addLog(d.message || '取消请求已发送', '');
|
||||
})
|
||||
.catch(() => addLog('取消请求失败', 'failed'));
|
||||
}
|
||||
|
||||
function closeWindow() {
|
||||
if (!completed && !cancelled) {
|
||||
if (!confirm('任务还在运行,确定要关闭吗?')) return;
|
||||
}
|
||||
uiCloseWindow();
|
||||
}
|
||||
|
||||
// SSE 连接
|
||||
const es = new EventSource(`/api/ring_progress/${taskId}`);
|
||||
|
||||
es.onmessage = (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data);
|
||||
if (data.type === 'progress') {
|
||||
updateUI(data);
|
||||
} else if (data.type === 'done') {
|
||||
es.close();
|
||||
} else if (data.type === 'error') {
|
||||
addLog(data.message, 'failed');
|
||||
es.close();
|
||||
}
|
||||
} catch (err) {}
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
addLog('连接断开', 'failed');
|
||||
es.close();
|
||||
};
|
||||
|
||||
addLog('开始监听进度...', '');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
|
||||
// SSE 连接
|
||||
const es = new EventSource(`/api/ring_progress/${taskId}`);
|
||||
|
||||
es.onmessage = (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data);
|
||||
if (data.type === 'progress') {
|
||||
updateUI(data);
|
||||
} else if (data.type === 'done') {
|
||||
es.close();
|
||||
} else if (data.type === 'error') {
|
||||
addLog(data.message, 'failed');
|
||||
es.close();
|
||||
}
|
||||
} catch (err) {}
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
addLog('连接断开', 'failed');
|
||||
es.close();
|
||||
};
|
||||
|
||||
addLog('开始监听进度...', '');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+34
-34
@@ -1,34 +1,34 @@
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
# 测试各接口
|
||||
tests = [
|
||||
('/record/order', {'code': '51287', 'start_longitude': 116.98, 'start_latitude': 36.67}),
|
||||
('/record/checkLocation', {'longitude': 116.98, 'latitude': 36.67, 'bicycleCode': '51287'}),
|
||||
('/record/return', {'order_id': 15899504, 'longitude': 116.98, 'latitude': 36.67}),
|
||||
]
|
||||
|
||||
for path, body in tests:
|
||||
resp = requests.post(f'https://bike.sdlongren.com{path}', headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(path)
|
||||
print(' rtn_code:', data.get('rtn_code'))
|
||||
print(' code:', data.get('code'))
|
||||
print(' message:', data.get('message'))
|
||||
print(' data:', str(data.get('data'))[:200])
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
# 测试各接口
|
||||
tests = [
|
||||
('/record/order', {'code': '51287', 'start_longitude': 116.98, 'start_latitude': 36.67}),
|
||||
('/record/checkLocation', {'longitude': 116.98, 'latitude': 36.67, 'bicycleCode': '51287'}),
|
||||
('/record/return', {'order_id': 15899504, 'longitude': 116.98, 'latitude': 36.67}),
|
||||
]
|
||||
|
||||
for path, body in tests:
|
||||
resp = requests.post(f'https://bike.sdlongren.com{path}', headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(path)
|
||||
print(' rtn_code:', data.get('rtn_code'))
|
||||
print(' code:', data.get('code'))
|
||||
print(' message:', data.get('message'))
|
||||
print(' data:', str(data.get('data'))[:200])
|
||||
|
||||
+46
-46
@@ -1,46 +1,46 @@
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
tests = [
|
||||
# GET /user/packages - 我的卡包列表
|
||||
('GET', '/user/packages', None),
|
||||
# GET /packages/mapp - 推荐卡包列表
|
||||
('GET', '/packages/mapp', None),
|
||||
# GET /bus_packages/user_packages - 我的公交卡包
|
||||
('GET', '/bus_packages/user_packages', None),
|
||||
]
|
||||
|
||||
for method, path, body in tests:
|
||||
url = f'https://bike.sdlongren.com{path}'
|
||||
if method == 'GET':
|
||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||
else:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(f'=== {method} {path} ===')
|
||||
print(' rtn_code:', data.get('rtn_code'), 'code:', data.get('code'))
|
||||
print(' message:', data.get('message'))
|
||||
if data.get('data'):
|
||||
print(' data keys:', list(data.get('data', {}).keys()))
|
||||
d = data['data']
|
||||
# 打印卡包信息
|
||||
for k in ['bike_packages', 'packageList', 'package', 'packages', 'memberPackageCount', 'memberPackage']:
|
||||
if k in d:
|
||||
print(f' {k}:', str(d[k])[:300])
|
||||
print()
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
tests = [
|
||||
# GET /user/packages - 我的卡包列表
|
||||
('GET', '/user/packages', None),
|
||||
# GET /packages/mapp - 推荐卡包列表
|
||||
('GET', '/packages/mapp', None),
|
||||
# GET /bus_packages/user_packages - 我的公交卡包
|
||||
('GET', '/bus_packages/user_packages', None),
|
||||
]
|
||||
|
||||
for method, path, body in tests:
|
||||
url = f'https://bike.sdlongren.com{path}'
|
||||
if method == 'GET':
|
||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||
else:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(f'=== {method} {path} ===')
|
||||
print(' rtn_code:', data.get('rtn_code'), 'code:', data.get('code'))
|
||||
print(' message:', data.get('message'))
|
||||
if data.get('data'):
|
||||
print(' data keys:', list(data.get('data', {}).keys()))
|
||||
d = data['data']
|
||||
# 打印卡包信息
|
||||
for k in ['bike_packages', 'packageList', 'package', 'packages', 'memberPackageCount', 'memberPackage']:
|
||||
if k in d:
|
||||
print(f' {k}:', str(d[k])[:300])
|
||||
print()
|
||||
|
||||
+45
-45
@@ -1,45 +1,45 @@
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
tests = [
|
||||
# GET /user/packages - 从JS逆向得到的"我的卡包"
|
||||
('GET', '/user/packages', None),
|
||||
# 看看/user/info 里的 package 和 memberPackageCount
|
||||
('GET', '/user/info', None),
|
||||
# 可能的变体路径
|
||||
('GET', '/user/package', None),
|
||||
('GET', '/user/memberPackage', None),
|
||||
('GET', '/user/myPackage', None),
|
||||
('GET', '/packages/user', None),
|
||||
('GET', '/packages/my', None),
|
||||
]
|
||||
|
||||
for method, path, body in tests:
|
||||
url = f'https://bike.sdlongren.com{path}'
|
||||
if method == 'GET':
|
||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||
else:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(f'=== {method} {path} === rtn_code={data.get("rtn_code")} code={data.get("code")}')
|
||||
if data.get('rtn_code') == 0 and data.get('data'):
|
||||
for k, v in data['data'].items():
|
||||
if 'package' in k.lower() or 'card' in k.lower() or 'member' in k.lower() or 'count' in k.lower():
|
||||
print(f' {k}: {str(v)[:200]}')
|
||||
print()
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
tests = [
|
||||
# GET /user/packages - 从JS逆向得到的"我的卡包"
|
||||
('GET', '/user/packages', None),
|
||||
# 看看/user/info 里的 package 和 memberPackageCount
|
||||
('GET', '/user/info', None),
|
||||
# 可能的变体路径
|
||||
('GET', '/user/package', None),
|
||||
('GET', '/user/memberPackage', None),
|
||||
('GET', '/user/myPackage', None),
|
||||
('GET', '/packages/user', None),
|
||||
('GET', '/packages/my', None),
|
||||
]
|
||||
|
||||
for method, path, body in tests:
|
||||
url = f'https://bike.sdlongren.com{path}'
|
||||
if method == 'GET':
|
||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||
else:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(f'=== {method} {path} === rtn_code={data.get("rtn_code")} code={data.get("code")}')
|
||||
if data.get('rtn_code') == 0 and data.get('data'):
|
||||
for k, v in data['data'].items():
|
||||
if 'package' in k.lower() or 'card' in k.lower() or 'member' in k.lower() or 'count' in k.lower():
|
||||
print(f' {k}: {str(v)[:200]}')
|
||||
print()
|
||||
|
||||
+41
-41
@@ -1,41 +1,41 @@
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
# 获取推荐卡包的完整字段
|
||||
resp = requests.get('https://bike.sdlongren.com/packages/mapp', headers=headers, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print('=== 推荐卡包完整字段 ===')
|
||||
if data.get('rtn_code') == 0 and data.get('data', {}).get('bike_packages'):
|
||||
pkg = data['data']['bike_packages'][0]
|
||||
print(json.dumps(pkg, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
print('所有字段:', list(pkg.keys()))
|
||||
|
||||
# /user/info 里的 package 字段完整内容
|
||||
resp2 = requests.get('https://bike.sdlongren.com/user/info', headers=headers, timeout=10, verify=False)
|
||||
data2 = resp2.json()
|
||||
print('=== user/info 中的 package 字段 ===')
|
||||
pkg_data = data2.get('data', {}).get('package', {})
|
||||
print(json.dumps(pkg_data, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
print('package 所有字段:', list(pkg_data.keys()))
|
||||
|
||||
# memberPackageCount
|
||||
print('memberPackageCount:', data2['data'].get('memberPackageCount'))
|
||||
print('spec_count:', data2['data'].get('spec_count'))
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
# 获取推荐卡包的完整字段
|
||||
resp = requests.get('https://bike.sdlongren.com/packages/mapp', headers=headers, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print('=== 推荐卡包完整字段 ===')
|
||||
if data.get('rtn_code') == 0 and data.get('data', {}).get('bike_packages'):
|
||||
pkg = data['data']['bike_packages'][0]
|
||||
print(json.dumps(pkg, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
print('所有字段:', list(pkg.keys()))
|
||||
|
||||
# /user/info 里的 package 字段完整内容
|
||||
resp2 = requests.get('https://bike.sdlongren.com/user/info', headers=headers, timeout=10, verify=False)
|
||||
data2 = resp2.json()
|
||||
print('=== user/info 中的 package 字段 ===')
|
||||
pkg_data = data2.get('data', {}).get('package', {})
|
||||
print(json.dumps(pkg_data, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
print('package 所有字段:', list(pkg_data.keys()))
|
||||
|
||||
# memberPackageCount
|
||||
print('memberPackageCount:', data2['data'].get('memberPackageCount'))
|
||||
print('spec_count:', data2['data'].get('spec_count'))
|
||||
|
||||
+43
-43
@@ -1,43 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""测试API坐标"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
import hashlib
|
||||
import urllib3
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
HEADERS = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-tokenid': '1291378',
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
ts = str(int(time.time()))
|
||||
raw = f"1291378GET/project/map{ts}"
|
||||
sig = hashlib.sha256(raw.encode()).hexdigest()[:40]
|
||||
HEADERS['hsf-x-timestamp'] = ts
|
||||
HEADERS['hsf-x-signature'] = sig
|
||||
|
||||
resp = requests.get('https://bike.sdlongren.com/project/map?type=3', headers=HEADERS, verify=False)
|
||||
data = resp.json()
|
||||
|
||||
# 打印返回的学校中心坐标和前3辆车的坐标
|
||||
if data.get('rtn_code') == 0 and data.get('data'):
|
||||
d = data['data']
|
||||
print('=== 学校中心坐标 ===')
|
||||
print(f'centerLatitude: {d.get("centerLatitude")}')
|
||||
print(f'centerLongitude: {d.get("centerLongitude")}')
|
||||
print()
|
||||
print('=== 前3辆车坐标 ===')
|
||||
for i, bike in enumerate(d.get('bicycleStation', [])[:3]):
|
||||
print(f'{i+1}. code={bike.get("code")}, lat={bike.get("latitude")}, lng={bike.get("longitude")}')
|
||||
else:
|
||||
print('请求失败:', data)
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""测试API坐标"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
import hashlib
|
||||
import urllib3
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
HEADERS = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-tokenid': '1291378',
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
ts = str(int(time.time()))
|
||||
raw = f"1291378GET/project/map{ts}"
|
||||
sig = hashlib.sha256(raw.encode()).hexdigest()[:40]
|
||||
HEADERS['hsf-x-timestamp'] = ts
|
||||
HEADERS['hsf-x-signature'] = sig
|
||||
|
||||
resp = requests.get('https://bike.sdlongren.com/project/map?type=3', headers=HEADERS, verify=False)
|
||||
data = resp.json()
|
||||
|
||||
# 打印返回的学校中心坐标和前3辆车的坐标
|
||||
if data.get('rtn_code') == 0 and data.get('data'):
|
||||
d = data['data']
|
||||
print('=== 学校中心坐标 ===')
|
||||
print(f'centerLatitude: {d.get("centerLatitude")}')
|
||||
print(f'centerLongitude: {d.get("centerLongitude")}')
|
||||
print()
|
||||
print('=== 前3辆车坐标 ===')
|
||||
for i, bike in enumerate(d.get('bicycleStation', [])[:3]):
|
||||
print(f'{i+1}. code={bike.get("code")}, lat={bike.get("latitude")}, lng={bike.get("longitude")}')
|
||||
else:
|
||||
print('请求失败:', data)
|
||||
|
||||
@@ -1,442 +1,442 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""微信API通信模块
|
||||
|
||||
凭据模型(对照 98/ 反编译小程序与实机抓包还原):
|
||||
- token_id:登录后服务端下发的会话标识(单会话:小程序重新登录即失效)。
|
||||
上游目前唯一强校验的头,必填。
|
||||
- access_token:登录响应里的 JWT(30 天有效)。小程序用它在本地实时计算签名:
|
||||
hsf-x-signature = sha1(access_token + base64(签名串))。选填。
|
||||
|
||||
签名策略(双模式 + 强验证开关):
|
||||
- 常规模式:有真实 access_token 就实时计算签名;否则生成形似合法的
|
||||
sha1 伪装签名(40 位 hex、随请求变化,防上游日志识别出固定异常值)。
|
||||
- 强验证模式(管理端开关,server_config.json 持久化):模拟上游开启
|
||||
签名校验后的行为——没有真实 access_token 的凭据直接拒绝发起请求,
|
||||
提前给出明确错误,而不是发出必然失败的请求。
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import requests
|
||||
import gzip
|
||||
from pathlib import Path
|
||||
|
||||
# 旧占位签名值(仅用于识别"未配置 accessToken"的存量配置,不再对外发送)
|
||||
_DUMMY_SIGNATURE = "xiaobai"
|
||||
|
||||
|
||||
def fake_signature(timestamp: str, token_id: str) -> str:
|
||||
"""未配置 accessToken 时生成形似合法的签名:40 位小写 hex(sha1 输出格式),
|
||||
且随时间戳/凭据变化,与真实流量的日志特征一致,避免上游从日志中识别出异常固定值。"""
|
||||
return hashlib.sha1(f"{timestamp}{token_id}".encode("utf-8")).hexdigest()
|
||||
|
||||
BASE_URL = "https://bike.sdlongren.com"
|
||||
|
||||
# 强验证开关的持久化文件
|
||||
_SERVER_CONFIG_PATH = Path(__file__).parent / "server_config.json"
|
||||
|
||||
# 从配置文件加载全局凭据
|
||||
_TOKEN_CONFIG_PATH = Path(__file__).parent / "token_config.txt"
|
||||
|
||||
|
||||
# ========== 强验证开关 ==========
|
||||
def _load_server_config() -> dict:
|
||||
try:
|
||||
if _SERVER_CONFIG_PATH.exists():
|
||||
return json.loads(_SERVER_CONFIG_PATH.read_text("utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def is_strict_mode() -> bool:
|
||||
"""上游强签名验证开关:开启后无真实 accessToken 的凭据将被拒绝发起请求"""
|
||||
return bool(_load_server_config().get("require_access_token"))
|
||||
|
||||
|
||||
def set_strict_mode(enabled: bool) -> bool:
|
||||
try:
|
||||
cfg = _load_server_config()
|
||||
cfg["require_access_token"] = bool(enabled)
|
||||
_SERVER_CONFIG_PATH.write_text(json.dumps(cfg, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[强验证开关] 保存失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def has_real_access_token(access_token) -> bool:
|
||||
"""是否为可用于计算签名的真实 accessToken(排除空值与占位符)"""
|
||||
return bool(access_token) and access_token != _DUMMY_SIGNATURE
|
||||
|
||||
|
||||
def parse_access_token_expiry(access_token) -> dict:
|
||||
"""从 accessToken(JWT)解析登录态有效期。
|
||||
|
||||
小程序登录响应中的 accessToken 是 RS256 JWT,payload 里带标准
|
||||
iat / nbf / exp(实测有效期 30 天)。只解码不验签——我们只需要
|
||||
展示大致过期时间,签名校验由上游负责。
|
||||
返回:{"parseable": bool, "expire_at": ts|None, "expire_time": "YYYY-MM-DD HH:MM"|None,
|
||||
"remaining_seconds": int|None, "source": "exp"|"iat+30d"|None, "reason": str}
|
||||
"""
|
||||
import base64 as _b64
|
||||
import datetime as _dt
|
||||
import json as _json
|
||||
|
||||
token = (access_token or "").strip()
|
||||
tz = _dt.timezone(_dt.timedelta(hours=8))
|
||||
result = {"parseable": False, "expire_at": None, "expire_time": None,
|
||||
"remaining_seconds": None, "source": None, "reason": ""}
|
||||
|
||||
def _fmt(ts: int) -> str:
|
||||
return _dt.datetime.fromtimestamp(ts, tz).strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
if not has_real_access_token(token):
|
||||
result["reason"] = "未填写 AccessToken"
|
||||
return result
|
||||
parts = token.split(".")
|
||||
if len(parts) != 3 or not token.startswith("ey"):
|
||||
result["reason"] = "不是标准 JWT 格式,无法解析过期时间"
|
||||
return result
|
||||
try:
|
||||
pad = parts[1] + "=" * (-len(parts[1]) % 4)
|
||||
payload = _json.loads(_b64.urlsafe_b64decode(pad))
|
||||
except Exception:
|
||||
result["reason"] = "JWT payload 解码失败"
|
||||
return result
|
||||
|
||||
exp = payload.get("exp") if isinstance(payload, dict) else None
|
||||
iat = payload.get("iat") if isinstance(payload, dict) else None
|
||||
try:
|
||||
exp = int(exp) if exp is not None else None
|
||||
iat = int(iat) if iat is not None else None
|
||||
except (TypeError, ValueError):
|
||||
exp = iat = None
|
||||
|
||||
if exp:
|
||||
result.update(parseable=True, expire_at=exp, expire_time=_fmt(exp),
|
||||
source="exp")
|
||||
elif iat:
|
||||
expire = iat + 30 * 86400 # 实测 accessToken 有效期 30 天
|
||||
result.update(parseable=True, expire_at=expire, expire_time=_fmt(expire),
|
||||
source="iat+30d")
|
||||
else:
|
||||
result["reason"] = "JWT 中没有 exp/iat 字段,无法推算有效期"
|
||||
return result
|
||||
|
||||
result["remaining_seconds"] = int(result["expire_at"] - _dt.datetime.now(tz).timestamp())
|
||||
return result
|
||||
|
||||
|
||||
def _strict_reject() -> dict:
|
||||
return {"rtn_code": 403,
|
||||
"message": "已开启上游强签名验证:请先填写 AccessToken(从微信小程序登录响应中获取)"}
|
||||
|
||||
|
||||
def _load_token_config():
|
||||
"""从 token_config.txt 加载全局凭据。
|
||||
|
||||
token_id:必填(重新登录小程序会失效,单会话策略)。
|
||||
access_token(旧键名 wx_signature 兼容读取):选填,用于实时计算签名。
|
||||
"""
|
||||
config = {"token_id": "", "access_token": ""}
|
||||
try:
|
||||
if _TOKEN_CONFIG_PATH.exists():
|
||||
for line in _TOKEN_CONFIG_PATH.read_text("utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
k, v = line.split("=", 1)
|
||||
k = k.strip()
|
||||
if k == "wx_signature": # 旧配置键名兼容
|
||||
k = "access_token"
|
||||
config[k] = v.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return config
|
||||
|
||||
|
||||
_TOKEN_CONFIG = _load_token_config()
|
||||
_GLOBAL_TOKEN_ID = _TOKEN_CONFIG.get("token_id", "")
|
||||
_GLOBAL_ACCESS_TOKEN = _TOKEN_CONFIG.get("access_token", "")
|
||||
|
||||
# 全局凭据只来自 token_config.txt / 管理后台保存,代码中不硬编码
|
||||
if not _GLOBAL_TOKEN_ID:
|
||||
print("[全局凭据] 警告: token_config.txt 中未配置 token_id,"
|
||||
"地图采集等全局请求将无法通过上游校验,请在管理后台填写")
|
||||
|
||||
HEADERS = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"hsf-x-signature": "",
|
||||
"hsf-x-timestamp": "",
|
||||
"hsf-x-tokenid": _GLOBAL_TOKEN_ID,
|
||||
"xweb_xhr": "1",
|
||||
"platform": "xiaobai",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 MicroMessenger/7.0",
|
||||
"content-type": "application/json",
|
||||
"accept": "*/*",
|
||||
"accept-language": "*",
|
||||
"sec-fetch-site": "cross-site",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-dest": "empty",
|
||||
"referer": "https://servicewechat.com/wx10426ca961518f43/108/page-frame.html",
|
||||
}
|
||||
|
||||
SEARCH_BIKE_URL = "https://bike.sdlongren.com/project/search_bicycle"
|
||||
SEARCH_HEADERS = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "*/*",
|
||||
}
|
||||
|
||||
|
||||
def build_sign_string(method: str, path: str, timestamp: str, token_id: str,
|
||||
params: dict = None) -> str:
|
||||
"""还原小程序 c(method, path, ts, params, needToken) 的签名串"""
|
||||
s = f"{method.upper()}$Hsf-X-Timestamp:{timestamp}Hsf-X-TokenId:{token_id}${path}"
|
||||
if params:
|
||||
s += "?"
|
||||
for k in sorted(params.keys()):
|
||||
v = params[k]
|
||||
# 与小程序一致:空字符串值只拼 key,嵌套对象/数组跳过
|
||||
if not k or (isinstance(v, str) and v == ""):
|
||||
s += f"{k}&"
|
||||
elif isinstance(v, (dict, list)):
|
||||
continue
|
||||
else:
|
||||
s += f"{k}={v}&"
|
||||
s = s.rstrip("&")
|
||||
return s
|
||||
|
||||
|
||||
def compute_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||
token_id: str, params: dict = None) -> str:
|
||||
"""小程序算法:sha1(accessToken + base64(sign_str))"""
|
||||
sign_str = build_sign_string(method, path, timestamp, token_id, params)
|
||||
b64 = base64.b64encode(sign_str.encode("utf-8")).decode("ascii")
|
||||
return hashlib.sha1(f"{access_token}{b64}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def make_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||
token_id: str, params: dict = None) -> str:
|
||||
"""有真实 accessToken 就按小程序算法实时签名;
|
||||
没有则生成形似合法的 sha1 签名(40 位 hex、随请求变化),防上游日志识别。"""
|
||||
if has_real_access_token(access_token):
|
||||
return compute_signature(access_token, method, path, timestamp,
|
||||
token_id, params)
|
||||
return fake_signature(timestamp, token_id)
|
||||
|
||||
|
||||
def get_headers(timestamp: str = None) -> dict:
|
||||
"""生成带时间戳的请求头"""
|
||||
ts = timestamp or str(int(time.time()))
|
||||
headers = HEADERS.copy()
|
||||
headers["hsf-x-timestamp"] = ts
|
||||
return headers
|
||||
|
||||
|
||||
def get_signature_headers(timestamp: str = None) -> dict:
|
||||
"""车辆查询接口(/project/search_bicycle)用的简化签名头。
|
||||
有全局 accessToken 时按小程序算法计算(针对该路径);否则生成
|
||||
sha1(时间戳+token_id) 占位值(上游目前不校验)。"""
|
||||
ts = timestamp or str(int(time.time()))
|
||||
token_id = HEADERS.get("hsf-x-tokenid", "")
|
||||
if has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||
sig = compute_signature(_GLOBAL_ACCESS_TOKEN, "POST", "/project/search_bicycle",
|
||||
ts, token_id)
|
||||
else:
|
||||
sig = fake_signature(ts, token_id)
|
||||
return {
|
||||
"hsf-x-timestamp": ts,
|
||||
"hsf-x-tokenid": token_id,
|
||||
"hsf-x-signature": sig,
|
||||
"platform": "xiaobai",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_token_invalid(result: dict, scope: str):
|
||||
"""上游返回 102001(token_id 失效,通常是小程序重新登录把旧会话踢掉)时
|
||||
统一改写响应:scope='user' 面向用户提示重新配置;scope='global' 面向管理员。
|
||||
注意 global 文案刻意不含 Token 字样,避免前端误弹用户级凭据弹窗。"""
|
||||
if isinstance(result, dict) and result.get("rtn_code") == 102001:
|
||||
result["token_invalid"] = True
|
||||
if scope == "user":
|
||||
result["message"] = "Token失效,微信凭据已过期,请在个人中心重新配置"
|
||||
else:
|
||||
result["message"] = "地图数据暂不可用:服务器全局凭据已失效,请联系管理员更新"
|
||||
return result
|
||||
|
||||
|
||||
def request_api(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
||||
"""Share global map reads across users, collection jobs and worker processes."""
|
||||
if method.upper() == "GET" and path == "/project/map":
|
||||
from map_cache import shared_map_cache
|
||||
bike_type = str((params or {}).get("type", "1")).strip()
|
||||
return shared_map_cache.get(bike_type, lambda: _request_api_uncached(
|
||||
method, path, params={**(params or {}), "type": bike_type}, data=data))
|
||||
return _request_api_uncached(method, path, params=params, data=data)
|
||||
|
||||
|
||||
def _request_api_uncached(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
||||
"""通用 API 请求(使用全局凭据;强验证模式下必须有全局 accessToken)"""
|
||||
if is_strict_mode() and not has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||
return _strict_reject()
|
||||
url = f"{BASE_URL}{path}"
|
||||
ts = str(int(time.time()))
|
||||
token_id = HEADERS["hsf-x-tokenid"]
|
||||
headers = get_headers(ts)
|
||||
headers["hsf-x-signature"] = make_signature(
|
||||
_GLOBAL_ACCESS_TOKEN, method, path, ts, token_id,
|
||||
params if method.upper() == "GET" else data)
|
||||
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = requests.get(url, params=params, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
else:
|
||||
resp = requests.post(url, json=data, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
content = resp.content
|
||||
if resp.headers.get("Content-Encoding") == "gzip" or content[:2] == b'\x1f\x8b':
|
||||
try:
|
||||
content = gzip.decompress(content)
|
||||
except Exception:
|
||||
pass
|
||||
return _normalize_token_invalid(json.loads(content), "global")
|
||||
except Exception as e:
|
||||
return {"error": str(e), "rtn_code": -1}
|
||||
|
||||
|
||||
def request_with_user_auth(user_id: int, method: str, path: str,
|
||||
params: dict = None, data: dict = None,
|
||||
_silent: bool = False) -> dict:
|
||||
"""使用用户凭据(token_id 必填 + access_token 选填)发起 API 请求"""
|
||||
from db import get_user_auth
|
||||
token_id, access_token = get_user_auth(user_id)
|
||||
if not token_id:
|
||||
return {"rtn_code": 401, "message": "用户未配置 Token ID"}
|
||||
if is_strict_mode() and not has_real_access_token(access_token):
|
||||
return _strict_reject()
|
||||
|
||||
ts = str(int(time.time()))
|
||||
headers = dict(HEADERS)
|
||||
headers["hsf-x-timestamp"] = ts
|
||||
headers["hsf-x-tokenid"] = token_id
|
||||
headers["hsf-x-signature"] = make_signature(
|
||||
access_token, method, path, ts, token_id,
|
||||
params if method.upper() == "GET" else data)
|
||||
|
||||
url = f"{BASE_URL}{path}"
|
||||
|
||||
if not _silent:
|
||||
from db import get_db
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
user_email = row["email"] if row else None
|
||||
print(f"[request_with_user_auth] user={user_email}, url={url}")
|
||||
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = requests.get(url, params=params, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
else:
|
||||
resp = requests.request(method, url, params=params, json=data,
|
||||
headers=headers, timeout=10, verify=True)
|
||||
if not _silent:
|
||||
print(f"[request_with_user_auth] response status={resp.status_code}, "
|
||||
f"body={resp.text[:200]}")
|
||||
return _normalize_token_invalid(resp.json(), "user")
|
||||
except Exception as e:
|
||||
if not _silent:
|
||||
print(f"[request_with_user_auth] request error: {e}")
|
||||
return {"rtn_code": -1, "error": str(e)}
|
||||
|
||||
|
||||
def get_token_config():
|
||||
"""获取当前全局凭据"""
|
||||
return {
|
||||
"token_id": HEADERS.get("hsf-x-tokenid", ""),
|
||||
"access_token": _GLOBAL_ACCESS_TOKEN,
|
||||
"has_access_token": has_real_access_token(_GLOBAL_ACCESS_TOKEN),
|
||||
}
|
||||
|
||||
|
||||
def save_token_config(token_id: str, access_token: str):
|
||||
"""保存全局凭据到文件并更新内存"""
|
||||
global _GLOBAL_ACCESS_TOKEN
|
||||
try:
|
||||
cfg = {
|
||||
"token_id": token_id or "",
|
||||
"access_token": access_token or "",
|
||||
}
|
||||
_TOKEN_CONFIG_PATH.write_text(
|
||||
"# 全局微信凭据\n"
|
||||
"# token_id: 登录后服务端下发的会话标识(重新登录小程序会失效,单会话策略)\n"
|
||||
"# access_token: 登录响应中的 accessToken(JWT,30天有效),用于实时计算签名;留空则发占位签名\n"
|
||||
f"token_id={cfg['token_id']}\n"
|
||||
f"access_token={cfg['access_token']}\n",
|
||||
encoding="utf-8")
|
||||
HEADERS["hsf-x-tokenid"] = cfg["token_id"]
|
||||
_GLOBAL_ACCESS_TOKEN = cfg["access_token"]
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[token配置] 保存失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# 上游错误文案 → 用户可读文案
|
||||
# 上游返回的 message 经常是英文原始错误(如 "non")或内部术语,直接透传
|
||||
# 用户看不懂。这里做统一映射;匹配不到时原样返回(上游文案本身可读时
|
||||
# 保持原样最安全)。所有面向用户的出口建议走这个函数。
|
||||
# =====================================================================
|
||||
|
||||
_UPSTREAM_MESSAGE_MAP = (
|
||||
# (命中关键词列表, 展示文案, 类别) 类别: occupied=车辆被占用 / unpaid=未支付
|
||||
# 认证/凭据
|
||||
(("token", "登录"), "登录状态已过期,请重新登录并更新凭据", "auth"),
|
||||
(("signature", "签名"), "请求签名校验失败,请重新登录小程序并更新 AccessToken", "auth"),
|
||||
# 车辆状态
|
||||
(("使用中", "骑行中"), "这辆车正在被别人骑行,换一辆试试", "occupied"),
|
||||
(("占用",), "这辆车当前被占用,换一辆试试", "occupied"),
|
||||
(("已被", "锁定"), "这辆车已被锁定或预约,换一辆试试", "occupied"),
|
||||
# 订单/支付
|
||||
(("未支付", "待支付"), "你有一笔未支付的订单,请先支付后再用车", "unpaid"),
|
||||
(("余额", "欠费"), "账户余额不足,请先充值", "unpaid"),
|
||||
# 业务拒绝
|
||||
(("超出", "范围"), "当前位置不在服务区内,请到规定的还车点操作", "deny"),
|
||||
(("频繁", "稍后再试"), "操作太频繁了,请稍等几秒再试", "deny"),
|
||||
)
|
||||
|
||||
# 保留关键词:内部逻辑(自动开锁避让重试等)需要按类别分支,调用方仍可拿到
|
||||
UPSTREAM_MSG_CATEGORY_KEYWORDS = {
|
||||
"occupied": ("使用中", "占用", "已被", "骑行", "锁定"),
|
||||
"unpaid": ("未支付", "待支付", "non"),
|
||||
}
|
||||
|
||||
|
||||
def upstream_msg_category(message) -> str:
|
||||
"""上游 message 的机器可读类别(occupied/unpaid/auth/deny/'')。"""
|
||||
msg = str(message or "").lower()
|
||||
for keys, _, cat in _UPSTREAM_MESSAGE_MAP:
|
||||
if any(k in msg for k in keys):
|
||||
return cat
|
||||
return ""
|
||||
|
||||
|
||||
def friendly_upstream_message(message, fallback="操作失败,请稍后重试"):
|
||||
"""把上游 message 翻译成用户可读文案;映射不到原样返回(无 fallback)。"""
|
||||
msg = str(message or "")
|
||||
if not msg.strip():
|
||||
return fallback
|
||||
for keys, text, _ in _UPSTREAM_MESSAGE_MAP:
|
||||
if any(k in msg for k in keys):
|
||||
return text
|
||||
return msg
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""微信API通信模块
|
||||
|
||||
凭据模型(对照 98/ 反编译小程序与实机抓包还原):
|
||||
- token_id:登录后服务端下发的会话标识(单会话:小程序重新登录即失效)。
|
||||
上游目前唯一强校验的头,必填。
|
||||
- access_token:登录响应里的 JWT(30 天有效)。小程序用它在本地实时计算签名:
|
||||
hsf-x-signature = sha1(access_token + base64(签名串))。选填。
|
||||
|
||||
签名策略(双模式 + 强验证开关):
|
||||
- 常规模式:有真实 access_token 就实时计算签名;否则生成形似合法的
|
||||
sha1 伪装签名(40 位 hex、随请求变化,防上游日志识别出固定异常值)。
|
||||
- 强验证模式(管理端开关,server_config.json 持久化):模拟上游开启
|
||||
签名校验后的行为——没有真实 access_token 的凭据直接拒绝发起请求,
|
||||
提前给出明确错误,而不是发出必然失败的请求。
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import requests
|
||||
import gzip
|
||||
from pathlib import Path
|
||||
|
||||
# 旧占位签名值(仅用于识别"未配置 accessToken"的存量配置,不再对外发送)
|
||||
_DUMMY_SIGNATURE = "xiaobai"
|
||||
|
||||
|
||||
def fake_signature(timestamp: str, token_id: str) -> str:
|
||||
"""未配置 accessToken 时生成形似合法的签名:40 位小写 hex(sha1 输出格式),
|
||||
且随时间戳/凭据变化,与真实流量的日志特征一致,避免上游从日志中识别出异常固定值。"""
|
||||
return hashlib.sha1(f"{timestamp}{token_id}".encode("utf-8")).hexdigest()
|
||||
|
||||
BASE_URL = "https://bike.sdlongren.com"
|
||||
|
||||
# 强验证开关的持久化文件
|
||||
_SERVER_CONFIG_PATH = Path(__file__).parent / "server_config.json"
|
||||
|
||||
# 从配置文件加载全局凭据
|
||||
_TOKEN_CONFIG_PATH = Path(__file__).parent / "token_config.txt"
|
||||
|
||||
|
||||
# ========== 强验证开关 ==========
|
||||
def _load_server_config() -> dict:
|
||||
try:
|
||||
if _SERVER_CONFIG_PATH.exists():
|
||||
return json.loads(_SERVER_CONFIG_PATH.read_text("utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def is_strict_mode() -> bool:
|
||||
"""上游强签名验证开关:开启后无真实 accessToken 的凭据将被拒绝发起请求"""
|
||||
return bool(_load_server_config().get("require_access_token"))
|
||||
|
||||
|
||||
def set_strict_mode(enabled: bool) -> bool:
|
||||
try:
|
||||
cfg = _load_server_config()
|
||||
cfg["require_access_token"] = bool(enabled)
|
||||
_SERVER_CONFIG_PATH.write_text(json.dumps(cfg, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[强验证开关] 保存失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def has_real_access_token(access_token) -> bool:
|
||||
"""是否为可用于计算签名的真实 accessToken(排除空值与占位符)"""
|
||||
return bool(access_token) and access_token != _DUMMY_SIGNATURE
|
||||
|
||||
|
||||
def parse_access_token_expiry(access_token) -> dict:
|
||||
"""从 accessToken(JWT)解析登录态有效期。
|
||||
|
||||
小程序登录响应中的 accessToken 是 RS256 JWT,payload 里带标准
|
||||
iat / nbf / exp(实测有效期 30 天)。只解码不验签——我们只需要
|
||||
展示大致过期时间,签名校验由上游负责。
|
||||
返回:{"parseable": bool, "expire_at": ts|None, "expire_time": "YYYY-MM-DD HH:MM"|None,
|
||||
"remaining_seconds": int|None, "source": "exp"|"iat+30d"|None, "reason": str}
|
||||
"""
|
||||
import base64 as _b64
|
||||
import datetime as _dt
|
||||
import json as _json
|
||||
|
||||
token = (access_token or "").strip()
|
||||
tz = _dt.timezone(_dt.timedelta(hours=8))
|
||||
result = {"parseable": False, "expire_at": None, "expire_time": None,
|
||||
"remaining_seconds": None, "source": None, "reason": ""}
|
||||
|
||||
def _fmt(ts: int) -> str:
|
||||
return _dt.datetime.fromtimestamp(ts, tz).strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
if not has_real_access_token(token):
|
||||
result["reason"] = "未填写 AccessToken"
|
||||
return result
|
||||
parts = token.split(".")
|
||||
if len(parts) != 3 or not token.startswith("ey"):
|
||||
result["reason"] = "不是标准 JWT 格式,无法解析过期时间"
|
||||
return result
|
||||
try:
|
||||
pad = parts[1] + "=" * (-len(parts[1]) % 4)
|
||||
payload = _json.loads(_b64.urlsafe_b64decode(pad))
|
||||
except Exception:
|
||||
result["reason"] = "JWT payload 解码失败"
|
||||
return result
|
||||
|
||||
exp = payload.get("exp") if isinstance(payload, dict) else None
|
||||
iat = payload.get("iat") if isinstance(payload, dict) else None
|
||||
try:
|
||||
exp = int(exp) if exp is not None else None
|
||||
iat = int(iat) if iat is not None else None
|
||||
except (TypeError, ValueError):
|
||||
exp = iat = None
|
||||
|
||||
if exp:
|
||||
result.update(parseable=True, expire_at=exp, expire_time=_fmt(exp),
|
||||
source="exp")
|
||||
elif iat:
|
||||
expire = iat + 30 * 86400 # 实测 accessToken 有效期 30 天
|
||||
result.update(parseable=True, expire_at=expire, expire_time=_fmt(expire),
|
||||
source="iat+30d")
|
||||
else:
|
||||
result["reason"] = "JWT 中没有 exp/iat 字段,无法推算有效期"
|
||||
return result
|
||||
|
||||
result["remaining_seconds"] = int(result["expire_at"] - _dt.datetime.now(tz).timestamp())
|
||||
return result
|
||||
|
||||
|
||||
def _strict_reject() -> dict:
|
||||
return {"rtn_code": 403,
|
||||
"message": "已开启上游强签名验证:请先填写 AccessToken(从微信小程序登录响应中获取)"}
|
||||
|
||||
|
||||
def _load_token_config():
|
||||
"""从 token_config.txt 加载全局凭据。
|
||||
|
||||
token_id:必填(重新登录小程序会失效,单会话策略)。
|
||||
access_token(旧键名 wx_signature 兼容读取):选填,用于实时计算签名。
|
||||
"""
|
||||
config = {"token_id": "", "access_token": ""}
|
||||
try:
|
||||
if _TOKEN_CONFIG_PATH.exists():
|
||||
for line in _TOKEN_CONFIG_PATH.read_text("utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
k, v = line.split("=", 1)
|
||||
k = k.strip()
|
||||
if k == "wx_signature": # 旧配置键名兼容
|
||||
k = "access_token"
|
||||
config[k] = v.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return config
|
||||
|
||||
|
||||
_TOKEN_CONFIG = _load_token_config()
|
||||
_GLOBAL_TOKEN_ID = _TOKEN_CONFIG.get("token_id", "")
|
||||
_GLOBAL_ACCESS_TOKEN = _TOKEN_CONFIG.get("access_token", "")
|
||||
|
||||
# 全局凭据只来自 token_config.txt / 管理后台保存,代码中不硬编码
|
||||
if not _GLOBAL_TOKEN_ID:
|
||||
print("[全局凭据] 警告: token_config.txt 中未配置 token_id,"
|
||||
"地图采集等全局请求将无法通过上游校验,请在管理后台填写")
|
||||
|
||||
HEADERS = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"hsf-x-signature": "",
|
||||
"hsf-x-timestamp": "",
|
||||
"hsf-x-tokenid": _GLOBAL_TOKEN_ID,
|
||||
"xweb_xhr": "1",
|
||||
"platform": "xiaobai",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 MicroMessenger/7.0",
|
||||
"content-type": "application/json",
|
||||
"accept": "*/*",
|
||||
"accept-language": "*",
|
||||
"sec-fetch-site": "cross-site",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-dest": "empty",
|
||||
"referer": "https://servicewechat.com/wx10426ca961518f43/108/page-frame.html",
|
||||
}
|
||||
|
||||
SEARCH_BIKE_URL = "https://bike.sdlongren.com/project/search_bicycle"
|
||||
SEARCH_HEADERS = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "*/*",
|
||||
}
|
||||
|
||||
|
||||
def build_sign_string(method: str, path: str, timestamp: str, token_id: str,
|
||||
params: dict = None) -> str:
|
||||
"""还原小程序 c(method, path, ts, params, needToken) 的签名串"""
|
||||
s = f"{method.upper()}$Hsf-X-Timestamp:{timestamp}Hsf-X-TokenId:{token_id}${path}"
|
||||
if params:
|
||||
s += "?"
|
||||
for k in sorted(params.keys()):
|
||||
v = params[k]
|
||||
# 与小程序一致:空字符串值只拼 key,嵌套对象/数组跳过
|
||||
if not k or (isinstance(v, str) and v == ""):
|
||||
s += f"{k}&"
|
||||
elif isinstance(v, (dict, list)):
|
||||
continue
|
||||
else:
|
||||
s += f"{k}={v}&"
|
||||
s = s.rstrip("&")
|
||||
return s
|
||||
|
||||
|
||||
def compute_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||
token_id: str, params: dict = None) -> str:
|
||||
"""小程序算法:sha1(accessToken + base64(sign_str))"""
|
||||
sign_str = build_sign_string(method, path, timestamp, token_id, params)
|
||||
b64 = base64.b64encode(sign_str.encode("utf-8")).decode("ascii")
|
||||
return hashlib.sha1(f"{access_token}{b64}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def make_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||
token_id: str, params: dict = None) -> str:
|
||||
"""有真实 accessToken 就按小程序算法实时签名;
|
||||
没有则生成形似合法的 sha1 签名(40 位 hex、随请求变化),防上游日志识别。"""
|
||||
if has_real_access_token(access_token):
|
||||
return compute_signature(access_token, method, path, timestamp,
|
||||
token_id, params)
|
||||
return fake_signature(timestamp, token_id)
|
||||
|
||||
|
||||
def get_headers(timestamp: str = None) -> dict:
|
||||
"""生成带时间戳的请求头"""
|
||||
ts = timestamp or str(int(time.time()))
|
||||
headers = HEADERS.copy()
|
||||
headers["hsf-x-timestamp"] = ts
|
||||
return headers
|
||||
|
||||
|
||||
def get_signature_headers(timestamp: str = None) -> dict:
|
||||
"""车辆查询接口(/project/search_bicycle)用的简化签名头。
|
||||
有全局 accessToken 时按小程序算法计算(针对该路径);否则生成
|
||||
sha1(时间戳+token_id) 占位值(上游目前不校验)。"""
|
||||
ts = timestamp or str(int(time.time()))
|
||||
token_id = HEADERS.get("hsf-x-tokenid", "")
|
||||
if has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||
sig = compute_signature(_GLOBAL_ACCESS_TOKEN, "POST", "/project/search_bicycle",
|
||||
ts, token_id)
|
||||
else:
|
||||
sig = fake_signature(ts, token_id)
|
||||
return {
|
||||
"hsf-x-timestamp": ts,
|
||||
"hsf-x-tokenid": token_id,
|
||||
"hsf-x-signature": sig,
|
||||
"platform": "xiaobai",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_token_invalid(result: dict, scope: str):
|
||||
"""上游返回 102001(token_id 失效,通常是小程序重新登录把旧会话踢掉)时
|
||||
统一改写响应:scope='user' 面向用户提示重新配置;scope='global' 面向管理员。
|
||||
注意 global 文案刻意不含 Token 字样,避免前端误弹用户级凭据弹窗。"""
|
||||
if isinstance(result, dict) and result.get("rtn_code") == 102001:
|
||||
result["token_invalid"] = True
|
||||
if scope == "user":
|
||||
result["message"] = "Token失效,微信凭据已过期,请在个人中心重新配置"
|
||||
else:
|
||||
result["message"] = "地图数据暂不可用:服务器全局凭据已失效,请联系管理员更新"
|
||||
return result
|
||||
|
||||
|
||||
def request_api(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
||||
"""Share global map reads across users, collection jobs and worker processes."""
|
||||
if method.upper() == "GET" and path == "/project/map":
|
||||
from map_cache import shared_map_cache
|
||||
bike_type = str((params or {}).get("type", "1")).strip()
|
||||
return shared_map_cache.get(bike_type, lambda: _request_api_uncached(
|
||||
method, path, params={**(params or {}), "type": bike_type}, data=data))
|
||||
return _request_api_uncached(method, path, params=params, data=data)
|
||||
|
||||
|
||||
def _request_api_uncached(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
||||
"""通用 API 请求(使用全局凭据;强验证模式下必须有全局 accessToken)"""
|
||||
if is_strict_mode() and not has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||
return _strict_reject()
|
||||
url = f"{BASE_URL}{path}"
|
||||
ts = str(int(time.time()))
|
||||
token_id = HEADERS["hsf-x-tokenid"]
|
||||
headers = get_headers(ts)
|
||||
headers["hsf-x-signature"] = make_signature(
|
||||
_GLOBAL_ACCESS_TOKEN, method, path, ts, token_id,
|
||||
params if method.upper() == "GET" else data)
|
||||
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = requests.get(url, params=params, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
else:
|
||||
resp = requests.post(url, json=data, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
content = resp.content
|
||||
if resp.headers.get("Content-Encoding") == "gzip" or content[:2] == b'\x1f\x8b':
|
||||
try:
|
||||
content = gzip.decompress(content)
|
||||
except Exception:
|
||||
pass
|
||||
return _normalize_token_invalid(json.loads(content), "global")
|
||||
except Exception as e:
|
||||
return {"error": str(e), "rtn_code": -1}
|
||||
|
||||
|
||||
def request_with_user_auth(user_id: int, method: str, path: str,
|
||||
params: dict = None, data: dict = None,
|
||||
_silent: bool = False) -> dict:
|
||||
"""使用用户凭据(token_id 必填 + access_token 选填)发起 API 请求"""
|
||||
from db import get_user_auth
|
||||
token_id, access_token = get_user_auth(user_id)
|
||||
if not token_id:
|
||||
return {"rtn_code": 401, "message": "用户未配置 Token ID"}
|
||||
if is_strict_mode() and not has_real_access_token(access_token):
|
||||
return _strict_reject()
|
||||
|
||||
ts = str(int(time.time()))
|
||||
headers = dict(HEADERS)
|
||||
headers["hsf-x-timestamp"] = ts
|
||||
headers["hsf-x-tokenid"] = token_id
|
||||
headers["hsf-x-signature"] = make_signature(
|
||||
access_token, method, path, ts, token_id,
|
||||
params if method.upper() == "GET" else data)
|
||||
|
||||
url = f"{BASE_URL}{path}"
|
||||
|
||||
if not _silent:
|
||||
from db import get_db
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
user_email = row["email"] if row else None
|
||||
print(f"[request_with_user_auth] user={user_email}, url={url}")
|
||||
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = requests.get(url, params=params, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
else:
|
||||
resp = requests.request(method, url, params=params, json=data,
|
||||
headers=headers, timeout=10, verify=True)
|
||||
if not _silent:
|
||||
print(f"[request_with_user_auth] response status={resp.status_code}, "
|
||||
f"body={resp.text[:200]}")
|
||||
return _normalize_token_invalid(resp.json(), "user")
|
||||
except Exception as e:
|
||||
if not _silent:
|
||||
print(f"[request_with_user_auth] request error: {e}")
|
||||
return {"rtn_code": -1, "error": str(e)}
|
||||
|
||||
|
||||
def get_token_config():
|
||||
"""获取当前全局凭据"""
|
||||
return {
|
||||
"token_id": HEADERS.get("hsf-x-tokenid", ""),
|
||||
"access_token": _GLOBAL_ACCESS_TOKEN,
|
||||
"has_access_token": has_real_access_token(_GLOBAL_ACCESS_TOKEN),
|
||||
}
|
||||
|
||||
|
||||
def save_token_config(token_id: str, access_token: str):
|
||||
"""保存全局凭据到文件并更新内存"""
|
||||
global _GLOBAL_ACCESS_TOKEN
|
||||
try:
|
||||
cfg = {
|
||||
"token_id": token_id or "",
|
||||
"access_token": access_token or "",
|
||||
}
|
||||
_TOKEN_CONFIG_PATH.write_text(
|
||||
"# 全局微信凭据\n"
|
||||
"# token_id: 登录后服务端下发的会话标识(重新登录小程序会失效,单会话策略)\n"
|
||||
"# access_token: 登录响应中的 accessToken(JWT,30天有效),用于实时计算签名;留空则发占位签名\n"
|
||||
f"token_id={cfg['token_id']}\n"
|
||||
f"access_token={cfg['access_token']}\n",
|
||||
encoding="utf-8")
|
||||
HEADERS["hsf-x-tokenid"] = cfg["token_id"]
|
||||
_GLOBAL_ACCESS_TOKEN = cfg["access_token"]
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[token配置] 保存失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# 上游错误文案 → 用户可读文案
|
||||
# 上游返回的 message 经常是英文原始错误(如 "non")或内部术语,直接透传
|
||||
# 用户看不懂。这里做统一映射;匹配不到时原样返回(上游文案本身可读时
|
||||
# 保持原样最安全)。所有面向用户的出口建议走这个函数。
|
||||
# =====================================================================
|
||||
|
||||
_UPSTREAM_MESSAGE_MAP = (
|
||||
# (命中关键词列表, 展示文案, 类别) 类别: occupied=车辆被占用 / unpaid=未支付
|
||||
# 认证/凭据
|
||||
(("token", "登录"), "登录状态已过期,请重新登录并更新凭据", "auth"),
|
||||
(("signature", "签名"), "请求签名校验失败,请重新登录小程序并更新 AccessToken", "auth"),
|
||||
# 车辆状态
|
||||
(("使用中", "骑行中"), "这辆车正在被别人骑行,换一辆试试", "occupied"),
|
||||
(("占用",), "这辆车当前被占用,换一辆试试", "occupied"),
|
||||
(("已被", "锁定"), "这辆车已被锁定或预约,换一辆试试", "occupied"),
|
||||
# 订单/支付
|
||||
(("未支付", "待支付"), "你有一笔未支付的订单,请先支付后再用车", "unpaid"),
|
||||
(("余额", "欠费"), "账户余额不足,请先充值", "unpaid"),
|
||||
# 业务拒绝
|
||||
(("超出", "范围"), "当前位置不在服务区内,请到规定的还车点操作", "deny"),
|
||||
(("频繁", "稍后再试"), "操作太频繁了,请稍等几秒再试", "deny"),
|
||||
)
|
||||
|
||||
# 保留关键词:内部逻辑(自动开锁避让重试等)需要按类别分支,调用方仍可拿到
|
||||
UPSTREAM_MSG_CATEGORY_KEYWORDS = {
|
||||
"occupied": ("使用中", "占用", "已被", "骑行", "锁定"),
|
||||
"unpaid": ("未支付", "待支付", "non"),
|
||||
}
|
||||
|
||||
|
||||
def upstream_msg_category(message) -> str:
|
||||
"""上游 message 的机器可读类别(occupied/unpaid/auth/deny/'')。"""
|
||||
msg = str(message or "").lower()
|
||||
for keys, _, cat in _UPSTREAM_MESSAGE_MAP:
|
||||
if any(k in msg for k in keys):
|
||||
return cat
|
||||
return ""
|
||||
|
||||
|
||||
def friendly_upstream_message(message, fallback="操作失败,请稍后重试"):
|
||||
"""把上游 message 翻译成用户可读文案;映射不到原样返回(无 fallback)。"""
|
||||
msg = str(message or "")
|
||||
if not msg.strip():
|
||||
return fallback
|
||||
for keys, text, _ in _UPSTREAM_MESSAGE_MAP:
|
||||
if any(k in msg for k in keys):
|
||||
return text
|
||||
return msg
|
||||
|
||||
Reference in New Issue
Block a user