Compare commits
4
Commits
preview
...
be3c8f775e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be3c8f775e | ||
|
|
e3a8df65f1 | ||
|
|
8fa8847384 | ||
|
|
f0537e446b |
@@ -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
|
||||||
+15
@@ -12,3 +12,18 @@ server_config.json
|
|||||||
.reasonix/
|
.reasonix/
|
||||||
*.zip
|
*.zip
|
||||||
*.log
|
*.log
|
||||||
|
temp/
|
||||||
|
.pytest_cache/
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
downloads/*.exe
|
||||||
|
token_config.txt.old-bak
|
||||||
|
scripts/.pack_baseline.json
|
||||||
|
update.zip
|
||||||
|
# ===== 敏感文件:证书 / 私钥 / 凭据一律不进库 =====
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
*.crt
|
||||||
|
*.ca-bundle
|
||||||
|
token_config.txt
|
||||||
|
*.db
|
||||||
@@ -1,153 +1,153 @@
|
|||||||
# 小白超人电动车地图
|
# 小白超人电动车地图
|
||||||
|
|
||||||
基于 Flask 的共享电动车位置追踪与租赁管理系统。通过微信小程序接口采集车辆位置,提供地图展示、历史轨迹、数据分析与租赁到期提醒功能。
|
基于 Flask 的共享电动车位置追踪与租赁管理系统。通过微信小程序接口采集车辆位置,提供地图展示、历史轨迹、数据分析与租赁到期提醒功能。
|
||||||
|
|
||||||
## 功能特性
|
## 功能特性
|
||||||
|
|
||||||
- **车辆位置采集**:自适应频率调用微信小程序接口抓取车辆数据(白天 5-10 分钟/次,夜间 30-60 分钟/次)
|
- **车辆位置采集**:自适应频率调用微信小程序接口抓取车辆数据(白天 5-10 分钟/次,夜间 30-60 分钟/次)
|
||||||
- **地图展示**:按车辆状态(可用 / 使用中 / 已锁定 / 已预约 / 低电量)分色标记
|
- **地图展示**:按车辆状态(可用 / 使用中 / 已锁定 / 已预约 / 低电量)分色标记
|
||||||
- **地图共享快照**:同一车辆类型的全局地图请求共用 60 秒快照,SQLite 租约合并跨线程/进程的并发刷新;失败也在同一窗口退避,不把过期成功结果当新数据返回。页面按快照到期时间自动刷新,返回前台时立即补刷,更新时间来自当前地图快照。
|
- **地图共享快照**:同一车辆类型的全局地图请求共用 60 秒快照,SQLite 租约合并跨线程/进程的并发刷新;失败也在同一窗口退避,不把过期成功结果当新数据返回。页面按快照到期时间自动刷新,返回前台时立即补刷,更新时间来自当前地图快照。
|
||||||
- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹
|
- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹
|
||||||
- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图
|
- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图
|
||||||
- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知)
|
- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知)
|
||||||
- **自动清理**:3 天前历史数据自动归档,定期 VACUUM 释放空间
|
- **自动清理**:3 天前历史数据自动归档,定期 VACUUM 释放空间
|
||||||
|
|
||||||
## 技术栈
|
## 技术栈
|
||||||
|
|
||||||
- **后端**:Flask + SQLite(原生 `sqlite3`)
|
- **后端**:Flask + SQLite(原生 `sqlite3`)
|
||||||
- **架构**:Blueprint 分模块(auth / map_api / rental / admin)
|
- **架构**:Blueprint 分模块(auth / map_api / rental / admin)
|
||||||
- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`)
|
- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`)
|
||||||
- **采集调度**:threading 后台线程 + 自适应间隔
|
- **采集调度**:threading 后台线程 + 自适应间隔
|
||||||
- **通知**:SMTP 邮件 + 内部计时器
|
- **通知**:SMTP 邮件 + 内部计时器
|
||||||
- **前端**:Jinja2 模板 + Leaflet 地图 + ECharts 图表
|
- **前端**:Jinja2 模板 + Leaflet 地图 + ECharts 图表
|
||||||
|
|
||||||
## 项目结构
|
## 项目结构
|
||||||
|
|
||||||
```
|
```
|
||||||
xbniu_map/
|
xbniu_map/
|
||||||
├── app.py # 应用入口 + 数据采集调度 + 分析 API
|
├── app.py # 应用入口 + 数据采集调度 + 分析 API
|
||||||
├── db.py # SQLite 连接与表初始化
|
├── db.py # SQLite 连接与表初始化
|
||||||
├── wechat.py # 微信小程序接口封装
|
├── wechat.py # 微信小程序接口封装
|
||||||
├── email_utils.py # 邮件发送
|
├── email_utils.py # 邮件发送
|
||||||
├── timer.py # 订单到期计时器管理
|
├── timer.py # 订单到期计时器管理
|
||||||
├── generate_icons.py # 地图标记图标生成
|
├── generate_icons.py # 地图标记图标生成
|
||||||
├── routes/
|
├── routes/
|
||||||
│ ├── auth.py # 用户注册 / 登录 / 微信授权
|
│ ├── auth.py # 用户注册 / 登录 / 微信授权
|
||||||
│ ├── map_api.py # 地图数据接口
|
│ ├── map_api.py # 地图数据接口
|
||||||
│ ├── rental.py # 租赁 / 提醒
|
│ ├── rental.py # 租赁 / 提醒
|
||||||
│ └── admin.py # 后台管理
|
│ └── admin.py # 后台管理
|
||||||
├── templates/
|
├── templates/
|
||||||
│ ├── map.html # 主地图页
|
│ ├── map.html # 主地图页
|
||||||
│ ├── analysis.html # 数据分析页
|
│ ├── analysis.html # 数据分析页
|
||||||
│ ├── admin.html # 后台管理页
|
│ ├── admin.html # 后台管理页
|
||||||
│ └── ring_progress.html # 状态环形图组件
|
│ └── ring_progress.html # 状态环形图组件
|
||||||
├── static/ # 地图标记图标(分色)
|
├── static/ # 地图标记图标(分色)
|
||||||
└── requirements.txt
|
└── requirements.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
## 配置说明
|
## 配置说明
|
||||||
|
|
||||||
启动前需准备以下敏感文件(不上传到 Git,已在 `.gitignore` 排除):
|
启动前需准备以下敏感文件(不上传到 Git,已在 `.gitignore` 排除):
|
||||||
|
|
||||||
| 文件 | 用途 | 示例 |
|
| 文件 | 用途 | 示例 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| `token_config.txt` | 全局默认微信 token | `token_id=1234567` |
|
| `token_config.txt` | 全局默认微信 token | `token_id=1234567` |
|
||||||
| `key.pem` / `private.key` | HTTPS 私钥 | `/BEGIN PRIVATE KEY/` |
|
| `key.pem` / `private.key` | HTTPS 私钥 | `/BEGIN PRIVATE KEY/` |
|
||||||
| `cert.pem` / `certificate.crt` / `ca_bundle.crt` | HTTPS 证书链 | `/BEGIN CERTIFICATE/` |
|
| `cert.pem` / `certificate.crt` / `ca_bundle.crt` | HTTPS 证书链 | `/BEGIN CERTIFICATE/` |
|
||||||
|
|
||||||
用户级授权凭据(`token_id` + `wx_signature`)存储在 `users.db` 的 `users` 表中,通过登录后从微信小程序抓包获取。
|
用户级授权凭据(`token_id` + `wx_signature`)存储在 `users.db` 的 `users` 表中,通过登录后从微信小程序抓包获取。
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 1. 安装依赖
|
# 1. 安装依赖
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
# 2. 准备敏感文件(见上方配置说明)
|
# 2. 准备敏感文件(见上方配置说明)
|
||||||
|
|
||||||
# 3. 启动服务
|
# 3. 启动服务
|
||||||
python app.py
|
python app.py
|
||||||
# 默认监听 127.0.0.1:98,对外由 nginx 反代提供 HTTPS
|
# 默认监听 127.0.0.1:98,对外由 nginx 反代提供 HTTPS
|
||||||
```
|
```
|
||||||
|
|
||||||
## 打包分发
|
## 打包分发
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 重新生成 1.zip(仅源码、模板、必要静态资源、测试和脚本)
|
# 重新生成 1.zip(仅源码、模板、必要静态资源、测试和脚本)
|
||||||
pwsh -File scripts/pack_zip.ps1
|
pwsh -File scripts/pack_zip.ps1
|
||||||
```
|
```
|
||||||
|
|
||||||
打包排除证书/密钥/token/数据库/备份/缓存,以及安装包、截图和运行日志;打包脚本会自动
|
打包排除证书/密钥/token/数据库/备份/缓存,以及安装包、截图和运行日志;打包脚本会自动
|
||||||
校验关键文件是否在位(campus/alerts/subscribe/export 等新模块缺失会直接报错)。
|
校验关键文件是否在位(campus/alerts/subscribe/export 等新模块缺失会直接报错)。
|
||||||
|
|
||||||
## 抓包工具下载
|
## 抓包工具下载
|
||||||
|
|
||||||
「填写凭证」等弹窗里的下载按钮指向 `/download/capture-tool.exe`,对应磁盘文件
|
「填写凭证」等弹窗里的下载按钮指向 `/download/capture-tool.exe`,对应磁盘文件
|
||||||
`downloads/xbniu-capture-tool.exe`(约 160MB,不在版本库及源码包 1.zip 中,部署时另行提供)。
|
`downloads/xbniu-capture-tool.exe`(约 160MB,不在版本库及源码包 1.zip 中,部署时另行提供)。
|
||||||
|
|
||||||
- 公开访问,无需登录:用户注册前就要先拿到工具,否则形成死循环。
|
- 公开访问,无需登录:用户注册前就要先拿到工具,否则形成死循环。
|
||||||
- 路由带 `conditional=True` 并显式返回 `Accept-Ranges: bytes`,支持断点续传。
|
- 路由带 `conditional=True` 并显式返回 `Accept-Ranges: bytes`,支持断点续传。
|
||||||
- 文件缺失时返回 `404 {"rtn_code": 404, "message": "安装包暂未上传"}`。
|
- 文件缺失时返回 `404 {"rtn_code": 404, "message": "安装包暂未上传"}`。
|
||||||
- 微信/QQ/支付宝/钉钉/微博/抖音等内置浏览器会拦截 exe 下载,前端改为弹出
|
- 微信/QQ/支付宝/钉钉/微博/抖音等内置浏览器会拦截 exe 下载,前端改为弹出
|
||||||
「复制链接到外部浏览器」提示。
|
「复制链接到外部浏览器」提示。
|
||||||
|
|
||||||
**nginx 注意**:大文件经 `proxy_pass` 下载时,若带宽较低可能被默认的
|
**nginx 注意**:大文件经 `proxy_pass` 下载时,若带宽较低可能被默认的
|
||||||
`proxy_read_timeout 60s` 中断,建议在对应 `location` 上放宽:
|
`proxy_read_timeout 60s` 中断,建议在对应 `location` 上放宽:
|
||||||
|
|
||||||
```nginx
|
```nginx
|
||||||
location /download/ {
|
location /download/ {
|
||||||
proxy_pass http://127.0.0.1:98;
|
proxy_pass http://127.0.0.1:98;
|
||||||
proxy_read_timeout 600s;
|
proxy_read_timeout 600s;
|
||||||
proxy_max_temp_file_size 0; # 不缓冲大文件,直接透传
|
proxy_max_temp_file_size 0; # 不缓冲大文件,直接透传
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 数据库表结构
|
## 数据库表结构
|
||||||
|
|
||||||
| 表 | 用途 |
|
| 表 | 用途 |
|
||||||
|----|------|
|
|----|------|
|
||||||
| `users` | 用户账号、微信授权凭据 |
|
| `users` | 用户账号、微信授权凭据 |
|
||||||
| `sessions` | 登录会话 token |
|
| `sessions` | 登录会话 token |
|
||||||
| `reminders` | 租赁提醒订阅 |
|
| `reminders` | 租赁提醒订阅 |
|
||||||
| `rentals` | 租车记录 + 多级通知状态(notified_10/5/3/2/1/0)|
|
| `rentals` | 租车记录 + 多级通知状态(notified_10/5/3/2/1/0)|
|
||||||
| `bike_history` | 车辆位置历史(含状态、电量)|
|
| `bike_history` | 车辆位置历史(含状态、电量)|
|
||||||
| `snapshots` | 整体快照(总数、状态分布)|
|
| `snapshots` | 整体快照(总数、状态分布)|
|
||||||
|
|
||||||
## 核心机制
|
## 核心机制
|
||||||
|
|
||||||
### 自适应采集
|
### 自适应采集
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def get_adaptive_interval():
|
def get_adaptive_interval():
|
||||||
# 夜间(23:00-07:00):1800-3600s(30-60 分钟)
|
# 夜间(23:00-07:00):1800-3600s(30-60 分钟)
|
||||||
# 白天:300-600s(5-10 分钟)
|
# 白天:300-600s(5-10 分钟)
|
||||||
```
|
```
|
||||||
|
|
||||||
后台线程循环执行 `snapshot_bike_positions()`,调用 `/project/map?type=3` 拉取全部车辆,写入 `bike_history`。
|
后台线程循环执行 `snapshot_bike_positions()`,调用 `/project/map?type=3` 拉取全部车辆,写入 `bike_history`。
|
||||||
|
|
||||||
### 数据清理
|
### 数据清理
|
||||||
|
|
||||||
每 23 小时执行一次:删除 3 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
每 23 小时执行一次:删除 3 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
||||||
|
|
||||||
### 订单到期提醒
|
### 订单到期提醒
|
||||||
|
|
||||||
`timer.py` 在启动时恢复未到期的计时器(`restore_active_timers`),并在到期前 10/5/3/2/1/0 分钟触发邮件通知。每条 `rentals` 记录的 `notified_*` 字段标记对应级别是否已发送,避免重复通知。
|
`timer.py` 在启动时恢复未到期的计时器(`restore_active_timers`),并在到期前 10/5/3/2/1/0 分钟触发邮件通知。每条 `rentals` 记录的 `notified_*` 字段标记对应级别是否已发送,避免重复通知。
|
||||||
|
|
||||||
## 主要接口
|
## 主要接口
|
||||||
|
|
||||||
| 方法 | 路径 | 说明 |
|
| 方法 | 路径 | 说明 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| POST | `/api/collect_now` | 手动触发一次采集 |
|
| POST | `/api/collect_now` | 手动触发一次采集 |
|
||||||
| GET | `/api/bike_history?code=xxx` | 查询指定车辆历史轨迹 |
|
| GET | `/api/bike_history?code=xxx` | 查询指定车辆历史轨迹 |
|
||||||
| GET | `/api/analysis/overview` | 状态分布 + 时段分布 + Top10 |
|
| GET | `/api/analysis/overview` | 状态分布 + 时段分布 + Top10 |
|
||||||
| GET | `/api/analysis/heatmap?code=xxx` | 热力图数据 |
|
| GET | `/api/analysis/heatmap?code=xxx` | 热力图数据 |
|
||||||
|
|
||||||
具体路由详见 `routes/*.py`。
|
具体路由详见 `routes/*.py`。
|
||||||
|
|
||||||
## 注意事项
|
## 注意事项
|
||||||
|
|
||||||
- `token_id` 与 `wx_signature` 来自微信小程序抓包,**修改后需重启服务或通过后台保存**
|
- `token_id` 与 `wx_signature` 来自微信小程序抓包,**修改后需重启服务或通过后台保存**
|
||||||
- `users.db` 包含用户授权信息与历史轨迹,**不可公开**
|
- `users.db` 包含用户授权信息与历史轨迹,**不可公开**
|
||||||
- HTTPS 证书文件(`*.pem` `*.crt` `*.key`)若损坏会导致小程序接口无法访问
|
- HTTPS 证书文件(`*.pem` `*.crt` `*.key`)若损坏会导致小程序接口无法访问
|
||||||
- 服务监听端口默认 98(非特权端口)
|
- 服务监听端口默认 98(非特权端口)
|
||||||
|
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
-----BEGIN CERTIFICATE-----
|
|
||||||
MIIGITCCBAmgAwIBAgIRANCpCCVfjlDl8zltERRwKjcwDQYJKoZIhvcNAQEMBQAw
|
|
||||||
XzELMAkGA1UEBhMCR0IxGDAWBgNVBAoTD1NlY3RpZ28gTGltaXRlZDE2MDQGA1UE
|
|
||||||
AxMtU2VjdGlnbyBQdWJsaWMgU2VydmVyIEF1dGhlbnRpY2F0aW9uIFJvb3QgUjQ2
|
|
||||||
MB4XDTI1MDkyNDAwMDAwMFoXDTM1MDkyMzIzNTk1OVowRjELMAkGA1UEBhMCQVQx
|
|
||||||
FTATBgNVBAoTDFplcm9TU0wgR21iSDEgMB4GA1UEAxMXWmVyb1NTTCBSU0EgRFYg
|
|
||||||
U1NMIENBIDIwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCnXX3Qm/G+
|
|
||||||
ujylvYIkhJ53ZZ7XM03vXY03sCnO9VWjwMsV0qCQMlvhuRiJwrm4M5jgGehxIiCR
|
|
||||||
1qT0AyL2rHTWJR07vjJzuNmp7uoKu3HKwixBk9QuXD5aliO8/EDbzdZDcG/Hm5pC
|
|
||||||
mOeusLtds/UE/Iq24nw5WpcgZE5Ly+F/yCYDuEa7hXLJAPM5SecJIblG1OQ3ukMl
|
|
||||||
HHNBbDxBpGWTyDudd0DTed0NTgCPs1t8RZPhW9Gt/8nDwFX0pQ4eHfPEB8c6eNl2
|
|
||||||
sRr2Afp1YErakR+53yEX2SXc2Kz0fbTlUc+To0ULGcJiWNyZwj//DTZ+M4xxsT2T
|
|
||||||
qjQ4Xfvm2EUTymrXDrh1Pm/wkBouu860c6eeQfNlKlccUyHOSeKCtPIWreMvH3Be
|
|
||||||
Ydeu3DwI8lefn/VUhSB2Bbz7hX3qz3oMmtSTmWhTnobyKlx1L2b/oloaqpy1cBc/
|
|
||||||
QiLRSOptYGPjZtX0pRrTVKQXeP2rPUk0y5q/40WRpugSlHCX6aceWnsCAwEAAaOC
|
|
||||||
AW8wggFrMB8GA1UdIwQYMBaAFFZzWGSV+ZIasBIqBGJ5oUAViCFJMB0GA1UdDgQW
|
|
||||||
BBRLvvp2hCNEBLnOvjFv6fUyBv8MVzAOBgNVHQ8BAf8EBAMCAYYwEgYDVR0TAQH/
|
|
||||||
BAgwBgEB/wIBADATBgNVHSUEDDAKBggrBgEFBQcDATATBgNVHSAEDDAKMAgGBmeB
|
|
||||||
DAECATBUBgNVHR8ETTBLMEmgR6BFhkNodHRwOi8vY3JsLnNlY3RpZ28uY29tL1Nl
|
|
||||||
Y3RpZ29QdWJsaWNTZXJ2ZXJBdXRoZW50aWNhdGlvblJvb3RSNDYuY3JsMIGEBggr
|
|
||||||
BgEFBQcBAQR4MHYwTwYIKwYBBQUHMAKGQ2h0dHA6Ly9jcnQuc2VjdGlnby5jb20v
|
|
||||||
U2VjdGlnb1B1YmxpY1NlcnZlckF1dGhlbnRpY2F0aW9uUm9vdFI0Ni5wN2MwIwYI
|
|
||||||
KwYBBQUHMAGGF2h0dHA6Ly9vY3NwLnNlY3RpZ28uY29tMA0GCSqGSIb3DQEBDAUA
|
|
||||||
A4ICAQCJ/3v2/vdexHsdVyXL9aCTQE01YXl23866TVM/LgRpRW+kneZXXZxP0hy4
|
|
||||||
GnvlqUcxTq97B6qPdQcQxQxpGne7CRn0nWauzqieMcJzYl3fDC2Q/ANyPhyrbwCI
|
|
||||||
zx9EsRrgfjvuJCaUMtlfYpKqBUYiPOCPAN0HdrLD5hU6oV1tvWVsUzTA43skC3uH
|
|
||||||
wQM5YPIk0NDJFw3NhQPOIOwbq09T+SYSEZvsJ3t4sA4H3gh03RETNaAwTcTNS/+u
|
|
||||||
1tAeQUZZmKQyLWYLyoxvbISp/MFr9xqhDqrpAurYVNeiLJ5+4/WZPml20yNZjcxV
|
|
||||||
KKqRYdEurl8rmI2toCnCDWiEcTDvoYGtz60eYIt7VJID4DrCjTxAWTWh2T5ag2pK
|
|
||||||
ryNJGt8BFGLtjeD774SxAFn5MGYBVvEK4LXmCjVX78pb6/0Dceo71dlQUK68yftb
|
|
||||||
+yTeyoqjwgk2L8vNSrkj6UTkvvqXSONFuVU7bvC0O/9bi5MXBv7QUivMNxDsTtaT
|
|
||||||
IZO7PsSCRmLraQM2EPBgbNL9lRSEYi4Hj+NicT/e87pbhv88k0oec9xGcnkcvZpN
|
|
||||||
sJBz78mkZfeFIIjh02e2y9ke/Fqw1FbdhHtU2myaFnX0sRyGLmI/vzXSwyvT+Kxl
|
|
||||||
Wx8FV64z2PBdwd0vXRaAMXomGC0M1vQa5fBDn4dimzewsSiphQ==
|
|
||||||
-----END CERTIFICATE-----
|
|
||||||
@@ -69,6 +69,45 @@ def gcj02_to_bd09(lng, lat):
|
|||||||
return [z * math.cos(theta) + 0.0065, z * math.sin(theta) + 0.006]
|
return [z * math.cos(theta) + 0.0065, z * math.sin(theta) + 0.006]
|
||||||
|
|
||||||
|
|
||||||
|
def wgs84_to_gcj02(lng, lat):
|
||||||
|
"""WGS84(GPS 原始)-> GCJ02。
|
||||||
|
|
||||||
|
用途:浏览器 `navigator.geolocation` 给的是 WGS84,上游车辆/停车区是
|
||||||
|
GCJ02,两者直接比较会差 500 米左右。算法与 static/js/coordtransform.js
|
||||||
|
的 `wgs84togcj02` 完全一致。
|
||||||
|
"""
|
||||||
|
lng, lat = float(lng), float(lat)
|
||||||
|
if _out_of_china(lng, lat):
|
||||||
|
return [lng, lat]
|
||||||
|
dlat = _transform_lat(lng - 105.0, lat - 35.0)
|
||||||
|
dlng = _transform_lng(lng - 105.0, lat - 35.0)
|
||||||
|
radlat = lat / 180.0 * _PI
|
||||||
|
magic = math.sin(radlat)
|
||||||
|
magic = 1 - _EE * magic * magic
|
||||||
|
sqrtmagic = math.sqrt(magic)
|
||||||
|
dlat = (dlat * 180.0) / ((_A * (1 - _EE)) / (magic * sqrtmagic) * _PI)
|
||||||
|
dlng = (dlng * 180.0) / (_A / sqrtmagic * math.cos(radlat) * _PI)
|
||||||
|
return [lng + dlng, lat + dlat]
|
||||||
|
|
||||||
|
|
||||||
|
def gcj02_to_wgs84(lng, lat):
|
||||||
|
"""GCJ02 -> WGS84(把内部算出的点转回浏览器/上游使用的坐标系)。
|
||||||
|
|
||||||
|
用不动点迭代反解(4 轮即收敛到厘米级):先按 GCJ02 猜一个 WGS84,再用
|
||||||
|
正向转换量修正。比 coordtransform 的「对称偏移」反解精度更高 —— 后者在
|
||||||
|
本地实测约 1 米误差,会吃到停车区边界的判断上。
|
||||||
|
"""
|
||||||
|
lng, lat = float(lng), float(lat)
|
||||||
|
if _out_of_china(lng, lat):
|
||||||
|
return [lng, lat]
|
||||||
|
w_lng, w_lat = lng, lat
|
||||||
|
for _ in range(4):
|
||||||
|
g_lng, g_lat = wgs84_to_gcj02(w_lng, w_lat)
|
||||||
|
w_lng -= (g_lng - lng)
|
||||||
|
w_lat -= (g_lat - lat)
|
||||||
|
return [w_lng, w_lat]
|
||||||
|
|
||||||
|
|
||||||
# ========== 几何工具 ==========
|
# ========== 几何工具 ==========
|
||||||
|
|
||||||
def haversine_m(lat1, lng1, lat2, lng2):
|
def haversine_m(lat1, lng1, lat2, lng2):
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
-----BEGIN CERTIFICATE-----
|
|
||||||
MIIDCTCCAfGgAwIBAgIUcol8xUcjrWOBC1h/XBA3PSL8hr4wDQYJKoZIhvcNAQEL
|
|
||||||
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDQyMTEyNTgzM1oXDTI3MDQy
|
|
||||||
MTEyNTgzM1owFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
|
|
||||||
AAOCAQ8AMIIBCgKCAQEAugEeAJfOaLGmKkxnHfcbssngyK78LcmC3TvMaGybcTaM
|
|
||||||
LvyVyuKI9vTnb8kfJM8tQZxP104uPVwTBa2bPdlaFju8DEw0tv6SvwPAxXMahBwS
|
|
||||||
lEa+sYEGjgGuwdzDpem9dpkx+3t6MPk/vs5LUN3bJsnqhRHIYFV05IwcUmNQHvu3
|
|
||||||
DkSPyVukBgbkg0kfZmbD0fSd2MOi7W7oPfX7GFs+mow7Ofg9mBvewazTsfm80KkB
|
|
||||||
RLJlG7cEk9r+qME75XnAzPSrxjsr2gUhu44YJ5HPqSgz+jsWiLB47U8D0GgeEZZF
|
|
||||||
DKOxoSzadIhKPcAzH6rmyv+88RORhoftasnml1SMxQIDAQABo1MwUTAdBgNVHQ4E
|
|
||||||
FgQUflZL1SfllduC5LWjr/TTvIunlCIwHwYDVR0jBBgwFoAUflZL1SfllduC5LWj
|
|
||||||
r/TTvIunlCIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAKQy1
|
|
||||||
YJnUAOXKOGKZJUUDsWjbYZ0i7qG+4YzpyPb0KRfyzTwn0FDnuPbHfSjd5QGZgJxt
|
|
||||||
CoZV0qTUHWctKdid+A8q1fynvu1DERIYHRGWJvKLv9ySY8KmRZLG/gYJvzjxiPkL
|
|
||||||
qDECmVRKJM1wRp5tKynuo97kyCLmQHHEnIlyZ9HM+elItpwZweD/R7yd/qULbKUX
|
|
||||||
lTGzPeReUj7mIcscsuTvKCRKBhslxvUgQDHsN1q4eEwLCNVr94V0wstEp5sdeJvl
|
|
||||||
pL4lqLxXlCqBMxzZ8hm5VK83N+Wj1nokkCsCLmzL96GW6yE7ZffDU+Ibus+YCtj2
|
|
||||||
9zC9vtd3PadkFyHkDQ==
|
|
||||||
-----END CERTIFICATE-----
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
-----BEGIN CERTIFICATE-----
|
|
||||||
MIIFfzCCA+egAwIBAgIQDON/Evu3Aq6w4T67JD84rzANBgkqhkiG9w0BAQsFADBG
|
|
||||||
MQswCQYDVQQGEwJBVDEVMBMGA1UEChMMWmVyb1NTTCBHbWJIMSAwHgYDVQQDExda
|
|
||||||
ZXJvU1NMIFJTQSBEViBTU0wgQ0EgMjAeFw0yNjA0MjEwMDAwMDBaFw0yNjA3MjAy
|
|
||||||
MzU5NTlaMBkxFzAVBgNVBAMTDjQ3LjExMi4xODcuMTcyMIIBIjANBgkqhkiG9w0B
|
|
||||||
AQEFAAOCAQ8AMIIBCgKCAQEA6uK6FJIX3CHtkkWb8s448v5l0UY8yh4hbL/xhvQQ
|
|
||||||
rAGEdeDRm/zwstwsw/OKkkWLe0eE1zC0/zvgZN8gjXNtgUK4A6uev+CjctEPijT6
|
|
||||||
fhcXsWspQQ6ihRGw+giSIm8TIGdh97cwpyKB6e8EgpddLlcaBPBd4Xkyi5aZwGuq
|
|
||||||
DjuvDMeYfd+3Fe0MuZ61RObQ8cplAG14GKBly/HhEkY4ycxrzxKNbMYRJW9wZvUH
|
|
||||||
v+E3ku7ezdCtaLU2AVtVlVYRgPwUT7kB9oSqXSXds18g1H6f3w0Ci1osRgrA/gRQ
|
|
||||||
ZNUIwdJ58FT955xHmvkP98NxRLLPZ8Wqmn9/5jnsVyn12QIDAQABo4ICFDCCAhAw
|
|
||||||
HwYDVR0jBBgwFoAUS776doQjRAS5zr4xb+n1Mgb/DFcwHQYDVR0OBBYEFIyOE+cJ
|
|
||||||
rZ4oLGIPabNopuvEy8ReMA4GA1UdDwEB/wQEAwIFoDAMBgNVHRMBAf8EAjAAMBMG
|
|
||||||
A1UdJQQMMAoGCCsGAQUFBwMBMBMGA1UdIAQMMAowCAYGZ4EMAQIBMG4GCCsGAQUF
|
|
||||||
BwEBBGIwYDA5BggrBgEFBQcwAoYtaHR0cDovL2NydC5zZWN0aWdvLmNvbS9aZXJv
|
|
||||||
U1NMUlNBRFZTU0xDQTIuY3J0MCMGCCsGAQUFBzABhhdodHRwOi8vb2NzcC5zZWN0
|
|
||||||
aWdvLmNvbTCCAQMGCisGAQQB1nkCBAIEgfQEgfEA7wB2ANdtfRDRp/V3wsfpX9cA
|
|
||||||
v/mCyTNaZeHQswFzF8DIxWl3AAABnbBCKukAAAQDAEcwRQIgJjjYYsW+ptzeLGtg
|
|
||||||
MfutQR8kJDZufkJ2IRyuazHm0zYCIQDXWFYyaPX+FDx/4+oahwkrpOpb8ywLfibm
|
|
||||||
oE/KjyEYGwB1AMijxH/Hs625NWsBP2p6Em3jOk5DpcZG+ZetOXWZHc+aAAABnbBC
|
|
||||||
K6IAAAQDAEYwRAIgLP/AOhTK1ZWDFs/wPJ1XnImgiatyMic9yPpjB5+1l0wCIDks
|
|
||||||
CKZq5eKiHo1HlGh/tqg8TVIcEbFH6rd7APD+AtTgMA8GA1UdEQQIMAaHBC9wu6ww
|
|
||||||
DQYJKoZIhvcNAQELBQADggGBADYvxJBts1Z7PqRZrDmR8FYEnHS4ldzq+ANDypZV
|
|
||||||
wY4A0DAq1VkClYC32EW2p7DDLr1+xOX8OIUwGmFh5lZq7m1JiaMe2p3ajFz89pSR
|
|
||||||
QccFgXNsPW1Ux0W70Jb+R6oOW7q9VhwQl8fQRatkeTf8Su1K/LpS/4+72z3AOPJe
|
|
||||||
FqW2Vrp6x1Ecta7GJxlLvuS0Z6276/0h+bWAp2cEsSzJ4cnNfrdCKIhakHcWjN0n
|
|
||||||
zDITy9Sflv7xHDeHyV8p5N7+bTt/9tQE+sr8n0KOmUaxpPLPqfEVjXMdi/2G+YYM
|
|
||||||
YsATqDPgdBpwxClTd4I/bpumVU+Aqf8u0UPOhtCapPjm1cgV3AOfZ4TyQ/0Wd415
|
|
||||||
kjVFfSi/w4vN2D2I+Kp1hG0heqLq4Wm7DV2rt0shaTZxwP6cdEJ7aNqYDIegKGLx
|
|
||||||
xfFKWCWw9VwxuC/L0Fvb7gwFvxZ3fBFYKnexwVgRMvt39JSXWlcAvFW6Pc8+OeZL
|
|
||||||
J29EzuPpiH9B9zwiDeMMO4XzLw==
|
|
||||||
-----END CERTIFICATE-----
|
|
||||||
+48
-48
@@ -1,48 +1,48 @@
|
|||||||
from playwright.sync_api import sync_playwright
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
with sync_playwright() as p:
|
with sync_playwright() as p:
|
||||||
browser = p.chromium.launch(headless=True)
|
browser = p.chromium.launch(headless=True)
|
||||||
page = browser.new_page()
|
page = browser.new_page()
|
||||||
page.goto('http://127.0.0.1:5000/analysis')
|
page.goto('http://127.0.0.1:5000/analysis')
|
||||||
page.wait_for_timeout(2000)
|
page.wait_for_timeout(2000)
|
||||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug1.png')
|
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug1.png')
|
||||||
print("Page loaded, took debug1.png")
|
print("Page loaded, took debug1.png")
|
||||||
|
|
||||||
# 点击加载轨迹
|
# 点击加载轨迹
|
||||||
page.click('button:has-text("加载轨迹")')
|
page.click('button:has-text("加载轨迹")')
|
||||||
page.wait_for_timeout(4000)
|
page.wait_for_timeout(4000)
|
||||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug2.png')
|
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug2.png')
|
||||||
print("After loading trajectory, took debug2.png")
|
print("After loading trajectory, took debug2.png")
|
||||||
|
|
||||||
# 检查 traj-map 容器内的 DOM 结构
|
# 检查 traj-map 容器内的 DOM 结构
|
||||||
html = page.evaluate('''() => {
|
html = page.evaluate('''() => {
|
||||||
const el = document.getElementById("traj-map");
|
const el = document.getElementById("traj-map");
|
||||||
if (!el) return "NOT FOUND";
|
if (!el) return "NOT FOUND";
|
||||||
let info = "children: " + el.children.length + "\\n";
|
let info = "children: " + el.children.length + "\\n";
|
||||||
let canvas = el.querySelectorAll("canvas");
|
let canvas = el.querySelectorAll("canvas");
|
||||||
let mapdiv = el.querySelectorAll("div");
|
let mapdiv = el.querySelectorAll("div");
|
||||||
info += "canvas count: " + canvas.length + "\\n";
|
info += "canvas count: " + canvas.length + "\\n";
|
||||||
info += "div count: " + mapdiv.length + "\\n";
|
info += "div count: " + mapdiv.length + "\\n";
|
||||||
for (let c of canvas) {
|
for (let c of canvas) {
|
||||||
info += " canvas: " + c.width + "x" + c.height + "\\n";
|
info += " canvas: " + c.width + "x" + c.height + "\\n";
|
||||||
}
|
}
|
||||||
// 检查 pointer-events
|
// 检查 pointer-events
|
||||||
let allEls = Array.from(el.querySelectorAll("*"));
|
let allEls = Array.from(el.querySelectorAll("*"));
|
||||||
let blocking = [];
|
let blocking = [];
|
||||||
for (let e of allEls) {
|
for (let e of allEls) {
|
||||||
let style = window.getComputedStyle(e);
|
let style = window.getComputedStyle(e);
|
||||||
let rect = e.getBoundingClientRect();
|
let rect = e.getBoundingClientRect();
|
||||||
if (rect.width > 0 && rect.height > 0) {
|
if (rect.width > 0 && rect.height > 0) {
|
||||||
let pe = style.pointerEvents;
|
let pe = style.pointerEvents;
|
||||||
let vis = style.visibility;
|
let vis = style.visibility;
|
||||||
let op = style.opacity;
|
let op = style.opacity;
|
||||||
let z = style.zIndex;
|
let z = style.zIndex;
|
||||||
let disp = style.display;
|
let disp = style.display;
|
||||||
blocking.push(e.className + " ptr:" + pe + " vis:" + vis + " z:" + z + " op:" + op + " disp:" + disp);
|
blocking.push(e.className + " ptr:" + pe + " vis:" + vis + " z:" + z + " op:" + op + " disp:" + disp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return info + "\\nall elements:\\n" + blocking.join("\\n");
|
return info + "\\nall elements:\\n" + blocking.join("\\n");
|
||||||
}''')
|
}''')
|
||||||
print(html)
|
print(html)
|
||||||
|
|
||||||
browser.close()
|
browser.close()
|
||||||
|
|||||||
+134
-134
@@ -1,134 +1,134 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""注册/重置密码邮箱验证码:服务端 60 秒冷却、10 分钟有效期、5 次错误作废。
|
"""注册/重置密码邮箱验证码:服务端 60 秒冷却、10 分钟有效期、5 次错误作废。
|
||||||
内存存储(单进程部署足够);重启后验证码失效,用户重新发送即可。
|
内存存储(单进程部署足够);重启后验证码失效,用户重新发送即可。
|
||||||
purpose 区分用途(register / reset),不同用途互不通用。"""
|
purpose 区分用途(register / reset),不同用途互不通用。"""
|
||||||
import hashlib
|
import hashlib
|
||||||
import secrets
|
import secrets
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
|
||||||
import rate_limit
|
import rate_limit
|
||||||
from email_utils import render_email_safe, send_email
|
from email_utils import render_email_safe, send_email
|
||||||
|
|
||||||
CODE_TTL_SECONDS = 10 * 60
|
CODE_TTL_SECONDS = 10 * 60
|
||||||
CODE_SEND_COOLDOWN = 60 # 同一邮箱两次发送的最小间隔(服务端强制)
|
CODE_SEND_COOLDOWN = 60 # 同一邮箱两次发送的最小间隔(服务端强制)
|
||||||
CODE_MAX_ATTEMPTS = 5
|
CODE_MAX_ATTEMPTS = 5
|
||||||
SEND_IP_MAX_PER_HOUR = 10 # 同一 IP 每小时最多请求验证码次数
|
SEND_IP_MAX_PER_HOUR = 10 # 同一 IP 每小时最多请求验证码次数
|
||||||
|
|
||||||
PURPOSES = ("register", "reset")
|
PURPOSES = ("register", "reset")
|
||||||
|
|
||||||
_lock = threading.Lock()
|
_lock = threading.Lock()
|
||||||
_codes: dict = {} # email -> {"hash": sha256hex, "expires": ts, "attempts": n, "sent_at": ts, "purpose": str}
|
_codes: dict = {} # email -> {"hash": sha256hex, "expires": ts, "attempts": n, "sent_at": ts, "purpose": str}
|
||||||
|
|
||||||
# purpose -> (邮件主题, 页面标题, 首段说明, 顶部 kicker, 主题色)
|
# purpose -> (邮件主题, 页面标题, 首段说明, 顶部 kicker, 主题色)
|
||||||
_PURPOSE_TITLES = {
|
_PURPOSE_TITLES = {
|
||||||
"register": (
|
"register": (
|
||||||
"【小白超人】注册验证码",
|
"【小白超人】注册验证码",
|
||||||
"注册验证码",
|
"注册验证码",
|
||||||
"你正在注册小白超人电动车地图账号,请在页面中输入下面的验证码完成注册。",
|
"你正在注册小白超人电动车地图账号,请在页面中输入下面的验证码完成注册。",
|
||||||
"小白超人 · 账号注册",
|
"小白超人 · 账号注册",
|
||||||
"#2563eb",
|
"#2563eb",
|
||||||
),
|
),
|
||||||
"reset": (
|
"reset": (
|
||||||
"【小白超人】重置密码验证码",
|
"【小白超人】重置密码验证码",
|
||||||
"重置密码验证码",
|
"重置密码验证码",
|
||||||
"你正在重置小白超人电动车地图的登录密码,请在页面中输入下面的验证码。",
|
"你正在重置小白超人电动车地图的登录密码,请在页面中输入下面的验证码。",
|
||||||
"小白超人 · 重置密码",
|
"小白超人 · 重置密码",
|
||||||
"#dc2626",
|
"#dc2626",
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _now() -> float:
|
def _now() -> float:
|
||||||
return time.time()
|
return time.time()
|
||||||
|
|
||||||
|
|
||||||
def _code_hash(code: str, email: str) -> str:
|
def _code_hash(code: str, email: str) -> str:
|
||||||
return hashlib.sha256(f"{email.lower()}:{code}".encode("utf-8")).hexdigest()
|
return hashlib.sha256(f"{email.lower()}:{code}".encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def _cleanup_locked(now: float):
|
def _cleanup_locked(now: float):
|
||||||
for email in [e for e, v in _codes.items() if v["expires"] <= now]:
|
for email in [e for e, v in _codes.items() if v["expires"] <= now]:
|
||||||
_codes.pop(email, None)
|
_codes.pop(email, None)
|
||||||
|
|
||||||
|
|
||||||
def send_code(email: str, purpose: str = "register") -> tuple:
|
def send_code(email: str, purpose: str = "register") -> tuple:
|
||||||
"""发送验证码到邮箱。返回 (ok, message)。受 60s 邮箱冷却与每小时 IP 上限约束。"""
|
"""发送验证码到邮箱。返回 (ok, message)。受 60s 邮箱冷却与每小时 IP 上限约束。"""
|
||||||
email = (email or "").strip().lower()
|
email = (email or "").strip().lower()
|
||||||
if purpose not in PURPOSES:
|
if purpose not in PURPOSES:
|
||||||
purpose = "register"
|
purpose = "register"
|
||||||
now = _now()
|
now = _now()
|
||||||
with _lock:
|
with _lock:
|
||||||
entry = _codes.get(email)
|
entry = _codes.get(email)
|
||||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||||
wait = int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
wait = int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||||
return False, f"发送过于频繁,请 {wait} 秒后再试"
|
return False, f"发送过于频繁,请 {wait} 秒后再试"
|
||||||
code = f"{secrets.randbelow(1000000):06d}"
|
code = f"{secrets.randbelow(1000000):06d}"
|
||||||
subject, title, lead, kicker, accent = _PURPOSE_TITLES.get(
|
subject, title, lead, kicker, accent = _PURPOSE_TITLES.get(
|
||||||
purpose, _PURPOSE_TITLES["register"])
|
purpose, _PURPOSE_TITLES["register"])
|
||||||
ttl_minutes = CODE_TTL_SECONDS // 60
|
ttl_minutes = CODE_TTL_SECONDS // 60
|
||||||
# 纯文本版本保留(无 HTML 能力的客户端);HTML 版本走统一模板。
|
# 纯文本版本保留(无 HTML 能力的客户端);HTML 版本走统一模板。
|
||||||
plain = (f"{title}\n\n{lead}\n\n验证码:{code}\n\n"
|
plain = (f"{title}\n\n{lead}\n\n验证码:{code}\n\n"
|
||||||
f"{ttl_minutes} 分钟内有效。若不是你本人操作,请忽略本邮件。")
|
f"{ttl_minutes} 分钟内有效。若不是你本人操作,请忽略本邮件。")
|
||||||
html_body = render_email_safe(
|
html_body = render_email_safe(
|
||||||
kicker=kicker, title=title,
|
kicker=kicker, title=title,
|
||||||
lead=f"请在页面中输入下面的验证码,{ttl_minutes} 分钟内有效。",
|
lead=f"请在页面中输入下面的验证码,{ttl_minutes} 分钟内有效。",
|
||||||
code=code, accent=accent,
|
code=code, accent=accent,
|
||||||
details=[("有效期", f"{ttl_minutes} 分钟"),
|
details=[("有效期", f"{ttl_minutes} 分钟"),
|
||||||
("用途", "账号注册" if purpose == "register" else "重置登录密码")],
|
("用途", "账号注册" if purpose == "register" else "重置登录密码")],
|
||||||
footnote="若不是你本人操作,请忽略本邮件,你的账号不会受到任何影响。",
|
footnote="若不是你本人操作,请忽略本邮件,你的账号不会受到任何影响。",
|
||||||
)
|
)
|
||||||
ok = send_email(email, subject, plain, html_body)
|
ok = send_email(email, subject, plain, html_body)
|
||||||
if not ok:
|
if not ok:
|
||||||
return False, "验证码邮件发送失败,请稍后重试"
|
return False, "验证码邮件发送失败,请稍后重试"
|
||||||
with _lock:
|
with _lock:
|
||||||
_codes[email] = {
|
_codes[email] = {
|
||||||
"hash": _code_hash(code, email),
|
"hash": _code_hash(code, email),
|
||||||
"expires": now + CODE_TTL_SECONDS,
|
"expires": now + CODE_TTL_SECONDS,
|
||||||
"attempts": 0,
|
"attempts": 0,
|
||||||
"sent_at": now,
|
"sent_at": now,
|
||||||
"purpose": purpose,
|
"purpose": purpose,
|
||||||
}
|
}
|
||||||
return True, "验证码已发送"
|
return True, "验证码已发送"
|
||||||
|
|
||||||
|
|
||||||
def check_send_cooldown(email: str) -> int:
|
def check_send_cooldown(email: str) -> int:
|
||||||
"""返回还需等待的秒数(0 = 可发送)。供接口在未真正发送前返回通用响应。"""
|
"""返回还需等待的秒数(0 = 可发送)。供接口在未真正发送前返回通用响应。"""
|
||||||
email = (email or "").strip().lower()
|
email = (email or "").strip().lower()
|
||||||
now = _now()
|
now = _now()
|
||||||
with _lock:
|
with _lock:
|
||||||
entry = _codes.get(email)
|
entry = _codes.get(email)
|
||||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||||
return int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
return int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def verify_code(email: str, code: str, purpose: str = "register") -> bool:
|
def verify_code(email: str, code: str, purpose: str = "register") -> bool:
|
||||||
"""校验验证码;成功即作废,连续错误 5 次作废。purpose 必须与发送时一致。"""
|
"""校验验证码;成功即作废,连续错误 5 次作废。purpose 必须与发送时一致。"""
|
||||||
email = (email or "").strip().lower()
|
email = (email or "").strip().lower()
|
||||||
code = (code or "").strip()
|
code = (code or "").strip()
|
||||||
if purpose not in PURPOSES:
|
if purpose not in PURPOSES:
|
||||||
purpose = "register"
|
purpose = "register"
|
||||||
now = _now()
|
now = _now()
|
||||||
with _lock:
|
with _lock:
|
||||||
entry = _codes.get(email)
|
entry = _codes.get(email)
|
||||||
if not entry or entry["expires"] <= now or entry["attempts"] >= CODE_MAX_ATTEMPTS:
|
if not entry or entry["expires"] <= now or entry["attempts"] >= CODE_MAX_ATTEMPTS:
|
||||||
return False
|
return False
|
||||||
if entry.get("purpose", "register") != purpose:
|
if entry.get("purpose", "register") != purpose:
|
||||||
# 用途不匹配(例如拿注册验证码去重置密码):按错误处理并计数
|
# 用途不匹配(例如拿注册验证码去重置密码):按错误处理并计数
|
||||||
entry["attempts"] += 1
|
entry["attempts"] += 1
|
||||||
return False
|
return False
|
||||||
if not (len(code) == 6 and code.isdigit()):
|
if not (len(code) == 6 and code.isdigit()):
|
||||||
entry["attempts"] += 1
|
entry["attempts"] += 1
|
||||||
return False
|
return False
|
||||||
if secrets.compare_digest(entry["hash"], _code_hash(code, email)):
|
if secrets.compare_digest(entry["hash"], _code_hash(code, email)):
|
||||||
_codes.pop(email, None)
|
_codes.pop(email, None)
|
||||||
return True
|
return True
|
||||||
entry["attempts"] += 1
|
entry["attempts"] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def ip_send_allowed(ip: str) -> bool:
|
def ip_send_allowed(ip: str) -> bool:
|
||||||
"""同一 IP 每小时验证码发送次数上限。"""
|
"""同一 IP 每小时验证码发送次数上限。"""
|
||||||
return rate_limit.hit(("send_code", ip), SEND_IP_MAX_PER_HOUR, 3600)
|
return rate_limit.hit(("send_code", ip), SEND_IP_MAX_PER_HOUR, 3600)
|
||||||
|
|||||||
+55
-55
@@ -1,55 +1,55 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""生成车辆标记图标"""
|
"""生成车辆标记图标"""
|
||||||
from PIL import Image, ImageDraw, ImageFont
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
import os
|
import os
|
||||||
|
|
||||||
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
||||||
os.makedirs(STATIC_DIR, exist_ok=True)
|
os.makedirs(STATIC_DIR, exist_ok=True)
|
||||||
|
|
||||||
# 状态颜色 (R, G, B)
|
# 状态颜色 (R, G, B)
|
||||||
COLORS = {
|
COLORS = {
|
||||||
"green": "#4CAF50",
|
"green": "#4CAF50",
|
||||||
"pink": "#E91E8C",
|
"pink": "#E91E8C",
|
||||||
"orange": "#FF9800",
|
"orange": "#FF9800",
|
||||||
"gray": "#9E9E9E",
|
"gray": "#9E9E9E",
|
||||||
"red": "#F44336",
|
"red": "#F44336",
|
||||||
}
|
}
|
||||||
|
|
||||||
def make_icon(color_hex, label="", size=36):
|
def make_icon(color_hex, label="", size=36):
|
||||||
"""生成圆形标记图标,label=文字(如百分比或状态符)"""
|
"""生成圆形标记图标,label=文字(如百分比或状态符)"""
|
||||||
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||||
draw = ImageDraw.Draw(img)
|
draw = ImageDraw.Draw(img)
|
||||||
|
|
||||||
r = size // 2
|
r = size // 2
|
||||||
cx, cy = r, r
|
cx, cy = r, r
|
||||||
# 填充圆
|
# 填充圆
|
||||||
draw.ellipse([2, 2, size-3, size-3], fill=color_hex + "E0") # 带透明度
|
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)
|
draw.ellipse([2, 2, size-3, size-3], outline=color_hex, width=2)
|
||||||
|
|
||||||
if label:
|
if label:
|
||||||
# 文字居中
|
# 文字居中
|
||||||
try:
|
try:
|
||||||
font_size = 11 if len(label) <= 2 else 9
|
font_size = 11 if len(label) <= 2 else 9
|
||||||
font = ImageFont.truetype("arial.ttf", font_size)
|
font = ImageFont.truetype("arial.ttf", font_size)
|
||||||
except Exception:
|
except Exception:
|
||||||
font = ImageFont.load_default()
|
font = ImageFont.load_default()
|
||||||
bbox = draw.textbbox((0, 0), label, font=font)
|
bbox = draw.textbbox((0, 0), label, font=font)
|
||||||
tw = bbox[2] - bbox[0]
|
tw = bbox[2] - bbox[0]
|
||||||
th = bbox[3] - bbox[1]
|
th = bbox[3] - bbox[1]
|
||||||
tx = cx - tw // 2 - bbox[0]
|
tx = cx - tw // 2 - bbox[0]
|
||||||
ty = cy - th // 2 - bbox[1]
|
ty = cy - th // 2 - bbox[1]
|
||||||
# 白色文字
|
# 白色文字
|
||||||
draw.text((tx, ty), label, fill="#FFFFFF", font=font)
|
draw.text((tx, ty), label, fill="#FFFFFF", font=font)
|
||||||
|
|
||||||
path = os.path.join(STATIC_DIR, f"marker_{color_hex[1:]}.png")
|
path = os.path.join(STATIC_DIR, f"marker_{color_hex[1:]}.png")
|
||||||
img.save(path, "PNG")
|
img.save(path, "PNG")
|
||||||
print(f" {path}")
|
print(f" {path}")
|
||||||
return path
|
return path
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print("生成标记图标...")
|
print("生成标记图标...")
|
||||||
for name, color in COLORS.items():
|
for name, color in COLORS.items():
|
||||||
make_icon(color)
|
make_icon(color)
|
||||||
print("完成!")
|
print("完成!")
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
-----BEGIN PRIVATE KEY-----
|
|
||||||
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC6AR4Al85osaYq
|
|
||||||
TGcd9xuyyeDIrvwtyYLdO8xobJtxNowu/JXK4oj29OdvyR8kzy1BnE/XTi49XBMF
|
|
||||||
rZs92VoWO7wMTDS2/pK/A8DFcxqEHBKURr6xgQaOAa7B3MOl6b12mTH7e3ow+T++
|
|
||||||
zktQ3dsmyeqFEchgVXTkjBxSY1Ae+7cORI/JW6QGBuSDSR9mZsPR9J3Yw6Ltbug9
|
|
||||||
9fsYWz6ajDs5+D2YG97BrNOx+bzQqQFEsmUbtwST2v6owTvlecDM9KvGOyvaBSG7
|
|
||||||
jhgnkc+pKDP6OxaIsHjtTwPQaB4RlkUMo7GhLNp0iEo9wDMfqubK/7zxE5GGh+1q
|
|
||||||
yeaXVIzFAgMBAAECggEAAz37vjo8gHoAPHfXyvTrXa1ue/EDjO9t7C9GUSz7dKNl
|
|
||||||
GXiQ9S1dAnj4WRbMsoE4omPNccz3ZLMTKHkt3eEeVImMAzwyJbJq77tqrnENgu9T
|
|
||||||
qj6lb5tLzZ6H45yBKIYveulmrqHTWmvYdESiRBw/MqjjAUNzFlgcUSjZYYeWS5lD
|
|
||||||
ViTo/jR0uInj5Ebj3CfNCMZXwMHDZVIcp5EruXbZv/PAozCCEwzUOdxiibs5iX25
|
|
||||||
+ArnVaYRbTTttyWjf1pu0UxmiZaqN7/3Z0nTIL13l8QEakooVGKOBFOG1HLfYBNG
|
|
||||||
hnYcfbWPOzgoowDqfzb3ylovdQJPL4Lrt5Oxd9ajTQKBgQDhSE/i+JhfhZg2+PZW
|
|
||||||
WGKA3FWcFJ8UScCCHdHP5rVxn5fGWIHMWtURnjzzkUm38DONXQihl5M8Mg99wfc9
|
|
||||||
wIGDv7VHqZlSBF/s0aF7w4ndsVXttClh5NFl/7/RGmpVM5EklIwm+9Kox5fAkzOX
|
|
||||||
/UAeHxIoooP6bvWUG5BEksX+KwKBgQDTXcR2VS564poOsFIB93VQ8uwN/qrVz33Z
|
|
||||||
T8PQXV5DkyhQ9mvGknUN0v8jG7xb946ZO4GQmISA6AcOvdkpeQYYNa/HKu3wmZ6G
|
|
||||||
IZmZgA9XNdX4EVnztyuNY7Bnrepm3xHEH4DhafQqeqc2tjplxMmUAqlFTfDhwioq
|
|
||||||
IukFQDgYzwKBgEdcuLGVPe9ESmtfgejoJovbP+MpRRsQIcMV3xiUZHWRsGpMLxGk
|
|
||||||
1Em4bmZZZ5i0ph/pkIpfkWxID1Au2TreeChb2fjRaJfqethxr02dK1bmjem2YEV6
|
|
||||||
TjqZQRHj5DsJErkbtSnEK377er6t4nIK7vybqwzkLhpue6xm7tRKCh3xAoGAA7PU
|
|
||||||
yS3czpJBmJhGF3q6N1zJ/cTEQVKNJc1b5L599DkTr7dhU+0k18UmavsFZacEfHKq
|
|
||||||
ZloFmCx4Uy3ILA3OqYXnOlnqKRjHyhm0kxfHLQPoZ5wGM1q2DJf+cxJ81Kh7qy/S
|
|
||||||
FiDBAi172F2A0F+OGGWjiW9AFPRNwMczxb/GO8kCgYEAuG4Fn/CVrXSY8HyDEjoJ
|
|
||||||
Miamb4fP/xYT0qAQPRZXzdAlsEsWnAO9DlQSevzAWZQbQXEl3V4ZQo9N/GT+3rfw
|
|
||||||
ZiD1fB5SUB+91PAXot5rCgC9G8Yih+78tRifPRnFJVYfn+/o6rw3rNG4LzM/8ssn
|
|
||||||
M+XVUWaErmaUPpUH5dGcOVA=
|
|
||||||
-----END PRIVATE KEY-----
|
|
||||||
+212
@@ -0,0 +1,212 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""上游停车区(parkeArea)多边形:还车点判定 + 失败后吸附到最近合法停车区。
|
||||||
|
|
||||||
|
## 为什么要有这个模块
|
||||||
|
|
||||||
|
上游 `/record/checkLocation` 会判断「这个坐标能不能还车」,不在停车区内返回
|
||||||
|
`parkNoShow`。旧兜底(`routes/rental.py::get_nearest_park_point`)是「找最近的一辆
|
||||||
|
type=1 共享单车,把它的坐标当停车点」—— 拿车当车位,周边没单车就直接失效,
|
||||||
|
而且返回的是 GCJ02、被当成 WGS84 发回上游。本模块改用上游自己返回的
|
||||||
|
`parkeArea` 多边形做判断和吸附。
|
||||||
|
|
||||||
|
## 坐标系(改之前先读完,这里错一次就偏 500 米)
|
||||||
|
|
||||||
|
**本模块只处理 GCJ02,不做任何转换。**
|
||||||
|
|
||||||
|
- `parkeArea.points` / `bicycleStation` / `bike_history` / `campus_locations`
|
||||||
|
全部是 **GCJ02**(上游与本地库同一套);
|
||||||
|
- 唯一不一样的是浏览器 `navigator.geolocation`,它给 **WGS84**;
|
||||||
|
- 所以 WGS84 → GCJ02 的转换只发生在 API 边界(`routes/rental.py::
|
||||||
|
to_upstream_coords`、`routes/share.py` 的共享还车入口),一次转完,
|
||||||
|
之后从判定到发上游全用 GCJ02。
|
||||||
|
|
||||||
|
把 GCJ02 多边形直接和 WGS84 点比较 = 系统性偏移,比不判断更糟;反过来,
|
||||||
|
把 GCJ02 点再转一次也是同一个错误。
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
|
||||||
|
from campus import point_in_polygon
|
||||||
|
|
||||||
|
#: 吸附距离超过这个值(米)只打日志、仍然吸附:说明坐标本身可能有问题。
|
||||||
|
SNAP_WARN_M = 800.0
|
||||||
|
|
||||||
|
#: 从停车区边界往内部推的试探步长(米),第一个落在多边形内的即采用。
|
||||||
|
_INSIDE_STEPS_M = (0.6, 1.5, 3.0, 6.0, 12.0, 25.0)
|
||||||
|
|
||||||
|
_EARTH_R = 6371000.0
|
||||||
|
|
||||||
|
|
||||||
|
def _num(value):
|
||||||
|
try:
|
||||||
|
return float(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 解析 ==========
|
||||||
|
|
||||||
|
def parse_park_areas(map_data):
|
||||||
|
"""上游 `/project/map` 的 data -> [{"points": [[lat, lng], ...]}]。
|
||||||
|
|
||||||
|
- **只跳过 `is_disable == 2`(停用)块**;`1` 是启用 —— 这条是实测出来的,
|
||||||
|
别凭字段名猜:拿 23 块的首点逐块问上游 `/record/checkLocation`,
|
||||||
|
21 块 `is_disable=1` 全部返回 `rtn=0 定位已满足还车条件`,唯一的
|
||||||
|
`is_disable=2` 块返回 `204009 请到停车区域进行还车`。
|
||||||
|
(前端 `map.js` 里 `is_disable !== 1` 当启用画绿色,同样判反了。)
|
||||||
|
- points 兼容 `{latitude, longitude}` 与 `[lat, lng]` 两种写法;
|
||||||
|
- 少于 3 个点的(构不成多边形)忽略。
|
||||||
|
|
||||||
|
注意:返回的坐标是上游原样的 **GCJ02**(实测 checkLocation 只认这套),
|
||||||
|
不要在这里转换。
|
||||||
|
"""
|
||||||
|
if not isinstance(map_data, dict):
|
||||||
|
return []
|
||||||
|
raw_areas = map_data.get("parkeArea")
|
||||||
|
if not isinstance(raw_areas, list):
|
||||||
|
return []
|
||||||
|
areas = []
|
||||||
|
for raw in raw_areas:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
continue
|
||||||
|
if str(raw.get("is_disable")) == "2": # 2 = 停用;1 = 启用
|
||||||
|
continue
|
||||||
|
points = []
|
||||||
|
for item in raw.get("points") or []:
|
||||||
|
if isinstance(item, dict):
|
||||||
|
lat, lng = _num(item.get("latitude")), _num(item.get("longitude"))
|
||||||
|
elif isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||||
|
lat, lng = _num(item[0]), _num(item[1])
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
if lat is None or lng is None:
|
||||||
|
continue
|
||||||
|
points.append([lat, lng])
|
||||||
|
if len(points) >= 3:
|
||||||
|
areas.append({"points": points})
|
||||||
|
return areas
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 局部平面投影(百米尺度下足够精确,避免每步开方算球面) ==========
|
||||||
|
|
||||||
|
def _to_xy(lat, lng, origin_lat, origin_lng):
|
||||||
|
x = math.radians(lng - origin_lng) * _EARTH_R * math.cos(math.radians(origin_lat))
|
||||||
|
y = math.radians(lat - origin_lat) * _EARTH_R
|
||||||
|
return x, y
|
||||||
|
|
||||||
|
|
||||||
|
def _to_latlng(x, y, origin_lat, origin_lng):
|
||||||
|
lat = origin_lat + math.degrees(y / _EARTH_R)
|
||||||
|
cos = math.cos(math.radians(origin_lat))
|
||||||
|
lng = origin_lng + math.degrees(x / (_EARTH_R * (cos if abs(cos) > 1e-9 else 1e-9)))
|
||||||
|
return lat, lng
|
||||||
|
|
||||||
|
|
||||||
|
def closest_boundary_point(lat, lng, polygon):
|
||||||
|
"""点到多边形边界最近的点(与边平行的投影)。
|
||||||
|
|
||||||
|
入参与返回均为 GCJ02,返回 `{"latitude", "longitude", "distance"}`(米),
|
||||||
|
多边形非法时返回 None。
|
||||||
|
"""
|
||||||
|
if not polygon or len(polygon) < 3:
|
||||||
|
return None
|
||||||
|
best = None
|
||||||
|
best_d = float("inf")
|
||||||
|
for i in range(len(polygon)):
|
||||||
|
ax, ay = _to_xy(polygon[i][0], polygon[i][1], lat, lng)
|
||||||
|
bx, by = _to_xy(polygon[(i + 1) % len(polygon)][0],
|
||||||
|
polygon[(i + 1) % len(polygon)][1], lat, lng)
|
||||||
|
dx, dy = bx - ax, by - ay
|
||||||
|
seg2 = dx * dx + dy * dy
|
||||||
|
# 查询点就是原点 (0,0)
|
||||||
|
t = 0.0 if seg2 == 0 else max(0.0, min(1.0, -(ax * dx + ay * dy) / seg2))
|
||||||
|
cx, cy = ax + t * dx, ay + t * dy
|
||||||
|
dist = math.hypot(cx, cy)
|
||||||
|
if dist < best_d:
|
||||||
|
best_d = dist
|
||||||
|
best = (cx, cy)
|
||||||
|
if best is None:
|
||||||
|
return None
|
||||||
|
plat, plng = _to_latlng(best[0], best[1], lat, lng)
|
||||||
|
return {"latitude": plat, "longitude": plng, "distance": best_d}
|
||||||
|
|
||||||
|
|
||||||
|
def _centroid(polygon):
|
||||||
|
n = len(polygon)
|
||||||
|
return (sum(p[0] for p in polygon) / n, sum(p[1] for p in polygon) / n)
|
||||||
|
|
||||||
|
|
||||||
|
def _nudge_inside(edge_lat, edge_lng, polygon, target_lat, target_lng):
|
||||||
|
"""从边界点朝 target(一般是质心)方向逐级推,返回第一个落在内部的点。"""
|
||||||
|
dx, dy = _to_xy(target_lat, target_lng, edge_lat, edge_lng)
|
||||||
|
norm = math.hypot(dx, dy)
|
||||||
|
if norm == 0:
|
||||||
|
return None
|
||||||
|
ux, uy = dx / norm, dy / norm
|
||||||
|
for step in _INSIDE_STEPS_M:
|
||||||
|
cand_lat, cand_lng = _to_latlng(ux * step, uy * step, edge_lat, edge_lng)
|
||||||
|
if point_in_polygon(cand_lat, cand_lng, polygon):
|
||||||
|
return {"latitude": cand_lat, "longitude": cand_lng}
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def nearest_parking_point(lat, lng, areas):
|
||||||
|
"""GCJ02 点 -> 最近的可用停车区里的一个 GCJ02 点。
|
||||||
|
|
||||||
|
返回 `{"latitude", "longitude", "distance"}`;没有任何可用区时返回 None。
|
||||||
|
"""
|
||||||
|
if not areas:
|
||||||
|
return None
|
||||||
|
best_area = None
|
||||||
|
best_edge = None
|
||||||
|
best_d = float("inf")
|
||||||
|
for area in areas:
|
||||||
|
edge = closest_boundary_point(lat, lng, area["points"])
|
||||||
|
if edge is None:
|
||||||
|
continue
|
||||||
|
if edge["distance"] < best_d:
|
||||||
|
best_area, best_edge, best_d = area, edge, edge["distance"]
|
||||||
|
if best_area is None or best_edge is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
polygon = best_area["points"]
|
||||||
|
centre_lat, centre_lng = _centroid(polygon)
|
||||||
|
inside = _nudge_inside(best_edge["latitude"], best_edge["longitude"],
|
||||||
|
polygon, centre_lat, centre_lng)
|
||||||
|
if inside is None:
|
||||||
|
# 退化/自交多边形:退到质心,质心也不在多边形内就放弃,不要瞎发坐标。
|
||||||
|
if point_in_polygon(centre_lat, centre_lng, polygon):
|
||||||
|
inside = {"latitude": centre_lat, "longitude": centre_lng}
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
inside["distance"] = best_d
|
||||||
|
return inside
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 对外主入口 ==========
|
||||||
|
|
||||||
|
def resolve_return_coord(latitude, longitude, areas):
|
||||||
|
"""把一个还车坐标解析成「一定落在停车区内」的坐标(全程 GCJ02)。
|
||||||
|
|
||||||
|
返回:
|
||||||
|
- None:拿不到可用停车区(调用方保留原坐标);
|
||||||
|
- {"inside": True, "moved": False}:本来就在区内,原样返回;
|
||||||
|
- {"inside": False, "moved": True}:已吸附到最近停车区内的点。
|
||||||
|
|
||||||
|
⚠️ 入参必须是 GCJ02。浏览器给的是 WGS84,调用方要先用
|
||||||
|
`campus.wgs84_to_gcj02` / `routes.rental.to_upstream_coords` 转换一次。
|
||||||
|
"""
|
||||||
|
lat, lng = _num(latitude), _num(longitude)
|
||||||
|
if lat is None or lng is None or not areas:
|
||||||
|
return None
|
||||||
|
|
||||||
|
for area in areas:
|
||||||
|
if point_in_polygon(lat, lng, area["points"]):
|
||||||
|
return {"latitude": lat, "longitude": lng,
|
||||||
|
"inside": True, "moved": False, "distance": 0.0}
|
||||||
|
|
||||||
|
snapped = nearest_parking_point(lat, lng, areas)
|
||||||
|
if snapped is None:
|
||||||
|
return None
|
||||||
|
return {"latitude": snapped["latitude"], "longitude": snapped["longitude"],
|
||||||
|
"inside": False, "moved": True, "distance": snapped["distance"]}
|
||||||
-27
@@ -1,27 +0,0 @@
|
|||||||
-----BEGIN RSA PRIVATE KEY-----
|
|
||||||
MIIEpAIBAAKCAQEA6uK6FJIX3CHtkkWb8s448v5l0UY8yh4hbL/xhvQQrAGEdeDR
|
|
||||||
m/zwstwsw/OKkkWLe0eE1zC0/zvgZN8gjXNtgUK4A6uev+CjctEPijT6fhcXsWsp
|
|
||||||
QQ6ihRGw+giSIm8TIGdh97cwpyKB6e8EgpddLlcaBPBd4Xkyi5aZwGuqDjuvDMeY
|
|
||||||
fd+3Fe0MuZ61RObQ8cplAG14GKBly/HhEkY4ycxrzxKNbMYRJW9wZvUHv+E3ku7e
|
|
||||||
zdCtaLU2AVtVlVYRgPwUT7kB9oSqXSXds18g1H6f3w0Ci1osRgrA/gRQZNUIwdJ5
|
|
||||||
8FT955xHmvkP98NxRLLPZ8Wqmn9/5jnsVyn12QIDAQABAoIBAA9Gphf65WLbcQY7
|
|
||||||
kTgiGdmR2oDZCtCRU5atSBHBE0mAgsMg1zkIIwZa4+1tjCRVsgvXO6g8InVcCUy+
|
|
||||||
JzGT4XoP4wRYF8e+Xhr0Rki0h9sF+PRAtirlPwQdAa/NOWXUZ//KQXiZGSixiZXz
|
|
||||||
hc1Rd02xe/94u35TwcoKxh6Z0fJBZwxSi2J72XnEWWQ71ru63RAp70JgxONMrcZ8
|
|
||||||
gHyqit8AN/kmzjT+LGsrw8SKJJTyD7/2Mtcn3QnfAB3+bFrwZPdcDlGIdDn/jmjx
|
|
||||||
sFbtxdug8zHVuI0EbGL6EHVGcgSWhp9FvZ9is2k08dmQdPLotOG8+vSfg9RCMZBT
|
|
||||||
50KrbOUCgYEA9nx8aWsML/0fQisWyN4JTtjqKy6ZizrdfLTktmHCl0OO3gvUQoIH
|
|
||||||
1KHSzlIBIKsC0utQEbM1pszh8aXFBH8bg/x1RrZigT9bTTzTrOfmsIL7Hg+AR/iv
|
|
||||||
GC1LszZdmB2kwaquKgUilfAz6ZCBgkZ5RwpcvmNdoqLfmNlcpQMs95UCgYEA8/Od
|
|
||||||
ro3GRXyq8hZz7LpgOx33XpLtD3Fj4z00TIJqKZAGcsHrlJw/wDHbMQqkdpCSu673
|
|
||||||
TLb67vXLyjyXuOXGCbIsKJpT3Ach5DxwceUnwg3OHWoreuCwyklHjIz9xwGecvpZ
|
|
||||||
qzDN9t/6IoTLlGXEZ28+hoXMDXJQtMq85lpy5DUCgYAu36eNKJVNvvYl0CnqEwd0
|
|
||||||
Hh4SDi+W4Z/jKkdgQ6EMwQU3RsqbxzyT/B4prECYpMzJrYQxiYIHcWj6WkroOv/R
|
|
||||||
jr4Cr4Z2C8ViH9IlTIh7Qr1cjxgXF7y8fUirEQild+WwCrRKO2XDW8WTgi6OxrYj
|
|
||||||
g131utHArvaUi6lpm/v+LQKBgQDVmIqJmWzuzndGvE4ICi/T0ysSTYbvLJMPFjnC
|
|
||||||
e7XEamya8hv45M4U1BJdYDob7f3sAwhYzSXtMJ2cl20o4VaCitSLQIUIc95C3oB9
|
|
||||||
2Oz0xe2gZ6NmVXG1zG+vKovRQSOg/H6im3rbG8UBkFBHwMs03XxbgK7nXx43DgRT
|
|
||||||
lQJfuQKBgQDxLjiwU9nYonBoiwUx8vfB3RGuoPgmVCGh9tEy+nyXxOu0imvx/Mbz
|
|
||||||
DP7PGP9+mG1HxcbAevlGD3tTTLimSTx+UIXIslgX+gY3KRv04PrDv8u44crA8Raf
|
|
||||||
3+sg7ASi8drli7EE6+UdloAR59UjKHOcW23EOS18/v999CnXAuFEqg==
|
|
||||||
-----END RSA PRIVATE KEY-----
|
|
||||||
+1226
-1226
File diff suppressed because it is too large
Load Diff
+743
-743
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -2,7 +2,7 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""抓包工具安装包下载
|
"""抓包工具安装包下载
|
||||||
|
|
||||||
安装包体积较大(约 160MB),放在项目根的 downloads/ 目录而不是 static/,
|
安装包体积较大(约 25MB),放在项目根的 downloads/ 目录而不是 static/,
|
||||||
避免被 Flask 静态路由以外的缓存策略干扰,也便于单独替换升级。
|
避免被 Flask 静态路由以外的缓存策略干扰,也便于单独替换升级。
|
||||||
|
|
||||||
公开访问:用户注册前就需要拿到工具,若加登录校验会形成「没工具拿不到凭据、
|
公开访问:用户注册前就需要拿到工具,若加登录校验会形成「没工具拿不到凭据、
|
||||||
@@ -18,7 +18,7 @@ bp = Blueprint("download", __name__)
|
|||||||
# 容易出编码问题。对外的下载文件名由 download_name 还原。
|
# 容易出编码问题。对外的下载文件名由 download_name 还原。
|
||||||
DOWNLOADS_DIR = Path(__file__).parent.parent / "downloads"
|
DOWNLOADS_DIR = Path(__file__).parent.parent / "downloads"
|
||||||
CAPTURE_TOOL_FILE = "xbniu-capture-tool.exe"
|
CAPTURE_TOOL_FILE = "xbniu-capture-tool.exe"
|
||||||
CAPTURE_TOOL_NAME = "小白超人抓包工具(新版).exe"
|
CAPTURE_TOOL_NAME = "HeaderCapture.exe"
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/download/capture-tool.exe", methods=["GET", "HEAD"])
|
@bp.route("/download/capture-tool.exe", methods=["GET", "HEAD"])
|
||||||
|
|||||||
+412
-412
@@ -1,412 +1,412 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""地图数据、寻车、分析等路由"""
|
"""地图数据、寻车、分析等路由"""
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
import hashlib
|
import hashlib
|
||||||
import threading
|
import threading
|
||||||
import asyncio
|
import asyncio
|
||||||
import aiohttp
|
import aiohttp
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from flask import Blueprint, current_app, jsonify, request, render_template
|
from flask import Blueprint, current_app, jsonify, request, render_template
|
||||||
|
|
||||||
from db import get_db, get_user_display_name, get_user_auth
|
from db import get_db, get_user_display_name, get_user_auth
|
||||||
from routes.auth import get_current_user
|
from routes.auth import get_current_user
|
||||||
from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS
|
from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS
|
||||||
|
|
||||||
bp = Blueprint("map_api", __name__)
|
bp = Blueprint("map_api", __name__)
|
||||||
|
|
||||||
# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放
|
# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放
|
||||||
BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
|
BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
|
||||||
|
|
||||||
# 并行寻车任务
|
# 并行寻车任务
|
||||||
ring_tasks: dict = {}
|
ring_tasks: dict = {}
|
||||||
_ring_lock = threading.Lock()
|
_ring_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
async def ring_single_bike_async(session, bike_code, school_id=10):
|
async def ring_single_bike_async(session, bike_code, school_id=10):
|
||||||
try:
|
try:
|
||||||
headers = {**SEARCH_HEADERS, **get_signature_headers()}
|
headers = {**SEARCH_HEADERS, **get_signature_headers()}
|
||||||
async with session.post(
|
async with session.post(
|
||||||
SEARCH_BIKE_URL,
|
SEARCH_BIKE_URL,
|
||||||
json={"code": bike_code, "school_id": school_id},
|
json={"code": bike_code, "school_id": school_id},
|
||||||
headers=headers,
|
headers=headers,
|
||||||
timeout=aiohttp.ClientTimeout(total=5)
|
timeout=aiohttp.ClientTimeout(total=5)
|
||||||
) as resp:
|
) as resp:
|
||||||
data = await resp.json()
|
data = await resp.json()
|
||||||
return data.get("rtn_code") == 0 or data.get("success") is True
|
return data.get("rtn_code") == 0 or data.get("success") is True
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def run_ring_task(task_id: str):
|
def run_ring_task(task_id: str):
|
||||||
global ring_tasks
|
global ring_tasks
|
||||||
task = ring_tasks.get(task_id)
|
task = ring_tasks.get(task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return
|
return
|
||||||
bikes = task["bikes"]
|
bikes = task["bikes"]
|
||||||
total = len(bikes)
|
total = len(bikes)
|
||||||
task["total"] = total
|
task["total"] = total
|
||||||
loop = asyncio.new_event_loop()
|
loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(loop)
|
asyncio.set_event_loop(loop)
|
||||||
connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop)
|
connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop)
|
||||||
try:
|
try:
|
||||||
async def run_session():
|
async def run_session():
|
||||||
semaphore = asyncio.Semaphore(20)
|
semaphore = asyncio.Semaphore(20)
|
||||||
async with aiohttp.ClientSession(connector=connector) as session:
|
async with aiohttp.ClientSession(connector=connector) as session:
|
||||||
async def ring_one(idx, code):
|
async def ring_one(idx, code):
|
||||||
async with semaphore:
|
async with semaphore:
|
||||||
if task["cancelled"]:
|
if task["cancelled"]:
|
||||||
return False
|
return False
|
||||||
result = await ring_single_bike_async(session, code, 10)
|
result = await ring_single_bike_async(session, code, 10)
|
||||||
with _ring_lock:
|
with _ring_lock:
|
||||||
task["done"] += 1
|
task["done"] += 1
|
||||||
if result:
|
if result:
|
||||||
task["success"] += 1
|
task["success"] += 1
|
||||||
else:
|
else:
|
||||||
task["failed"] += 1
|
task["failed"] += 1
|
||||||
task["last_update"] = time.time()
|
task["last_update"] = time.time()
|
||||||
return result
|
return result
|
||||||
batch_size = 20
|
batch_size = 20
|
||||||
for i in range(0, len(bikes), batch_size):
|
for i in range(0, len(bikes), batch_size):
|
||||||
if task["cancelled"]:
|
if task["cancelled"]:
|
||||||
break
|
break
|
||||||
batch = bikes[i:i + batch_size]
|
batch = bikes[i:i + batch_size]
|
||||||
await asyncio.gather(
|
await asyncio.gather(
|
||||||
*[ring_one(i + j, b["code"]) for j, b in enumerate(batch)],
|
*[ring_one(i + j, b["code"]) for j, b in enumerate(batch)],
|
||||||
return_exceptions=True
|
return_exceptions=True
|
||||||
)
|
)
|
||||||
await asyncio.sleep(0.1)
|
await asyncio.sleep(0.1)
|
||||||
loop.run_until_complete(run_session())
|
loop.run_until_complete(run_session())
|
||||||
finally:
|
finally:
|
||||||
with _ring_lock:
|
with _ring_lock:
|
||||||
task["status"] = "completed" if not task["cancelled"] else "cancelled"
|
task["status"] = "completed" if not task["cancelled"] else "cancelled"
|
||||||
task["done"] = total
|
task["done"] = total
|
||||||
loop.close()
|
loop.close()
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/ring_all", methods=["POST"])
|
@bp.route("/api/ring_all", methods=["POST"])
|
||||||
def api_ring_all():
|
def api_ring_all():
|
||||||
global ring_tasks
|
global ring_tasks
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||||
if user["email"] not in BATCH_RING_ALLOWED_EMAILS:
|
if user["email"] not in BATCH_RING_ALLOWED_EMAILS:
|
||||||
return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"})
|
return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"})
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
codes = data.get("codes", [])
|
codes = data.get("codes", [])
|
||||||
if isinstance(codes, str):
|
if isinstance(codes, str):
|
||||||
codes = [codes]
|
codes = [codes]
|
||||||
if not codes:
|
if not codes:
|
||||||
return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"})
|
return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"})
|
||||||
user_name = get_user_display_name(user["id"])
|
user_name = get_user_display_name(user["id"])
|
||||||
print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}")
|
print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}")
|
||||||
task_id = str(uuid.uuid4())[:8]
|
task_id = str(uuid.uuid4())[:8]
|
||||||
task = {
|
task = {
|
||||||
"status": "running", "total": len(codes), "done": 0,
|
"status": "running", "total": len(codes), "done": 0,
|
||||||
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
|
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
|
||||||
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
|
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
|
||||||
}
|
}
|
||||||
with _ring_lock:
|
with _ring_lock:
|
||||||
ring_tasks[task_id] = task
|
ring_tasks[task_id] = task
|
||||||
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
|
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
|
||||||
t.start()
|
t.start()
|
||||||
return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes),
|
return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes),
|
||||||
"message": f"任务已启动,共 {len(codes)} 辆车"})
|
"message": f"任务已启动,共 {len(codes)} 辆车"})
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/ring_status/<task_id>")
|
@bp.route("/api/ring_status/<task_id>")
|
||||||
def api_ring_status(task_id):
|
def api_ring_status(task_id):
|
||||||
with _ring_lock:
|
with _ring_lock:
|
||||||
task = ring_tasks.get(task_id)
|
task = ring_tasks.get(task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||||
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
|
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
|
||||||
"done": task["done"], "success": task["success"], "failed": task["failed"]})
|
"done": task["done"], "success": task["success"], "failed": task["failed"]})
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
|
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
|
||||||
def api_ring_cancel(task_id):
|
def api_ring_cancel(task_id):
|
||||||
with _ring_lock:
|
with _ring_lock:
|
||||||
task = ring_tasks.get(task_id)
|
task = ring_tasks.get(task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||||
if task["status"] != "running":
|
if task["status"] != "running":
|
||||||
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
|
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
|
||||||
task["cancelled"] = True
|
task["cancelled"] = True
|
||||||
task["status"] = "cancelling"
|
task["status"] = "cancelling"
|
||||||
return jsonify({"rtn_code": 0, "message": "取消请求已发送"})
|
return jsonify({"rtn_code": 0, "message": "取消请求已发送"})
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/ring_progress/<task_id>")
|
@bp.route("/api/ring_progress/<task_id>")
|
||||||
def api_ring_progress(task_id):
|
def api_ring_progress(task_id):
|
||||||
from flask import Response as FlaskResponse
|
from flask import Response as FlaskResponse
|
||||||
global ring_tasks
|
global ring_tasks
|
||||||
def _sse(obj):
|
def _sse(obj):
|
||||||
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
||||||
def generate():
|
def generate():
|
||||||
last_done = -1
|
last_done = -1
|
||||||
last_status = None
|
last_status = None
|
||||||
tick = 0
|
tick = 0
|
||||||
while True:
|
while True:
|
||||||
with _ring_lock:
|
with _ring_lock:
|
||||||
task = ring_tasks.get(task_id)
|
task = ring_tasks.get(task_id)
|
||||||
if not task:
|
if not task:
|
||||||
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
|
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
|
||||||
yield _sse({"type": "error", "message": "任务不存在或已结束"})
|
yield _sse({"type": "error", "message": "任务不存在或已结束"})
|
||||||
return
|
return
|
||||||
done = task["done"]
|
done = task["done"]
|
||||||
status = task["status"]
|
status = task["status"]
|
||||||
if done != last_done or status != last_status:
|
if done != last_done or status != last_status:
|
||||||
last_done = done
|
last_done = done
|
||||||
last_status = status
|
last_status = status
|
||||||
yield _sse({
|
yield _sse({
|
||||||
"type": "progress",
|
"type": "progress",
|
||||||
"status": status,
|
"status": status,
|
||||||
"done": done,
|
"done": done,
|
||||||
"total": task["total"],
|
"total": task["total"],
|
||||||
"success": task["success"],
|
"success": task["success"],
|
||||||
"failed": task["failed"],
|
"failed": task["failed"],
|
||||||
})
|
})
|
||||||
if status in ("completed", "cancelled"):
|
if status in ("completed", "cancelled"):
|
||||||
# 已结束,补发一条 done 事件后关闭
|
# 已结束,补发一条 done 事件后关闭
|
||||||
yield _sse({"type": "done", "status": status})
|
yield _sse({"type": "done", "status": status})
|
||||||
return
|
return
|
||||||
tick += 1
|
tick += 1
|
||||||
if tick >= 20: # 约 10s 一次心跳,避免代理/连接超时被判定为断开
|
if tick >= 20: # 约 10s 一次心跳,避免代理/连接超时被判定为断开
|
||||||
tick = 0
|
tick = 0
|
||||||
yield ": ping\n\n"
|
yield ": ping\n\n"
|
||||||
time.sleep(0.5)
|
time.sleep(0.5)
|
||||||
return FlaskResponse(
|
return FlaskResponse(
|
||||||
generate(),
|
generate(),
|
||||||
mimetype="text/event-stream",
|
mimetype="text/event-stream",
|
||||||
headers={
|
headers={
|
||||||
"Cache-Control": "no-cache",
|
"Cache-Control": "no-cache",
|
||||||
"Connection": "keep-alive",
|
"Connection": "keep-alive",
|
||||||
"X-Accel-Buffering": "no",
|
"X-Accel-Buffering": "no",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
|
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
|
||||||
def api_ring_status_clear(task_id):
|
def api_ring_status_clear(task_id):
|
||||||
with _ring_lock:
|
with _ring_lock:
|
||||||
ring_tasks.pop(task_id, None)
|
ring_tasks.pop(task_id, None)
|
||||||
return jsonify({"rtn_code": 0, "message": "已清除"})
|
return jsonify({"rtn_code": 0, "message": "已清除"})
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/map")
|
@bp.route("/api/map")
|
||||||
def api_map():
|
def api_map():
|
||||||
# 非登录人员不能使用:地图数据需登录后查看
|
# 非登录人员不能使用:地图数据需登录后查看
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||||
bike_type = request.args.get("type", "1").strip()
|
bike_type = request.args.get("type", "1").strip()
|
||||||
from map_cache import MAP_TYPES
|
from map_cache import MAP_TYPES
|
||||||
if bike_type not in MAP_TYPES:
|
if bike_type not in MAP_TYPES:
|
||||||
return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400
|
return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400
|
||||||
result = request_api("GET", "/project/map", params={"type": bike_type})
|
result = request_api("GET", "/project/map", params={"type": bike_type})
|
||||||
# 上游错误文案统一翻译(成功响应原样透传)
|
# 上游错误文案统一翻译(成功响应原样透传)
|
||||||
if result.get("rtn_code") not in (None, 0):
|
if result.get("rtn_code") not in (None, 0):
|
||||||
from wechat import friendly_upstream_message
|
from wechat import friendly_upstream_message
|
||||||
result = {**result,
|
result = {**result,
|
||||||
"message": friendly_upstream_message(result.get("message", ""))}
|
"message": friendly_upstream_message(result.get("message", ""))}
|
||||||
response = jsonify(result)
|
response = jsonify(result)
|
||||||
# Only the server snapshot is cached; browsers must ask the server on refresh.
|
# Only the server snapshot is cached; browsers must ask the server on refresh.
|
||||||
response.headers["Cache-Control"] = "private, no-store"
|
response.headers["Cache-Control"] = "private, no-store"
|
||||||
response.headers["Vary"] = "Authorization"
|
response.headers["Vary"] = "Authorization"
|
||||||
response.headers["X-Map-Server-Time"] = str(time.time())
|
response.headers["X-Map-Server-Time"] = str(time.time())
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/bicycle", methods=["GET", "POST"])
|
@bp.route("/api/bicycle", methods=["GET", "POST"])
|
||||||
def api_bicycle():
|
def api_bicycle():
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
code = data.get("code", "")
|
code = data.get("code", "")
|
||||||
if not code:
|
if not code:
|
||||||
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
|
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
|
||||||
user_name = get_user_display_name(user["id"])
|
user_name = get_user_display_name(user["id"])
|
||||||
print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}")
|
print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}")
|
||||||
result = request_api("POST", "/project/bicycle", data={"code": code})
|
result = request_api("POST", "/project/bicycle", data={"code": code})
|
||||||
if result.get("rtn_code") not in (None, 0):
|
if result.get("rtn_code") not in (None, 0):
|
||||||
from wechat import friendly_upstream_message
|
from wechat import friendly_upstream_message
|
||||||
result = {**result,
|
result = {**result,
|
||||||
"message": friendly_upstream_message(result.get("message", ""))}
|
"message": friendly_upstream_message(result.get("message", ""))}
|
||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/find_bike", methods=["POST"])
|
@bp.route("/api/find_bike", methods=["POST"])
|
||||||
def api_find_bike():
|
def api_find_bike():
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
keyword = (data.get("keyword") or data.get("code") or "").strip()
|
keyword = (data.get("keyword") or data.get("code") or "").strip()
|
||||||
if not keyword:
|
if not keyword:
|
||||||
return jsonify({"rtn_code": 400, "message": "缺少关键字"})
|
return jsonify({"rtn_code": 400, "message": "缺少关键字"})
|
||||||
school_id = data.get("school_id", 10)
|
school_id = data.get("school_id", 10)
|
||||||
result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id})
|
result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id})
|
||||||
if result.get("rtn_code") not in (None, 0):
|
if result.get("rtn_code") not in (None, 0):
|
||||||
from wechat import friendly_upstream_message
|
from wechat import friendly_upstream_message
|
||||||
result = {**result,
|
result = {**result,
|
||||||
"message": friendly_upstream_message(result.get("message", ""))}
|
"message": friendly_upstream_message(result.get("message", ""))}
|
||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/config")
|
@bp.route("/api/config")
|
||||||
def api_config():
|
def api_config():
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"center_lat": 36.531820, "center_lng": 116.780180,
|
"center_lat": 36.531820, "center_lng": 116.780180,
|
||||||
"scale": 17, "school_name": "山东管理学院",
|
"scale": 17, "school_name": "山东管理学院",
|
||||||
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
|
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
|
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
|
||||||
@bp.route("/api/map/freshness")
|
@bp.route("/api/map/freshness")
|
||||||
def api_map_freshness():
|
def api_map_freshness():
|
||||||
"""优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。
|
"""优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。
|
||||||
|
|
||||||
只读取缓存元数据,不会为了查询时间额外请求上游。
|
只读取缓存元数据,不会为了查询时间额外请求上游。
|
||||||
"""
|
"""
|
||||||
from map_cache import shared_map_cache
|
from map_cache import shared_map_cache
|
||||||
snapshot = shared_map_cache.freshness(request.args.get("type", "3"))
|
snapshot = shared_map_cache.freshness(request.args.get("type", "3"))
|
||||||
if snapshot is not None:
|
if snapshot is not None:
|
||||||
response = jsonify({"rtn_code": 0, "data": snapshot})
|
response = jsonify({"rtn_code": 0, "data": snapshot})
|
||||||
response.headers["Cache-Control"] = "no-store"
|
response.headers["Cache-Control"] = "no-store"
|
||||||
return response
|
return response
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone()
|
"SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone()
|
||||||
conn.close()
|
conn.close()
|
||||||
latest = row["latest"] if row else None
|
latest = row["latest"] if row else None
|
||||||
if not latest:
|
if not latest:
|
||||||
return jsonify({"rtn_code": 0, "data": {
|
return jsonify({"rtn_code": 0, "data": {
|
||||||
"latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}})
|
"latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}})
|
||||||
|
|
||||||
import datetime as dt
|
import datetime as dt
|
||||||
import sqlite3
|
import sqlite3
|
||||||
# recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源
|
# recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源
|
||||||
try:
|
try:
|
||||||
naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S")
|
naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S")
|
||||||
latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
|
latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
|
||||||
now = dt.datetime.now(latest_dt.tzinfo)
|
now = dt.datetime.now(latest_dt.tzinfo)
|
||||||
stale = max(0, int((now - latest_dt).total_seconds()))
|
stale = max(0, int((now - latest_dt).total_seconds()))
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
return jsonify({"rtn_code": 0, "data": {
|
return jsonify({"rtn_code": 0, "data": {
|
||||||
"latest": str(latest), "stale_seconds": None,
|
"latest": str(latest), "stale_seconds": None,
|
||||||
"interval_hint": "时间格式异常"}})
|
"interval_hint": "时间格式异常"}})
|
||||||
|
|
||||||
hint = "白天 5-10 分钟 / 夜间 30-60 分钟"
|
hint = "白天 5-10 分钟 / 夜间 30-60 分钟"
|
||||||
return jsonify({"rtn_code": 0, "data": {
|
return jsonify({"rtn_code": 0, "data": {
|
||||||
"latest": str(latest), "stale_seconds": stale, "interval_hint": hint}})
|
"latest": str(latest), "stale_seconds": stale, "interval_hint": hint}})
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/campus/locations")
|
@bp.route("/api/campus/locations")
|
||||||
def campus_locations():
|
def campus_locations():
|
||||||
"""校园地点(单点模型)。
|
"""校园地点(单点模型)。
|
||||||
|
|
||||||
- kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」;
|
- kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」;
|
||||||
- kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。
|
- kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。
|
||||||
|
|
||||||
返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。
|
返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。
|
||||||
"""
|
"""
|
||||||
from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations
|
from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations
|
||||||
result = []
|
result = []
|
||||||
for loc in load_locations():
|
for loc in load_locations():
|
||||||
item = {
|
item = {
|
||||||
"id": loc["id"],
|
"id": loc["id"],
|
||||||
"name": loc["name"],
|
"name": loc["name"],
|
||||||
"kind": loc.get("kind") or "poi",
|
"kind": loc.get("kind") or "poi",
|
||||||
"latitude": loc.get("latitude"),
|
"latitude": loc.get("latitude"),
|
||||||
"longitude": loc.get("longitude"),
|
"longitude": loc.get("longitude"),
|
||||||
"radius": loc.get("radius") or (
|
"radius": loc.get("radius") or (
|
||||||
DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None),
|
DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None),
|
||||||
"bd09": None,
|
"bd09": None,
|
||||||
}
|
}
|
||||||
if loc.get("latitude") is not None and loc.get("longitude") is not None:
|
if loc.get("latitude") is not None and loc.get("longitude") is not None:
|
||||||
bd = gcj02_to_bd09(loc["longitude"], loc["latitude"])
|
bd = gcj02_to_bd09(loc["longitude"], loc["latitude"])
|
||||||
item["bd09"] = {"lat": bd[1], "lng": bd[0]}
|
item["bd09"] = {"lat": bd[1], "lng": bd[0]}
|
||||||
result.append(item)
|
result.append(item)
|
||||||
return jsonify({"rtn_code": 0, "data": result})
|
return jsonify({"rtn_code": 0, "data": result})
|
||||||
|
|
||||||
|
|
||||||
# ========== 用户信息 API ==========
|
# ========== 用户信息 API ==========
|
||||||
@bp.route("/api/user/info")
|
@bp.route("/api/user/info")
|
||||||
def api_user_info():
|
def api_user_info():
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||||
|
|
||||||
from wechat import request_with_user_auth
|
from wechat import request_with_user_auth
|
||||||
token_id, access_token = get_user_auth(user["id"])
|
token_id, access_token = get_user_auth(user["id"])
|
||||||
if not token_id:
|
if not token_id:
|
||||||
return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"})
|
return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"})
|
||||||
|
|
||||||
result = request_with_user_auth(user["id"], "GET", "/user/info")
|
result = request_with_user_auth(user["id"], "GET", "/user/info")
|
||||||
if result.get("rtn_code") != 0:
|
if result.get("rtn_code") != 0:
|
||||||
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")})
|
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")})
|
||||||
|
|
||||||
data = result.get("data", {})
|
data = result.get("data", {})
|
||||||
non_deal = data.get("nonDealOrder")
|
non_deal = data.get("nonDealOrder")
|
||||||
true_name = ""
|
true_name = ""
|
||||||
account = data.get("account", {})
|
account = data.get("account", {})
|
||||||
if isinstance(account, str):
|
if isinstance(account, str):
|
||||||
try:
|
try:
|
||||||
account = json.loads(account)
|
account = json.loads(account)
|
||||||
except Exception:
|
except Exception:
|
||||||
account = {}
|
account = {}
|
||||||
true_name = account.get("trueName", "") if isinstance(account, dict) else ""
|
true_name = account.get("trueName", "") if isinstance(account, dict) else ""
|
||||||
|
|
||||||
out_money = data.get("bus_account", {}).get("outMoneyBus", 0)
|
out_money = data.get("bus_account", {}).get("outMoneyBus", 0)
|
||||||
save_money = data.get("bus_account", {}).get("saveMoneyBus", 0)
|
save_money = data.get("bus_account", {}).get("saveMoneyBus", 0)
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"rtn_code": 0, "has_auth": True,
|
"rtn_code": 0, "has_auth": True,
|
||||||
"data": {
|
"data": {
|
||||||
"true_name": true_name, "out_money": out_money,
|
"true_name": true_name, "out_money": out_money,
|
||||||
"save_money": save_money, "has_auth": True,
|
"save_money": save_money, "has_auth": True,
|
||||||
"nonDealOrder": non_deal,
|
"nonDealOrder": non_deal,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
# ========== 首页路由 ==========
|
# ========== 首页路由 ==========
|
||||||
MAP_ASSETS = (
|
MAP_ASSETS = (
|
||||||
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
|
"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/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
|
||||||
"js/settings-pages.js", "js/map.js",
|
"js/settings-pages.js", "js/map.js",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _map_asset_version():
|
def _map_asset_version():
|
||||||
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
|
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
|
||||||
digest = hashlib.sha256()
|
digest = hashlib.sha256()
|
||||||
for filename in MAP_ASSETS:
|
for filename in MAP_ASSETS:
|
||||||
digest.update(filename.encode())
|
digest.update(filename.encode())
|
||||||
try:
|
try:
|
||||||
digest.update((Path(current_app.static_folder) / filename).read_bytes())
|
digest.update((Path(current_app.static_folder) / filename).read_bytes())
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
digest.update(b"missing")
|
digest.update(b"missing")
|
||||||
return digest.hexdigest()[:16]
|
return digest.hexdigest()[:16]
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/")
|
@bp.route("/")
|
||||||
def index():
|
def index():
|
||||||
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
|
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
|
||||||
response.headers["Cache-Control"] = "no-cache"
|
response.headers["Cache-Control"] = "no-cache"
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/analysis.html")
|
@bp.route("/analysis.html")
|
||||||
def analysis_page():
|
def analysis_page():
|
||||||
return render_template("analysis.html")
|
return render_template("analysis.html")
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/ring_progress.html")
|
@bp.route("/ring_progress.html")
|
||||||
def ring_progress():
|
def ring_progress():
|
||||||
return render_template("ring_progress.html")
|
return render_template("ring_progress.html")
|
||||||
|
|||||||
+1630
-1493
File diff suppressed because it is too large
Load Diff
+936
-932
File diff suppressed because it is too large
Load Diff
@@ -62,4 +62,4 @@ try {
|
|||||||
Write-Host "1.zip 完成:$($names.Count) 个文件,$sizeKB KB(仅源码与必要资源)"
|
Write-Host "1.zip 完成:$($names.Count) 个文件,$sizeKB KB(仅源码与必要资源)"
|
||||||
} finally {
|
} finally {
|
||||||
if (Test-Path -LiteralPath $pendingZip) { Remove-Item -LiteralPath $pendingZip -Force }
|
if (Test-Path -LiteralPath $pendingZip) { Remove-Item -LiteralPath $pendingZip -Force }
|
||||||
}
|
}
|
||||||
|
|||||||
+279
-279
@@ -1,279 +1,279 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""冒烟测试:验证应用可启动、路由无冲突、关键接口可响应。"""
|
"""冒烟测试:验证应用可启动、路由无冲突、关键接口可响应。"""
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根
|
||||||
|
|
||||||
# 注意: app.py 导入时会重新包装 sys.stdout, 这里不能自己再包一层,
|
# 注意: app.py 导入时会重新包装 sys.stdout, 这里不能自己再包一层,
|
||||||
# 否则旧包装器被 GC 时会关闭底层 buffer。编码由 PYTHONIOENCODING 控制。
|
# 否则旧包装器被 GC 时会关闭底层 buffer。编码由 PYTHONIOENCODING 控制。
|
||||||
_ORIG_STDOUT = sys.stdout # 持有引用, 防止被 GC 后关闭底层流
|
_ORIG_STDOUT = sys.stdout # 持有引用, 防止被 GC 后关闭底层流
|
||||||
|
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
|
||||||
PASS, FAIL = [], []
|
PASS, FAIL = [], []
|
||||||
|
|
||||||
|
|
||||||
def check(name, fn):
|
def check(name, fn):
|
||||||
try:
|
try:
|
||||||
detail = fn()
|
detail = fn()
|
||||||
PASS.append((name, detail))
|
PASS.append((name, detail))
|
||||||
print(f" [PASS] {name}" + (f" — {detail}" if detail else ""))
|
print(f" [PASS] {name}" + (f" — {detail}" if detail else ""))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
FAIL.append((name, f"{type(e).__name__}: {e}"))
|
FAIL.append((name, f"{type(e).__name__}: {e}"))
|
||||||
print(f" [FAIL] {name} — {type(e).__name__}: {e}")
|
print(f" [FAIL] {name} — {type(e).__name__}: {e}")
|
||||||
|
|
||||||
|
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("1) 模块导入检查")
|
print("1) 模块导入检查")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
|
|
||||||
def import_app():
|
def import_app():
|
||||||
import app as app_module
|
import app as app_module
|
||||||
return f"app 模块导入成功, 蓝图 {len(app_module.app.blueprints)} 个: {', '.join(app_module.app.blueprints)}"
|
return f"app 模块导入成功, 蓝图 {len(app_module.app.blueprints)} 个: {', '.join(app_module.app.blueprints)}"
|
||||||
|
|
||||||
|
|
||||||
check("导入 app.py 及全部依赖 (db/wechat/timer/routes.*)", import_app)
|
check("导入 app.py 及全部依赖 (db/wechat/timer/routes.*)", import_app)
|
||||||
|
|
||||||
|
|
||||||
def import_side_modules():
|
def import_side_modules():
|
||||||
import rental_mail, email_utils, generate_icons # noqa: F401
|
import rental_mail, email_utils, generate_icons # noqa: F401
|
||||||
return "rental_mail / email_utils / generate_icons 导入成功"
|
return "rental_mail / email_utils / generate_icons 导入成功"
|
||||||
|
|
||||||
|
|
||||||
check("导入其余业务模块", import_side_modules)
|
check("导入其余业务模块", import_side_modules)
|
||||||
|
|
||||||
app_obj = None
|
app_obj = None
|
||||||
try:
|
try:
|
||||||
import app as app_module
|
import app as app_module
|
||||||
app_obj = app_module.app
|
app_obj = app_module.app
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
print()
|
print()
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("2) 路由冲突检查")
|
print("2) 路由冲突检查")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
|
|
||||||
def route_conflicts():
|
def route_conflicts():
|
||||||
rules = defaultdict(list)
|
rules = defaultdict(list)
|
||||||
for r in app_obj.url_map.iter_rules():
|
for r in app_obj.url_map.iter_rules():
|
||||||
if r.endpoint == "static":
|
if r.endpoint == "static":
|
||||||
continue
|
continue
|
||||||
methods = sorted(m for m in r.methods if m not in ("HEAD", "OPTIONS"))
|
methods = sorted(m for m in r.methods if m not in ("HEAD", "OPTIONS"))
|
||||||
for m in methods:
|
for m in methods:
|
||||||
rules[(m, r.rule)].append(r.endpoint)
|
rules[(m, r.rule)].append(r.endpoint)
|
||||||
dupes = {k: v for k, v in rules.items() if len(v) > 1}
|
dupes = {k: v for k, v in rules.items() if len(v) > 1}
|
||||||
if dupes:
|
if dupes:
|
||||||
raise AssertionError(f"发现 {len(dupes)} 处路由冲突: {dupes}")
|
raise AssertionError(f"发现 {len(dupes)} 处路由冲突: {dupes}")
|
||||||
return f"共 {len(rules)} 条 (method, path) 规则, 无重复注册"
|
return f"共 {len(rules)} 条 (method, path) 规则, 无重复注册"
|
||||||
|
|
||||||
|
|
||||||
check("检查重复路由 (Flask 静默覆盖, 需显式检测)", route_conflicts)
|
check("检查重复路由 (Flask 静默覆盖, 需显式检测)", route_conflicts)
|
||||||
|
|
||||||
|
|
||||||
def route_summary():
|
def route_summary():
|
||||||
rules = sorted(r.rule for r in app_obj.url_map.iter_rules() if r.endpoint != "static")
|
rules = sorted(r.rule for r in app_obj.url_map.iter_rules() if r.endpoint != "static")
|
||||||
return f"{len(rules)} 条路由"
|
return f"{len(rules)} 条路由"
|
||||||
|
|
||||||
|
|
||||||
check("路由注册成功", route_summary)
|
check("路由注册成功", route_summary)
|
||||||
|
|
||||||
print()
|
print()
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("3) 数据库连通性")
|
print("3) 数据库连通性")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
|
|
||||||
def db_check():
|
def db_check():
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
p = Path("users.db")
|
p = Path("users.db")
|
||||||
if not p.exists():
|
if not p.exists():
|
||||||
raise AssertionError("users.db 不存在")
|
raise AssertionError("users.db 不存在")
|
||||||
conn = sqlite3.connect(str(p))
|
conn = sqlite3.connect(str(p))
|
||||||
conn.row_factory = sqlite3.Row
|
conn.row_factory = sqlite3.Row
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
tables = [r[0] for r in cur.execute(
|
tables = [r[0] for r in cur.execute(
|
||||||
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
|
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
|
||||||
counts = {}
|
counts = {}
|
||||||
for t in ("users", "rentals", "bike_history", "sessions"):
|
for t in ("users", "rentals", "bike_history", "sessions"):
|
||||||
if t in tables:
|
if t in tables:
|
||||||
counts[t] = cur.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
|
counts[t] = cur.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
|
||||||
cur.execute("PRAGMA integrity_check")
|
cur.execute("PRAGMA integrity_check")
|
||||||
integrity = cur.fetchone()[0]
|
integrity = cur.fetchone()[0]
|
||||||
conn.close()
|
conn.close()
|
||||||
if integrity != "ok":
|
if integrity != "ok":
|
||||||
raise AssertionError(f"数据库完整性异常: {integrity}")
|
raise AssertionError(f"数据库完整性异常: {integrity}")
|
||||||
return f"表 {len(tables)} 张, 行数: {counts}"
|
return f"表 {len(tables)} 张, 行数: {counts}"
|
||||||
|
|
||||||
|
|
||||||
check("users.db 完整性与核心表", db_check)
|
check("users.db 完整性与核心表", db_check)
|
||||||
|
|
||||||
|
|
||||||
def db_init_check():
|
def db_init_check():
|
||||||
"""init_db() 应可重复执行(幂等)而不报错 —— 用临时库验证。"""
|
"""init_db() 应可重复执行(幂等)而不报错 —— 用临时库验证。"""
|
||||||
import db, tempfile, os
|
import db, tempfile, os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
fd, tmp = tempfile.mkstemp(suffix=".db")
|
fd, tmp = tempfile.mkstemp(suffix=".db")
|
||||||
os.close(fd)
|
os.close(fd)
|
||||||
old = db.DB_PATH
|
old = db.DB_PATH
|
||||||
db.DB_PATH = Path(tmp)
|
db.DB_PATH = Path(tmp)
|
||||||
try:
|
try:
|
||||||
db.init_db()
|
db.init_db()
|
||||||
db.init_db() # 二次调用验证幂等
|
db.init_db() # 二次调用验证幂等
|
||||||
return "init_db 在临时库上执行两次均成功(幂等)"
|
return "init_db 在临时库上执行两次均成功(幂等)"
|
||||||
finally:
|
finally:
|
||||||
db.DB_PATH = old
|
db.DB_PATH = old
|
||||||
try:
|
try:
|
||||||
os.remove(tmp)
|
os.remove(tmp)
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
check("init_db 幂等性 (临时库)", db_init_check)
|
check("init_db 幂等性 (临时库)", db_init_check)
|
||||||
|
|
||||||
print()
|
print()
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("4) 模板与静态资源")
|
print("4) 模板与静态资源")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
|
|
||||||
def templates_check():
|
def templates_check():
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
tdir = Path("templates")
|
tdir = Path("templates")
|
||||||
files = sorted(p.name for p in tdir.glob("*.html"))
|
files = sorted(p.name for p in tdir.glob("*.html"))
|
||||||
if not files:
|
if not files:
|
||||||
raise AssertionError("templates 目录为空")
|
raise AssertionError("templates 目录为空")
|
||||||
return f"{len(files)} 个模板: {', '.join(files)}"
|
return f"{len(files)} 个模板: {', '.join(files)}"
|
||||||
|
|
||||||
|
|
||||||
check("模板文件存在", templates_check)
|
check("模板文件存在", templates_check)
|
||||||
|
|
||||||
|
|
||||||
def static_check():
|
def static_check():
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
sdir = Path("static")
|
sdir = Path("static")
|
||||||
total = sum(1 for _ in sdir.rglob("*") if _.is_file())
|
total = sum(1 for _ in sdir.rglob("*") if _.is_file())
|
||||||
if total == 0:
|
if total == 0:
|
||||||
raise AssertionError("static 目录为空")
|
raise AssertionError("static 目录为空")
|
||||||
return f"{total} 个静态文件"
|
return f"{total} 个静态文件"
|
||||||
|
|
||||||
|
|
||||||
check("静态资源存在", static_check)
|
check("静态资源存在", static_check)
|
||||||
|
|
||||||
print()
|
print()
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("5) 关键接口冒烟 (Flask test client, 不真正监听端口)")
|
print("5) 关键接口冒烟 (Flask test client, 不真正监听端口)")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
|
|
||||||
def client():
|
def client():
|
||||||
app_obj.config["TESTING"] = True
|
app_obj.config["TESTING"] = True
|
||||||
return app_obj.test_client()
|
return app_obj.test_client()
|
||||||
|
|
||||||
|
|
||||||
c = client()
|
c = client()
|
||||||
|
|
||||||
EXPECTED = {
|
EXPECTED = {
|
||||||
# (path): 说明。允许 200/3xx;404 属于页面/路由缺失
|
# (path): 说明。允许 200/3xx;404 属于页面/路由缺失
|
||||||
"/": "主页(地图)",
|
"/": "主页(地图)",
|
||||||
"/admin": "管理后台(未登录应跳转登录)",
|
"/admin": "管理后台(未登录应跳转登录)",
|
||||||
"/admin/login": "管理员登录页",
|
"/admin/login": "管理员登录页",
|
||||||
"/analysis.html": "数据分析页",
|
"/analysis.html": "数据分析页",
|
||||||
"/rental/email-return": "邮件还车页",
|
"/rental/email-return": "邮件还车页",
|
||||||
"/ring_progress.html": "寻车进度页",
|
"/ring_progress.html": "寻车进度页",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def page(path):
|
def page(path):
|
||||||
def fn():
|
def fn():
|
||||||
r = c.get(path)
|
r = c.get(path)
|
||||||
if r.status_code in (200, 301, 302, 304):
|
if r.status_code in (200, 301, 302, 304):
|
||||||
return f"{path} -> {r.status_code}"
|
return f"{path} -> {r.status_code}"
|
||||||
if r.status_code == 404:
|
if r.status_code == 404:
|
||||||
raise AssertionError(f"{path} -> 404 (页面/路由缺失)")
|
raise AssertionError(f"{path} -> 404 (页面/路由缺失)")
|
||||||
raise AssertionError(f"{path} -> {r.status_code}")
|
raise AssertionError(f"{path} -> {r.status_code}")
|
||||||
return fn
|
return fn
|
||||||
|
|
||||||
|
|
||||||
for path, name in EXPECTED.items():
|
for path, name in EXPECTED.items():
|
||||||
check(f"页面 {name} {path}", page(path))
|
check(f"页面 {name} {path}", page(path))
|
||||||
|
|
||||||
# API 类: 401/400 = 接口在且鉴权/校验正常; 404/500 = 有问题
|
# API 类: 401/400 = 接口在且鉴权/校验正常; 404/500 = 有问题
|
||||||
API_ALLOW = {200, 400, 401, 302, 301}
|
API_ALLOW = {200, 400, 401, 302, 301}
|
||||||
APIS = [
|
APIS = [
|
||||||
("/api/bike_history", "无参数应返回400"),
|
("/api/bike_history", "无参数应返回400"),
|
||||||
("/api/analysis/overview", "分析总览"),
|
("/api/analysis/overview", "分析总览"),
|
||||||
("/api/analysis/heatmap", "热力图"),
|
("/api/analysis/heatmap", "热力图"),
|
||||||
("/api/history/stats", "历史统计"),
|
("/api/history/stats", "历史统计"),
|
||||||
("/api/history/bikes", "历史车辆列表"),
|
("/api/history/bikes", "历史车辆列表"),
|
||||||
("/api/history/heatmap", "历史热力图"),
|
("/api/history/heatmap", "历史热力图"),
|
||||||
("/api/history/all_trajectory", "全量轨迹"),
|
("/api/history/all_trajectory", "全量轨迹"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def api(path):
|
def api(path):
|
||||||
def fn():
|
def fn():
|
||||||
r = c.get(path)
|
r = c.get(path)
|
||||||
if r.status_code in API_ALLOW:
|
if r.status_code in API_ALLOW:
|
||||||
return f"{path} -> {r.status_code}"
|
return f"{path} -> {r.status_code}"
|
||||||
raise AssertionError(f"{path} -> {r.status_code}")
|
raise AssertionError(f"{path} -> {r.status_code}")
|
||||||
return fn
|
return fn
|
||||||
|
|
||||||
|
|
||||||
for path, desc in APIS:
|
for path, desc in APIS:
|
||||||
check(f"API {desc} {path}", api(path))
|
check(f"API {desc} {path}", api(path))
|
||||||
|
|
||||||
|
|
||||||
def protected_api_check():
|
def protected_api_check():
|
||||||
"""未登录访问受保护接口应返回 401(或明确拒绝) 而不是 500/404"""
|
"""未登录访问受保护接口应返回 401(或明确拒绝) 而不是 500/404"""
|
||||||
paths = (
|
paths = (
|
||||||
"/api/auth/rental_settings", "/api/rental/status",
|
"/api/auth/rental_settings", "/api/rental/status",
|
||||||
"/api/share/active", "/api/auth/profile", "/api/order/status",
|
"/api/share/active", "/api/auth/profile", "/api/order/status",
|
||||||
)
|
)
|
||||||
for path in paths:
|
for path in paths:
|
||||||
r = c.get(path)
|
r = c.get(path)
|
||||||
if r.status_code == 404:
|
if r.status_code == 404:
|
||||||
raise AssertionError(f"{path} -> 404, 接口不存在")
|
raise AssertionError(f"{path} -> 404, 接口不存在")
|
||||||
if r.status_code >= 500:
|
if r.status_code >= 500:
|
||||||
raise AssertionError(f"{path} -> {r.status_code}, 服务端错误")
|
raise AssertionError(f"{path} -> {r.status_code}, 服务端错误")
|
||||||
if r.status_code == 200:
|
if r.status_code == 200:
|
||||||
body = r.get_json(silent=True) or {}
|
body = r.get_json(silent=True) or {}
|
||||||
if body.get("rtn_code") not in (401, 403):
|
if body.get("rtn_code") not in (401, 403):
|
||||||
raise AssertionError(
|
raise AssertionError(
|
||||||
f"{path} 未登录返回 200 且 rtn_code={body.get('rtn_code')}, 疑似未鉴权")
|
f"{path} 未登录返回 200 且 rtn_code={body.get('rtn_code')}, 疑似未鉴权")
|
||||||
return "受保护接口未登录时均正确拒绝(无 500/404/越权)"
|
return "受保护接口未登录时均正确拒绝(无 500/404/越权)"
|
||||||
|
|
||||||
|
|
||||||
check("受保护接口鉴权兜底", protected_api_check)
|
check("受保护接口鉴权兜底", protected_api_check)
|
||||||
|
|
||||||
|
|
||||||
def login_flow_check():
|
def login_flow_check():
|
||||||
"""登录接口对错误凭据应返回明确失败而非 500"""
|
"""登录接口对错误凭据应返回明确失败而非 500"""
|
||||||
r = c.post("/api/auth/login",
|
r = c.post("/api/auth/login",
|
||||||
json={"email": "smoke_nonexist@example.test", "password": "wrong"})
|
json={"email": "smoke_nonexist@example.test", "password": "wrong"})
|
||||||
if r.status_code >= 500:
|
if r.status_code >= 500:
|
||||||
raise AssertionError(f"/api/auth/login -> {r.status_code}")
|
raise AssertionError(f"/api/auth/login -> {r.status_code}")
|
||||||
body = r.get_json(silent=True) or {}
|
body = r.get_json(silent=True) or {}
|
||||||
if r.status_code == 200 and body.get("rtn_code") == 0:
|
if r.status_code == 200 and body.get("rtn_code") == 0:
|
||||||
raise AssertionError("错误凭据竟然登录成功!")
|
raise AssertionError("错误凭据竟然登录成功!")
|
||||||
return f"/api/auth/login 错误凭据 -> {r.status_code} rtn_code={body.get('rtn_code')} (拒绝正常)"
|
return f"/api/auth/login 错误凭据 -> {r.status_code} rtn_code={body.get('rtn_code')} (拒绝正常)"
|
||||||
|
|
||||||
|
|
||||||
check("登录接口错误凭据处理", login_flow_check)
|
check("登录接口错误凭据处理", login_flow_check)
|
||||||
|
|
||||||
print()
|
print()
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("冒烟测试结果汇总")
|
print("冒烟测试结果汇总")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print(f"通过: {len(PASS)} 失败: {len(FAIL)}")
|
print(f"通过: {len(PASS)} 失败: {len(FAIL)}")
|
||||||
if FAIL:
|
if FAIL:
|
||||||
print("\n失败项:")
|
print("\n失败项:")
|
||||||
for name, err in FAIL:
|
for name, err in FAIL:
|
||||||
print(f" - {name}: {err}")
|
print(f" - {name}: {err}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
print("全部通过 ✅")
|
print("全部通过 ✅")
|
||||||
|
|||||||
+2754
-2706
File diff suppressed because it is too large
Load Diff
+5378
-5347
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -12,7 +12,7 @@
|
|||||||
- 判定用最近 20 分钟内的采集点(每车取最新一条),坐标系与车辆一致(GCJ02)。
|
- 判定用最近 20 分钟内的采集点(每车取最新一条),坐标系与车辆一致(GCJ02)。
|
||||||
"""
|
"""
|
||||||
import datetime as dt
|
import datetime as dt
|
||||||
import math
|
import math
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import random
|
import random
|
||||||
import threading
|
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
+1009
-1003
File diff suppressed because it is too large
Load Diff
+259
-259
@@ -1,263 +1,263 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="zh">
|
<html lang="zh">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>全车寻铃进度</title>
|
<title>全车寻铃进度</title>
|
||||||
<style>
|
<style>
|
||||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
body {
|
body {
|
||||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
background: #1a1a2e;
|
background: #1a1a2e;
|
||||||
color: #eee;
|
color: #eee;
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
}
|
}
|
||||||
.container {
|
.container {
|
||||||
background: #16213e;
|
background: #16213e;
|
||||||
border-radius: 16px;
|
border-radius: 16px;
|
||||||
padding: 32px;
|
padding: 32px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 420px;
|
max-width: 420px;
|
||||||
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
|
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
|
||||||
}
|
}
|
||||||
.header {
|
.header {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
margin-bottom: 28px;
|
margin-bottom: 28px;
|
||||||
}
|
}
|
||||||
.header h1 {
|
.header h1 {
|
||||||
font-size: 22px;
|
font-size: 22px;
|
||||||
margin-bottom: 8px;
|
margin-bottom: 8px;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
}
|
}
|
||||||
.header p {
|
.header p {
|
||||||
color: #888;
|
color: #888;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
.stats {
|
.stats {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(3, 1fr);
|
grid-template-columns: repeat(3, 1fr);
|
||||||
gap: 12px;
|
gap: 12px;
|
||||||
margin-bottom: 24px;
|
margin-bottom: 24px;
|
||||||
}
|
}
|
||||||
.stat {
|
.stat {
|
||||||
background: #0f3460;
|
background: #0f3460;
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
padding: 16px 12px;
|
padding: 16px 12px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
.stat-value {
|
.stat-value {
|
||||||
font-size: 28px;
|
font-size: 28px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: #e94560;
|
color: #e94560;
|
||||||
}
|
}
|
||||||
.stat-value.success { color: #4ade80; }
|
.stat-value.success { color: #4ade80; }
|
||||||
.stat-value.failed { color: #f87171; }
|
.stat-value.failed { color: #f87171; }
|
||||||
.stat-label {
|
.stat-label {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #888;
|
color: #888;
|
||||||
margin-top: 4px;
|
margin-top: 4px;
|
||||||
}
|
}
|
||||||
.progress-bar {
|
.progress-bar {
|
||||||
background: #0f3460;
|
background: #0f3460;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
height: 20px;
|
height: 20px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
margin-bottom: 20px;
|
margin-bottom: 20px;
|
||||||
}
|
}
|
||||||
.progress-fill {
|
.progress-fill {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background: linear-gradient(90deg, #e94560, #ff6b6b);
|
background: linear-gradient(90deg, #e94560, #ff6b6b);
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
transition: width 0.2s ease;
|
transition: width 0.2s ease;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
padding-right: 8px;
|
padding-right: 8px;
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
min-width: 40px;
|
min-width: 40px;
|
||||||
}
|
}
|
||||||
.progress-fill.done { background: linear-gradient(90deg, #4ade80, #22c55e); }
|
.progress-fill.done { background: linear-gradient(90deg, #4ade80, #22c55e); }
|
||||||
.actions {
|
.actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 12px;
|
gap: 12px;
|
||||||
}
|
}
|
||||||
.btn {
|
.btn {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
padding: 14px;
|
padding: 14px;
|
||||||
border: none;
|
border: none;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: all 0.2s;
|
transition: all 0.2s;
|
||||||
}
|
}
|
||||||
.btn-cancel {
|
.btn-cancel {
|
||||||
background: #e94560;
|
background: #e94560;
|
||||||
color: white;
|
color: white;
|
||||||
}
|
}
|
||||||
.btn-cancel:hover { background: #d63850; }
|
.btn-cancel:hover { background: #d63850; }
|
||||||
.btn-close {
|
.btn-close {
|
||||||
background: #333;
|
background: #333;
|
||||||
color: #ccc;
|
color: #ccc;
|
||||||
}
|
}
|
||||||
.btn-close:hover { background: #444; }
|
.btn-close:hover { background: #444; }
|
||||||
.btn:disabled {
|
.btn:disabled {
|
||||||
opacity: 0.5;
|
opacity: 0.5;
|
||||||
cursor: not-allowed;
|
cursor: not-allowed;
|
||||||
}
|
}
|
||||||
.log {
|
.log {
|
||||||
margin-top: 20px;
|
margin-top: 20px;
|
||||||
background: #0a0a1a;
|
background: #0a0a1a;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
padding: 12px;
|
padding: 12px;
|
||||||
max-height: 120px;
|
max-height: 120px;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #888;
|
color: #888;
|
||||||
}
|
}
|
||||||
.log-entry { margin-bottom: 4px; }
|
.log-entry { margin-bottom: 4px; }
|
||||||
.log-entry.success { color: #4ade80; }
|
.log-entry.success { color: #4ade80; }
|
||||||
.log-entry.failed { color: #f87171; }
|
.log-entry.failed { color: #f87171; }
|
||||||
</style>
|
</style>
|
||||||
<link rel="stylesheet" href="/static/css/ui-system.css">
|
<link rel="stylesheet" href="/static/css/ui-system.css">
|
||||||
<script defer src="/static/js/ui-motion.js"></script>
|
<script defer src="/static/js/ui-motion.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="header">
|
<div class="header">
|
||||||
<h1>
|
<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>
|
<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>
|
</h1>
|
||||||
<p id="status-text">正在连接...</p>
|
<p id="status-text">正在连接...</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="stats">
|
<div class="stats">
|
||||||
<div class="stat">
|
<div class="stat">
|
||||||
<div class="stat-value" id="done-count">0</div>
|
<div class="stat-value" id="done-count">0</div>
|
||||||
<div class="stat-label">已完成</div>
|
<div class="stat-label">已完成</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat">
|
<div class="stat">
|
||||||
<div class="stat-value success" id="success-count">0</div>
|
<div class="stat-value success" id="success-count">0</div>
|
||||||
<div class="stat-label">成功</div>
|
<div class="stat-label">成功</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat">
|
<div class="stat">
|
||||||
<div class="stat-value failed" id="failed-count">0</div>
|
<div class="stat-value failed" id="failed-count">0</div>
|
||||||
<div class="stat-label">失败</div>
|
<div class="stat-label">失败</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="progress-bar">
|
<div class="progress-bar">
|
||||||
<div class="progress-fill" id="progress-fill" style="width: 0%">
|
<div class="progress-fill" id="progress-fill" style="width: 0%">
|
||||||
<span id="progress-text">0%</span>
|
<span id="progress-text">0%</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn btn-cancel" id="cancel-btn" onclick="cancelTask()">取消任务</button>
|
<button class="btn btn-cancel" id="cancel-btn" onclick="cancelTask()">取消任务</button>
|
||||||
<button class="btn btn-close" onclick="closeWindow()">关闭</button>
|
<button class="btn btn-close" onclick="closeWindow()">关闭</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="log" id="log"></div>
|
<div class="log" id="log"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const params = new URLSearchParams(window.location.search);
|
const params = new URLSearchParams(window.location.search);
|
||||||
const taskId = params.get('task_id');
|
const taskId = params.get('task_id');
|
||||||
const total = parseInt(params.get('total') || '0');
|
const total = parseInt(params.get('total') || '0');
|
||||||
|
|
||||||
document.getElementById('status-text').textContent = `共 ${total} 辆车`;
|
document.getElementById('status-text').textContent = `共 ${total} 辆车`;
|
||||||
|
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
let completed = false;
|
let completed = false;
|
||||||
|
|
||||||
function addLog(msg, type = '') {
|
function addLog(msg, type = '') {
|
||||||
const log = document.getElementById('log');
|
const log = document.getElementById('log');
|
||||||
const entry = document.createElement('div');
|
const entry = document.createElement('div');
|
||||||
entry.className = 'log-entry ' + type;
|
entry.className = 'log-entry ' + type;
|
||||||
entry.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
|
entry.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
|
||||||
log.appendChild(entry);
|
log.appendChild(entry);
|
||||||
log.scrollTop = log.scrollHeight;
|
log.scrollTop = log.scrollHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateUI(data) {
|
function updateUI(data) {
|
||||||
const { status, done, total, success, failed } = data;
|
const { status, done, total, success, failed } = data;
|
||||||
|
|
||||||
document.getElementById('done-count').textContent = done;
|
document.getElementById('done-count').textContent = done;
|
||||||
document.getElementById('success-count').textContent = success;
|
document.getElementById('success-count').textContent = success;
|
||||||
document.getElementById('failed-count').textContent = failed;
|
document.getElementById('failed-count').textContent = failed;
|
||||||
|
|
||||||
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
|
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
|
||||||
const fill = document.getElementById('progress-fill');
|
const fill = document.getElementById('progress-fill');
|
||||||
fill.style.width = pct + '%';
|
fill.style.width = pct + '%';
|
||||||
document.getElementById('progress-text').textContent = pct + '%';
|
document.getElementById('progress-text').textContent = pct + '%';
|
||||||
|
|
||||||
if (pct >= 100 || status === 'completed' || status === 'cancelled') {
|
if (pct >= 100 || status === 'completed' || status === 'cancelled') {
|
||||||
fill.classList.add('done');
|
fill.classList.add('done');
|
||||||
document.getElementById('cancel-btn').disabled = true;
|
document.getElementById('cancel-btn').disabled = true;
|
||||||
completed = true;
|
completed = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === 'cancelled') {
|
if (status === 'cancelled') {
|
||||||
document.getElementById('status-text').textContent = '❌ 已取消';
|
document.getElementById('status-text').textContent = '❌ 已取消';
|
||||||
addLog('任务已取消', '');
|
addLog('任务已取消', '');
|
||||||
} else if (status === 'completed') {
|
} else if (status === 'completed') {
|
||||||
document.getElementById('status-text').textContent = '✅ 全部完成';
|
document.getElementById('status-text').textContent = '✅ 全部完成';
|
||||||
addLog(`完成!成功:${success} 失败:${failed}`, '');
|
addLog(`完成!成功:${success} 失败:${failed}`, '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function cancelTask() {
|
function cancelTask() {
|
||||||
if (cancelled || completed) return;
|
if (cancelled || completed) return;
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
document.getElementById('cancel-btn').disabled = true;
|
document.getElementById('cancel-btn').disabled = true;
|
||||||
document.getElementById('cancel-btn').textContent = '取消中...';
|
document.getElementById('cancel-btn').textContent = '取消中...';
|
||||||
fetch(`/api/ring_cancel/${taskId}`, { method: 'POST' })
|
fetch(`/api/ring_cancel/${taskId}`, { method: 'POST' })
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.then(d => {
|
.then(d => {
|
||||||
addLog(d.message || '取消请求已发送', '');
|
addLog(d.message || '取消请求已发送', '');
|
||||||
})
|
})
|
||||||
.catch(() => addLog('取消请求失败', 'failed'));
|
.catch(() => addLog('取消请求失败', 'failed'));
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeWindow() {
|
function closeWindow() {
|
||||||
if (!completed && !cancelled) {
|
if (!completed && !cancelled) {
|
||||||
if (!confirm('任务还在运行,确定要关闭吗?')) return;
|
if (!confirm('任务还在运行,确定要关闭吗?')) return;
|
||||||
}
|
}
|
||||||
uiCloseWindow();
|
uiCloseWindow();
|
||||||
}
|
}
|
||||||
|
|
||||||
// SSE 连接
|
// SSE 连接
|
||||||
const es = new EventSource(`/api/ring_progress/${taskId}`);
|
const es = new EventSource(`/api/ring_progress/${taskId}`);
|
||||||
|
|
||||||
es.onmessage = (e) => {
|
es.onmessage = (e) => {
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(e.data);
|
const data = JSON.parse(e.data);
|
||||||
if (data.type === 'progress') {
|
if (data.type === 'progress') {
|
||||||
updateUI(data);
|
updateUI(data);
|
||||||
} else if (data.type === 'done') {
|
} else if (data.type === 'done') {
|
||||||
es.close();
|
es.close();
|
||||||
} else if (data.type === 'error') {
|
} else if (data.type === 'error') {
|
||||||
addLog(data.message, 'failed');
|
addLog(data.message, 'failed');
|
||||||
es.close();
|
es.close();
|
||||||
}
|
}
|
||||||
} catch (err) {}
|
} catch (err) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
es.onerror = () => {
|
es.onerror = () => {
|
||||||
addLog('连接断开', 'failed');
|
addLog('连接断开', 'failed');
|
||||||
es.close();
|
es.close();
|
||||||
};
|
};
|
||||||
|
|
||||||
addLog('开始监听进度...', '');
|
addLog('开始监听进度...', '');
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+34
-34
@@ -1,34 +1,34 @@
|
|||||||
import requests, time, json
|
import requests, time, json
|
||||||
|
|
||||||
token_id = '1291378'
|
token_id = '1291378'
|
||||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||||
timestamp = str(int(time.time()))
|
timestamp = str(int(time.time()))
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
'Host': 'bike.sdlongren.com',
|
'Host': 'bike.sdlongren.com',
|
||||||
'hsf-x-signature': wx_signature,
|
'hsf-x-signature': wx_signature,
|
||||||
'hsf-x-timestamp': timestamp,
|
'hsf-x-timestamp': timestamp,
|
||||||
'hsf-x-tokenid': token_id,
|
'hsf-x-tokenid': token_id,
|
||||||
'xweb_xhr': '1',
|
'xweb_xhr': '1',
|
||||||
'platform': 'xiaobai',
|
'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',
|
'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',
|
'content-type': 'application/json',
|
||||||
'accept': '*/*',
|
'accept': '*/*',
|
||||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||||
}
|
}
|
||||||
|
|
||||||
# 测试各接口
|
# 测试各接口
|
||||||
tests = [
|
tests = [
|
||||||
('/record/order', {'code': '51287', 'start_longitude': 116.98, 'start_latitude': 36.67}),
|
('/record/order', {'code': '51287', 'start_longitude': 116.98, 'start_latitude': 36.67}),
|
||||||
('/record/checkLocation', {'longitude': 116.98, 'latitude': 36.67, 'bicycleCode': '51287'}),
|
('/record/checkLocation', {'longitude': 116.98, 'latitude': 36.67, 'bicycleCode': '51287'}),
|
||||||
('/record/return', {'order_id': 15899504, 'longitude': 116.98, 'latitude': 36.67}),
|
('/record/return', {'order_id': 15899504, 'longitude': 116.98, 'latitude': 36.67}),
|
||||||
]
|
]
|
||||||
|
|
||||||
for path, body in tests:
|
for path, body in tests:
|
||||||
resp = requests.post(f'https://bike.sdlongren.com{path}', headers=headers, json=body, timeout=10, verify=False)
|
resp = requests.post(f'https://bike.sdlongren.com{path}', headers=headers, json=body, timeout=10, verify=False)
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
print(path)
|
print(path)
|
||||||
print(' rtn_code:', data.get('rtn_code'))
|
print(' rtn_code:', data.get('rtn_code'))
|
||||||
print(' code:', data.get('code'))
|
print(' code:', data.get('code'))
|
||||||
print(' message:', data.get('message'))
|
print(' message:', data.get('message'))
|
||||||
print(' data:', str(data.get('data'))[:200])
|
print(' data:', str(data.get('data'))[:200])
|
||||||
|
|||||||
+46
-46
@@ -1,46 +1,46 @@
|
|||||||
import requests, time, json
|
import requests, time, json
|
||||||
|
|
||||||
token_id = '1291378'
|
token_id = '1291378'
|
||||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||||
timestamp = str(int(time.time()))
|
timestamp = str(int(time.time()))
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
'Host': 'bike.sdlongren.com',
|
'Host': 'bike.sdlongren.com',
|
||||||
'hsf-x-signature': wx_signature,
|
'hsf-x-signature': wx_signature,
|
||||||
'hsf-x-timestamp': timestamp,
|
'hsf-x-timestamp': timestamp,
|
||||||
'hsf-x-tokenid': token_id,
|
'hsf-x-tokenid': token_id,
|
||||||
'xweb_xhr': '1',
|
'xweb_xhr': '1',
|
||||||
'platform': 'xiaobai',
|
'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',
|
'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',
|
'content-type': 'application/json',
|
||||||
'accept': '*/*',
|
'accept': '*/*',
|
||||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||||
}
|
}
|
||||||
|
|
||||||
tests = [
|
tests = [
|
||||||
# GET /user/packages - 我的卡包列表
|
# GET /user/packages - 我的卡包列表
|
||||||
('GET', '/user/packages', None),
|
('GET', '/user/packages', None),
|
||||||
# GET /packages/mapp - 推荐卡包列表
|
# GET /packages/mapp - 推荐卡包列表
|
||||||
('GET', '/packages/mapp', None),
|
('GET', '/packages/mapp', None),
|
||||||
# GET /bus_packages/user_packages - 我的公交卡包
|
# GET /bus_packages/user_packages - 我的公交卡包
|
||||||
('GET', '/bus_packages/user_packages', None),
|
('GET', '/bus_packages/user_packages', None),
|
||||||
]
|
]
|
||||||
|
|
||||||
for method, path, body in tests:
|
for method, path, body in tests:
|
||||||
url = f'https://bike.sdlongren.com{path}'
|
url = f'https://bike.sdlongren.com{path}'
|
||||||
if method == 'GET':
|
if method == 'GET':
|
||||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||||
else:
|
else:
|
||||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
print(f'=== {method} {path} ===')
|
print(f'=== {method} {path} ===')
|
||||||
print(' rtn_code:', data.get('rtn_code'), 'code:', data.get('code'))
|
print(' rtn_code:', data.get('rtn_code'), 'code:', data.get('code'))
|
||||||
print(' message:', data.get('message'))
|
print(' message:', data.get('message'))
|
||||||
if data.get('data'):
|
if data.get('data'):
|
||||||
print(' data keys:', list(data.get('data', {}).keys()))
|
print(' data keys:', list(data.get('data', {}).keys()))
|
||||||
d = data['data']
|
d = data['data']
|
||||||
# 打印卡包信息
|
# 打印卡包信息
|
||||||
for k in ['bike_packages', 'packageList', 'package', 'packages', 'memberPackageCount', 'memberPackage']:
|
for k in ['bike_packages', 'packageList', 'package', 'packages', 'memberPackageCount', 'memberPackage']:
|
||||||
if k in d:
|
if k in d:
|
||||||
print(f' {k}:', str(d[k])[:300])
|
print(f' {k}:', str(d[k])[:300])
|
||||||
print()
|
print()
|
||||||
|
|||||||
+45
-45
@@ -1,45 +1,45 @@
|
|||||||
import requests, time, json
|
import requests, time, json
|
||||||
|
|
||||||
token_id = '1291378'
|
token_id = '1291378'
|
||||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||||
timestamp = str(int(time.time()))
|
timestamp = str(int(time.time()))
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
'Host': 'bike.sdlongren.com',
|
'Host': 'bike.sdlongren.com',
|
||||||
'hsf-x-signature': wx_signature,
|
'hsf-x-signature': wx_signature,
|
||||||
'hsf-x-timestamp': timestamp,
|
'hsf-x-timestamp': timestamp,
|
||||||
'hsf-x-tokenid': token_id,
|
'hsf-x-tokenid': token_id,
|
||||||
'xweb_xhr': '1',
|
'xweb_xhr': '1',
|
||||||
'platform': 'xiaobai',
|
'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',
|
'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',
|
'content-type': 'application/json',
|
||||||
'accept': '*/*',
|
'accept': '*/*',
|
||||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||||
}
|
}
|
||||||
|
|
||||||
tests = [
|
tests = [
|
||||||
# GET /user/packages - 从JS逆向得到的"我的卡包"
|
# GET /user/packages - 从JS逆向得到的"我的卡包"
|
||||||
('GET', '/user/packages', None),
|
('GET', '/user/packages', None),
|
||||||
# 看看/user/info 里的 package 和 memberPackageCount
|
# 看看/user/info 里的 package 和 memberPackageCount
|
||||||
('GET', '/user/info', None),
|
('GET', '/user/info', None),
|
||||||
# 可能的变体路径
|
# 可能的变体路径
|
||||||
('GET', '/user/package', None),
|
('GET', '/user/package', None),
|
||||||
('GET', '/user/memberPackage', None),
|
('GET', '/user/memberPackage', None),
|
||||||
('GET', '/user/myPackage', None),
|
('GET', '/user/myPackage', None),
|
||||||
('GET', '/packages/user', None),
|
('GET', '/packages/user', None),
|
||||||
('GET', '/packages/my', None),
|
('GET', '/packages/my', None),
|
||||||
]
|
]
|
||||||
|
|
||||||
for method, path, body in tests:
|
for method, path, body in tests:
|
||||||
url = f'https://bike.sdlongren.com{path}'
|
url = f'https://bike.sdlongren.com{path}'
|
||||||
if method == 'GET':
|
if method == 'GET':
|
||||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||||
else:
|
else:
|
||||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
print(f'=== {method} {path} === rtn_code={data.get("rtn_code")} code={data.get("code")}')
|
print(f'=== {method} {path} === rtn_code={data.get("rtn_code")} code={data.get("code")}')
|
||||||
if data.get('rtn_code') == 0 and data.get('data'):
|
if data.get('rtn_code') == 0 and data.get('data'):
|
||||||
for k, v in data['data'].items():
|
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():
|
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(f' {k}: {str(v)[:200]}')
|
||||||
print()
|
print()
|
||||||
|
|||||||
+41
-41
@@ -1,41 +1,41 @@
|
|||||||
import requests, time, json
|
import requests, time, json
|
||||||
|
|
||||||
token_id = '1291378'
|
token_id = '1291378'
|
||||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||||
timestamp = str(int(time.time()))
|
timestamp = str(int(time.time()))
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
'Host': 'bike.sdlongren.com',
|
'Host': 'bike.sdlongren.com',
|
||||||
'hsf-x-signature': wx_signature,
|
'hsf-x-signature': wx_signature,
|
||||||
'hsf-x-timestamp': timestamp,
|
'hsf-x-timestamp': timestamp,
|
||||||
'hsf-x-tokenid': token_id,
|
'hsf-x-tokenid': token_id,
|
||||||
'xweb_xhr': '1',
|
'xweb_xhr': '1',
|
||||||
'platform': 'xiaobai',
|
'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',
|
'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',
|
'content-type': 'application/json',
|
||||||
'accept': '*/*',
|
'accept': '*/*',
|
||||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||||
}
|
}
|
||||||
|
|
||||||
# 获取推荐卡包的完整字段
|
# 获取推荐卡包的完整字段
|
||||||
resp = requests.get('https://bike.sdlongren.com/packages/mapp', headers=headers, timeout=10, verify=False)
|
resp = requests.get('https://bike.sdlongren.com/packages/mapp', headers=headers, timeout=10, verify=False)
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
print('=== 推荐卡包完整字段 ===')
|
print('=== 推荐卡包完整字段 ===')
|
||||||
if data.get('rtn_code') == 0 and data.get('data', {}).get('bike_packages'):
|
if data.get('rtn_code') == 0 and data.get('data', {}).get('bike_packages'):
|
||||||
pkg = data['data']['bike_packages'][0]
|
pkg = data['data']['bike_packages'][0]
|
||||||
print(json.dumps(pkg, ensure_ascii=False, indent=2))
|
print(json.dumps(pkg, ensure_ascii=False, indent=2))
|
||||||
print()
|
print()
|
||||||
print('所有字段:', list(pkg.keys()))
|
print('所有字段:', list(pkg.keys()))
|
||||||
|
|
||||||
# /user/info 里的 package 字段完整内容
|
# /user/info 里的 package 字段完整内容
|
||||||
resp2 = requests.get('https://bike.sdlongren.com/user/info', headers=headers, timeout=10, verify=False)
|
resp2 = requests.get('https://bike.sdlongren.com/user/info', headers=headers, timeout=10, verify=False)
|
||||||
data2 = resp2.json()
|
data2 = resp2.json()
|
||||||
print('=== user/info 中的 package 字段 ===')
|
print('=== user/info 中的 package 字段 ===')
|
||||||
pkg_data = data2.get('data', {}).get('package', {})
|
pkg_data = data2.get('data', {}).get('package', {})
|
||||||
print(json.dumps(pkg_data, ensure_ascii=False, indent=2))
|
print(json.dumps(pkg_data, ensure_ascii=False, indent=2))
|
||||||
print()
|
print()
|
||||||
print('package 所有字段:', list(pkg_data.keys()))
|
print('package 所有字段:', list(pkg_data.keys()))
|
||||||
|
|
||||||
# memberPackageCount
|
# memberPackageCount
|
||||||
print('memberPackageCount:', data2['data'].get('memberPackageCount'))
|
print('memberPackageCount:', data2['data'].get('memberPackageCount'))
|
||||||
print('spec_count:', data2['data'].get('spec_count'))
|
print('spec_count:', data2['data'].get('spec_count'))
|
||||||
|
|||||||
+43
-43
@@ -1,43 +1,43 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""测试API坐标"""
|
"""测试API坐标"""
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
import hashlib
|
import hashlib
|
||||||
import urllib3
|
import urllib3
|
||||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||||
|
|
||||||
HEADERS = {
|
HEADERS = {
|
||||||
'Host': 'bike.sdlongren.com',
|
'Host': 'bike.sdlongren.com',
|
||||||
'hsf-x-tokenid': '1291378',
|
'hsf-x-tokenid': '1291378',
|
||||||
'xweb_xhr': '1',
|
'xweb_xhr': '1',
|
||||||
'platform': 'xiaobai',
|
'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',
|
'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',
|
'content-type': 'application/json',
|
||||||
'accept': '*/*',
|
'accept': '*/*',
|
||||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||||
}
|
}
|
||||||
|
|
||||||
ts = str(int(time.time()))
|
ts = str(int(time.time()))
|
||||||
raw = f"1291378GET/project/map{ts}"
|
raw = f"1291378GET/project/map{ts}"
|
||||||
sig = hashlib.sha256(raw.encode()).hexdigest()[:40]
|
sig = hashlib.sha256(raw.encode()).hexdigest()[:40]
|
||||||
HEADERS['hsf-x-timestamp'] = ts
|
HEADERS['hsf-x-timestamp'] = ts
|
||||||
HEADERS['hsf-x-signature'] = sig
|
HEADERS['hsf-x-signature'] = sig
|
||||||
|
|
||||||
resp = requests.get('https://bike.sdlongren.com/project/map?type=3', headers=HEADERS, verify=False)
|
resp = requests.get('https://bike.sdlongren.com/project/map?type=3', headers=HEADERS, verify=False)
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
|
|
||||||
# 打印返回的学校中心坐标和前3辆车的坐标
|
# 打印返回的学校中心坐标和前3辆车的坐标
|
||||||
if data.get('rtn_code') == 0 and data.get('data'):
|
if data.get('rtn_code') == 0 and data.get('data'):
|
||||||
d = data['data']
|
d = data['data']
|
||||||
print('=== 学校中心坐标 ===')
|
print('=== 学校中心坐标 ===')
|
||||||
print(f'centerLatitude: {d.get("centerLatitude")}')
|
print(f'centerLatitude: {d.get("centerLatitude")}')
|
||||||
print(f'centerLongitude: {d.get("centerLongitude")}')
|
print(f'centerLongitude: {d.get("centerLongitude")}')
|
||||||
print()
|
print()
|
||||||
print('=== 前3辆车坐标 ===')
|
print('=== 前3辆车坐标 ===')
|
||||||
for i, bike in enumerate(d.get('bicycleStation', [])[: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")}')
|
print(f'{i+1}. code={bike.get("code")}, lat={bike.get("latitude")}, lng={bike.get("longitude")}')
|
||||||
else:
|
else:
|
||||||
print('请求失败:', data)
|
print('请求失败:', data)
|
||||||
|
|||||||
@@ -40,17 +40,20 @@ class OrderControlTests(unittest.TestCase):
|
|||||||
})
|
})
|
||||||
|
|
||||||
self.assertEqual(0, response.get_json()["rtn_code"])
|
self.assertEqual(0, response.get_json()["rtn_code"])
|
||||||
|
# 浏览器上报的是 WGS84,入口会先转成 GCJ02 再发给上游(实测上游只认 GCJ02)
|
||||||
|
exp_lat, exp_lng = rental.to_upstream_coords(36.671, 116.981)
|
||||||
|
self.assertFalse(exp_lng == 116.981) # 确实转过
|
||||||
self.assertEqual([
|
self.assertEqual([
|
||||||
((7, "POST", "/record/checkLocation"), {
|
((7, "POST", "/record/checkLocation"), {
|
||||||
"data": {"longitude": 116.981, "latitude": 36.671,
|
"data": {"longitude": exp_lng, "latitude": exp_lat,
|
||||||
"bicycleCode": "50001"}
|
"bicycleCode": "50001"}
|
||||||
}),
|
}),
|
||||||
((7, "POST", "/project/coordinate"), {
|
((7, "POST", "/project/coordinate"), {
|
||||||
"data": {"order_id": "9001", "code": "50001"}
|
"data": {"order_id": "9001", "code": "50001"}
|
||||||
}),
|
}),
|
||||||
((7, "POST", "/record/close"), {
|
((7, "POST", "/record/close"), {
|
||||||
"data": {"order_id": "9001", "end_longitude": 116.981,
|
"data": {"order_id": "9001", "end_longitude": exp_lng,
|
||||||
"end_latitude": 36.671}
|
"end_latitude": exp_lat}
|
||||||
}),
|
}),
|
||||||
], [(call.args, call.kwargs) for call in upstream.call_args_list])
|
], [(call.args, call.kwargs) for call in upstream.call_args_list])
|
||||||
|
|
||||||
|
|||||||
@@ -145,6 +145,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||||
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer, "start_rental_timer"):
|
patch.object(timer, "start_rental_timer"):
|
||||||
result = timer._check_user_order(7)
|
result = timer._check_user_order(7)
|
||||||
@@ -167,6 +168,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
{"rtn_code": 500, "message": "return rejected"},
|
{"rtn_code": 500, "message": "return rejected"},
|
||||||
]
|
]
|
||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer._time, "sleep"), \
|
patch.object(timer._time, "sleep"), \
|
||||||
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
||||||
@@ -184,6 +186,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
{"rtn_code": 0, "message": "ok"},
|
{"rtn_code": 0, "message": "ok"},
|
||||||
]
|
]
|
||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
||||||
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
||||||
@@ -206,6 +209,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
"rental_rounds": 2, "protect_card": True,
|
"rental_rounds": 2, "protect_card": True,
|
||||||
}
|
}
|
||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
||||||
patch.object(timer, "_try_card_pay_auto", return_value={"success": True, "message": "月卡支付成功"}), \
|
patch.object(timer, "_try_card_pay_auto", return_value={"success": True, "message": "月卡支付成功"}), \
|
||||||
@@ -240,6 +244,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
"rental_rounds": 2, "protect_card": True,
|
"rental_rounds": 2, "protect_card": True,
|
||||||
}
|
}
|
||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
||||||
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
||||||
|
|||||||
@@ -0,0 +1,243 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""停车区(parkeArea)判定、还车点吸附与坐标系边界。
|
||||||
|
|
||||||
|
覆盖四件事:
|
||||||
|
1. 坐标转换方向别搞反(浏览器 WGS84 / 上游 GCJ02,只在入口转一次);
|
||||||
|
2. 吸附点必须真的落在多边形内;
|
||||||
|
3. 自动还车「发还车之前」就对齐停车区,而不是让三次重试打同一个错坐标;
|
||||||
|
4. 临时的上游抖动不该把订单挂死。
|
||||||
|
"""
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import campus
|
||||||
|
import park_area
|
||||||
|
import timer
|
||||||
|
from routes import rental
|
||||||
|
|
||||||
|
# 山管院附近一块方形停车区(GCJ02,上游 parkeArea 的坐标系)
|
||||||
|
PARK_SQUARE = [
|
||||||
|
[36.5313, 116.7797],
|
||||||
|
[36.5313, 116.7807],
|
||||||
|
[36.5323, 116.7807],
|
||||||
|
[36.5323, 116.7797],
|
||||||
|
]
|
||||||
|
PARK_AREAS = [{"points": PARK_SQUARE}]
|
||||||
|
|
||||||
|
|
||||||
|
class CoordinateConversionTests(unittest.TestCase):
|
||||||
|
def test_wgs84_to_gcj02_matches_known_offset(self):
|
||||||
|
lng, lat = campus.wgs84_to_gcj02(116.404, 39.915)
|
||||||
|
# 北京一带:GCJ02 相对 WGS84 偏移在 0.004~0.007 度量级
|
||||||
|
self.assertTrue(0.003 < lng - 116.404 < 0.008)
|
||||||
|
self.assertTrue(-0.003 < lat - 39.915 < 0.003)
|
||||||
|
|
||||||
|
def test_roundtrip_is_sub_meter(self):
|
||||||
|
for lat, lng in ((36.5318, 116.7802), (39.915, 116.404), (22.5431, 114.0579)):
|
||||||
|
g_lng, g_lat = campus.wgs84_to_gcj02(lng, lat)
|
||||||
|
back_lng, back_lat = campus.gcj02_to_wgs84(g_lng, g_lat)
|
||||||
|
self.assertLess(campus.haversine_m(lat, lng, back_lat, back_lng), 1.0)
|
||||||
|
|
||||||
|
def test_out_of_china_is_passthrough(self):
|
||||||
|
self.assertEqual([-122.4194, 37.7749], campus.wgs84_to_gcj02(-122.4194, 37.7749))
|
||||||
|
self.assertEqual([-122.4194, 37.7749], campus.gcj02_to_wgs84(-122.4194, 37.7749))
|
||||||
|
|
||||||
|
|
||||||
|
class ParseParkAreaTests(unittest.TestCase):
|
||||||
|
def test_accepts_dict_and_list_points_and_skips_invalid(self):
|
||||||
|
list_area = [[36.53, 116.78], [36.53, 116.79], [36.54, 116.79]]
|
||||||
|
payload = {
|
||||||
|
"parkeArea": [
|
||||||
|
{"points": [{"latitude": 36.53, "longitude": 116.78}] * 3, "is_disable": 1},
|
||||||
|
{"points": list_area, "is_disable": 1},
|
||||||
|
{"points": [[36.53, 116.78], [36.53, 116.79]]}, # 少于 3 点
|
||||||
|
{"points": PARK_SQUARE, "is_disable": 2}, # 停用(实测语义)
|
||||||
|
{"points": []},
|
||||||
|
"not-a-dict",
|
||||||
|
]
|
||||||
|
}
|
||||||
|
areas = park_area.parse_park_areas(payload)
|
||||||
|
self.assertEqual(2, len(areas))
|
||||||
|
self.assertEqual(3, len(areas[0]["points"]))
|
||||||
|
self.assertEqual(list_area, areas[1]["points"])
|
||||||
|
self.assertNotIn(PARK_SQUARE, [a["points"] for a in areas])
|
||||||
|
|
||||||
|
def test_is_disable_1_is_kept_and_2_is_dropped(self):
|
||||||
|
"""语义是实测出来的:1=启用,2=停用。判反等于把所有能还车的区全丢掉。"""
|
||||||
|
payload = {"parkeArea": [
|
||||||
|
{"points": PARK_SQUARE, "is_disable": 1},
|
||||||
|
{"points": PARK_SQUARE, "is_disable": 2},
|
||||||
|
{"points": PARK_SQUARE},
|
||||||
|
]}
|
||||||
|
areas = park_area.parse_park_areas(payload)
|
||||||
|
self.assertEqual(2, len(areas))
|
||||||
|
|
||||||
|
def test_missing_or_malformed_data_returns_empty(self):
|
||||||
|
for payload in (None, {}, {"parkeArea": None}, {"parkeArea": {}}, []):
|
||||||
|
self.assertEqual([], park_area.parse_park_areas(payload))
|
||||||
|
|
||||||
|
|
||||||
|
class ResolveReturnCoordTests(unittest.TestCase):
|
||||||
|
def test_point_already_inside_is_kept_untouched(self):
|
||||||
|
resolved = park_area.resolve_return_coord(36.5318, 116.7802, PARK_AREAS)
|
||||||
|
self.assertIsNotNone(resolved)
|
||||||
|
self.assertTrue(resolved["inside"])
|
||||||
|
self.assertFalse(resolved["moved"])
|
||||||
|
self.assertEqual((36.5318, 116.7802),
|
||||||
|
(resolved["latitude"], resolved["longitude"]))
|
||||||
|
|
||||||
|
def test_outside_point_is_snapped_inside_the_polygon(self):
|
||||||
|
resolved = park_area.resolve_return_coord(36.5250, 116.7700, PARK_AREAS)
|
||||||
|
self.assertIsNotNone(resolved)
|
||||||
|
self.assertTrue(resolved["moved"])
|
||||||
|
self.assertGreater(resolved["distance"], 100)
|
||||||
|
self.assertTrue(campus.point_in_polygon(
|
||||||
|
resolved["latitude"], resolved["longitude"], PARK_SQUARE))
|
||||||
|
|
||||||
|
def test_no_area_returns_none(self):
|
||||||
|
self.assertIsNone(park_area.resolve_return_coord(36.5, 116.7, []))
|
||||||
|
self.assertIsNone(park_area.resolve_return_coord(None, 116.7, PARK_AREAS))
|
||||||
|
|
||||||
|
def test_nearest_of_two_areas_wins(self):
|
||||||
|
east = [[p[0], p[1] + 0.02] for p in PARK_SQUARE]
|
||||||
|
areas = [{"points": PARK_SQUARE}, {"points": east}]
|
||||||
|
resolved = park_area.resolve_return_coord(36.5318, 116.7995, areas)
|
||||||
|
self.assertIsNotNone(resolved)
|
||||||
|
self.assertGreater(resolved["longitude"], 116.7990)
|
||||||
|
|
||||||
|
|
||||||
|
class BoundaryCoordTests(unittest.TestCase):
|
||||||
|
"""入口坐标:浏览器 WGS84 -> 上游 GCJ02,只转一次。"""
|
||||||
|
|
||||||
|
def test_to_upstream_coords_shifts_into_gcj02(self):
|
||||||
|
lat, lng = rental.to_upstream_coords(36.5250, 116.7700)
|
||||||
|
moved = campus.haversine_m(36.5250, 116.7700, lat, lng)
|
||||||
|
self.assertGreater(moved, 100)
|
||||||
|
self.assertLess(moved, 800)
|
||||||
|
back_lng, back_lat = campus.gcj02_to_wgs84(lng, lat)
|
||||||
|
self.assertLess(campus.haversine_m(36.5250, 116.7700, back_lat, back_lng), 1.0)
|
||||||
|
|
||||||
|
def test_to_upstream_coords_tolerates_bad_input(self):
|
||||||
|
self.assertEqual((None, None), rental.to_upstream_coords(None, None))
|
||||||
|
self.assertEqual(("a", "b"), rental.to_upstream_coords("a", "b"))
|
||||||
|
|
||||||
|
|
||||||
|
class OrderLocationTests(unittest.TestCase):
|
||||||
|
def test_upstream_pass_returns_gcj02_not_raw_browser_value(self):
|
||||||
|
with patch.object(rental, "request_with_user_auth",
|
||||||
|
return_value={"rtn_code": 0, "parkNoShow": False}) as upstream:
|
||||||
|
lat, lng, used_nearest = rental._resolve_order_location(
|
||||||
|
7, "50001", 36.5318, 116.7802)
|
||||||
|
self.assertFalse(used_nearest)
|
||||||
|
expected = rental.to_upstream_coords(36.5318, 116.7802)
|
||||||
|
self.assertAlmostEqual(expected[0], lat, places=6)
|
||||||
|
self.assertAlmostEqual(expected[1], lng, places=6)
|
||||||
|
# checkLocation 也必须拿 GCJ02 去问,否则上游按自己坐标系判必偏 500 米
|
||||||
|
sent = upstream.call_args.kwargs["data"]
|
||||||
|
self.assertAlmostEqual(expected[1], sent["longitude"], places=6)
|
||||||
|
self.assertAlmostEqual(expected[0], sent["latitude"], places=6)
|
||||||
|
|
||||||
|
def test_park_no_show_snaps_into_park_area(self):
|
||||||
|
with patch.object(rental, "request_with_user_auth",
|
||||||
|
return_value={"rtn_code": 0, "parkNoShow": True}), \
|
||||||
|
patch.object(rental, "_park_areas", return_value=PARK_AREAS):
|
||||||
|
out_lat, out_lng, used_nearest = rental._resolve_order_location(
|
||||||
|
7, "50001", 36.5250, 116.7700)
|
||||||
|
self.assertTrue(used_nearest)
|
||||||
|
self.assertTrue(campus.point_in_polygon(out_lat, out_lng, PARK_SQUARE))
|
||||||
|
|
||||||
|
def test_get_nearest_park_point_returns_gcj02_from_legacy_bikes(self):
|
||||||
|
station = {"rtn_code": 0, "data": {"bicycleStation": [
|
||||||
|
{"latitude": 36.5318, "longitude": 116.7802}]}}
|
||||||
|
with patch.object(rental, "_park_areas", return_value=[]), \
|
||||||
|
patch.object(rental, "request_api", return_value=station):
|
||||||
|
point = rental.get_nearest_park_point(36.5250, 116.7700)
|
||||||
|
self.assertIsNotNone(point)
|
||||||
|
# 入参/返回同为 GCJ02:不再转换,值应与车点一致
|
||||||
|
self.assertAlmostEqual(36.5318, point["latitude"], places=6)
|
||||||
|
self.assertAlmostEqual(116.7802, point["longitude"], places=6)
|
||||||
|
|
||||||
|
|
||||||
|
class AutoReturnAlignTests(unittest.TestCase):
|
||||||
|
def test_align_moves_outside_point_into_area(self):
|
||||||
|
with patch.object(timer, "_park_areas_for_user", return_value=PARK_AREAS):
|
||||||
|
lat, lng, moved, dist = timer._align_to_park_area(7, 36.5250, 116.7700)
|
||||||
|
self.assertTrue(moved)
|
||||||
|
self.assertGreater(dist, 100)
|
||||||
|
self.assertTrue(campus.point_in_polygon(lat, lng, PARK_SQUARE))
|
||||||
|
|
||||||
|
def test_align_leaves_inside_point_alone(self):
|
||||||
|
with patch.object(timer, "_park_areas_for_user", return_value=PARK_AREAS):
|
||||||
|
lat, lng, moved, _ = timer._align_to_park_area(7, 36.5318, 116.7802)
|
||||||
|
self.assertFalse(moved)
|
||||||
|
self.assertEqual((36.5318, 116.7802), (lat, lng))
|
||||||
|
|
||||||
|
def test_align_without_park_areas_is_noop(self):
|
||||||
|
with patch.object(timer, "_park_areas_for_user", return_value=[]):
|
||||||
|
self.assertEqual(
|
||||||
|
(36.5250, 116.7700, False, 0.0),
|
||||||
|
timer._align_to_park_area(7, 36.5250, 116.7700))
|
||||||
|
|
||||||
|
|
||||||
|
class AutoReturnTests(unittest.TestCase):
|
||||||
|
RENTAL_ROW = {"id": 1, "bike_code": "50001", "order_id": "9001",
|
||||||
|
"expired": 0, "end_time": "2026-01-01 00:00:00"}
|
||||||
|
|
||||||
|
def _run(self, bike_lat, bike_lng, return_results):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_upstream(user_id, method, path, params=None, data=None, **kwargs):
|
||||||
|
if path == "/project/bicycle":
|
||||||
|
return {"rtn_code": 0,
|
||||||
|
"data": {"latitude": bike_lat, "longitude": bike_lng}}
|
||||||
|
if path == "/record/return":
|
||||||
|
calls.append(dict(data))
|
||||||
|
return return_results[min(len(calls) - 1, len(return_results) - 1)]
|
||||||
|
return {"rtn_code": 0}
|
||||||
|
|
||||||
|
with patch.object(timer, "get_db") as get_db, \
|
||||||
|
patch.object(timer, "request_with_user_auth", side_effect=fake_upstream), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=PARK_AREAS), \
|
||||||
|
patch.object(timer, "_mark_returned"), \
|
||||||
|
patch.object(timer, "mark_return_tokens_used"), \
|
||||||
|
patch.object(timer, "_cancel_rental_timers"), \
|
||||||
|
patch.object(timer, "_maybe_renew_after_return",
|
||||||
|
return_value={"renewed": False}), \
|
||||||
|
patch.object(timer, "_time") as fake_time:
|
||||||
|
fake_time.sleep = lambda *_: None
|
||||||
|
get_db.return_value.cursor.return_value.fetchone.return_value = dict(self.RENTAL_ROW)
|
||||||
|
result = timer._auto_return_bike(1, 7, allow_renewal=False)
|
||||||
|
return result, calls
|
||||||
|
|
||||||
|
def test_return_goes_to_park_area_on_the_first_try(self):
|
||||||
|
"""车停在区外:发还车之前就对齐,不该让三次重试打同一个错坐标。"""
|
||||||
|
result, calls = self._run(36.5250, 116.7700, [{"rtn_code": 0, "message": "ok"}])
|
||||||
|
self.assertTrue(result["success"])
|
||||||
|
self.assertEqual(1, len(calls))
|
||||||
|
self.assertNotEqual(116.7700, calls[0]["longitude"])
|
||||||
|
self.assertTrue(campus.point_in_polygon(
|
||||||
|
calls[0]["latitude"], calls[0]["longitude"], PARK_SQUARE))
|
||||||
|
|
||||||
|
def test_inside_point_is_sent_as_is_and_transient_failure_retries(self):
|
||||||
|
"""车已在区内:坐标原样发;上游抖动一次后重试成功。"""
|
||||||
|
result, calls = self._run(36.5318, 116.7802, [
|
||||||
|
{"rtn_code": 500, "message": "busy"},
|
||||||
|
{"rtn_code": 0, "message": "ok"},
|
||||||
|
])
|
||||||
|
self.assertTrue(result["success"])
|
||||||
|
self.assertEqual(2, len(calls))
|
||||||
|
for call in calls:
|
||||||
|
self.assertAlmostEqual(116.7802, call["longitude"], places=6)
|
||||||
|
self.assertAlmostEqual(36.5318, call["latitude"], places=6)
|
||||||
|
|
||||||
|
def test_failure_after_inside_point_really_fails_and_keeps_order_open(self):
|
||||||
|
result, calls = self._run(36.5318, 116.7802, [
|
||||||
|
{"rtn_code": 400, "message": "请到指定停车点还车"},
|
||||||
|
])
|
||||||
|
self.assertFalse(result["success"])
|
||||||
|
self.assertEqual(3, len(calls))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -24,6 +24,10 @@ _checker_lock = threading.Lock()
|
|||||||
# 10 分钟轮询会让 5/3/2/1/0 分钟提醒继续发送,改为每分钟核对一次。
|
# 10 分钟轮询会让 5/3/2/1/0 分钟提醒继续发送,改为每分钟核对一次。
|
||||||
ORDER_CHECK_INTERVAL = 60
|
ORDER_CHECK_INTERVAL = 60
|
||||||
|
|
||||||
|
# 自动还车用的停车区缓存:{user_id: (ts, parkeArea)},避免续租链反复拉地图
|
||||||
|
_PARK_AREA_CACHE: dict = {}
|
||||||
|
_PARK_AREA_TTL = 60
|
||||||
|
|
||||||
|
|
||||||
def _get_remaining_seconds(rental: dict) -> int:
|
def _get_remaining_seconds(rental: dict) -> int:
|
||||||
"""计算距离过期的秒数"""
|
"""计算距离过期的秒数"""
|
||||||
@@ -370,8 +374,58 @@ def _renewal_lock(rental_id: int):
|
|||||||
return _renewal_locks.setdefault(rental_id, threading.Lock())
|
return _renewal_locks.setdefault(rental_id, threading.Lock())
|
||||||
|
|
||||||
|
|
||||||
|
def _park_areas_for_user(user_id: int) -> list:
|
||||||
|
"""用用户凭据取上游停车区多边形(GCJ02)。结果短缓存,避免续租链反复拉地图。"""
|
||||||
|
import park_area
|
||||||
|
cached = _PARK_AREA_CACHE.get(user_id)
|
||||||
|
now = _time.time()
|
||||||
|
if cached and now - cached[0] < _PARK_AREA_TTL:
|
||||||
|
return cached[1]
|
||||||
|
try:
|
||||||
|
result = request_with_user_auth(
|
||||||
|
user_id, "GET", "/project/map", params={"type": "1"}, _silent=True
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[自动还车] 读取停车区失败: {exc}")
|
||||||
|
return []
|
||||||
|
if not isinstance(result, dict) or result.get("rtn_code") not in (None, 0):
|
||||||
|
return []
|
||||||
|
areas = park_area.parse_park_areas(result.get("data") or {})
|
||||||
|
if areas:
|
||||||
|
_PARK_AREA_CACHE[user_id] = (now, areas)
|
||||||
|
return areas
|
||||||
|
|
||||||
|
|
||||||
|
def _align_to_park_area(user_id: int, latitude, longitude):
|
||||||
|
"""把自动还车的坐标对齐到停车区(入参/返回都是 GCJ02)。
|
||||||
|
|
||||||
|
返回 (lat, lng, moved, distance)。拿不到 parkeArea 时原样返回。
|
||||||
|
自动还车前**先**对齐一次,绝大多数情况一次就还成功,不必靠重试撞。
|
||||||
|
"""
|
||||||
|
import park_area
|
||||||
|
areas = _park_areas_for_user(user_id)
|
||||||
|
if not areas:
|
||||||
|
return latitude, longitude, False, 0.0
|
||||||
|
try:
|
||||||
|
resolved = park_area.resolve_return_coord(latitude, longitude, areas)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[自动还车] 停车区判定异常: {exc}")
|
||||||
|
return latitude, longitude, False, 0.0
|
||||||
|
if resolved and resolved.get("moved"):
|
||||||
|
return (resolved["latitude"], resolved["longitude"], True,
|
||||||
|
float(resolved.get("distance") or 0.0))
|
||||||
|
return latitude, longitude, False, 0.0
|
||||||
|
|
||||||
|
|
||||||
def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
||||||
"""自动还车(含重试:最多3次),返回明确的成败结果。"""
|
"""自动还车(含重试:最多3次),返回明确的成败结果。
|
||||||
|
|
||||||
|
坐标链路(与手动还车同一套停车区规则):
|
||||||
|
1. 取车辆坐标(`/project/bicycle`,上游 = GCJ02,不要再转);
|
||||||
|
2. **发还车前**先用本地 parkeArea 多边形判定一次,不在停车区就先吸附到
|
||||||
|
最近的合法点 —— 原来直接发原始坐标,parkNoShow 时三次重试注定全失败;
|
||||||
|
3. 万一对齐后仍失败,第 2 次重试前再吸附一次(应对上游边界与本地不一致)。
|
||||||
|
"""
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
||||||
@@ -393,8 +447,18 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
|||||||
# 上游要求真实订单号;老记录可能只有本地自增 id,则兜底用它
|
# 上游要求真实订单号;老记录可能只有本地自增 id,则兜底用它
|
||||||
upstream_order_id = rental["order_id"] if rental["order_id"] else str(rental_id)
|
upstream_order_id = rental["order_id"] if rental["order_id"] else str(rental_id)
|
||||||
|
|
||||||
|
# 发还车前先对齐停车区:车辆坐标不在 parkeArea 内时直接换成最近的合法点,
|
||||||
|
# 否则 parkNoShow 会让三次重试全都打在同一个错坐标上。
|
||||||
|
latitude, longitude, aligned, aligned_m = _align_to_park_area(
|
||||||
|
user_id, latitude, longitude
|
||||||
|
)
|
||||||
|
if aligned:
|
||||||
|
print(f"[自动还车] 车辆坐标不在停车区,已对齐到最近停车区 "
|
||||||
|
f"({latitude:.6f}, {longitude:.6f}) [{aligned_m:.0f}m]")
|
||||||
|
|
||||||
return_result = None
|
return_result = None
|
||||||
last_error = None
|
last_error = None
|
||||||
|
snap_attempted = aligned # 已经对齐过的话,重试前不必再对齐一次
|
||||||
for attempt in range(1, 4):
|
for attempt in range(1, 4):
|
||||||
try:
|
try:
|
||||||
return_result = request_with_user_auth(
|
return_result = request_with_user_auth(
|
||||||
@@ -411,6 +475,16 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
last_error = str(e)
|
last_error = str(e)
|
||||||
print(f"[自动还车] 第{attempt}次异常: {last_error}")
|
print(f"[自动还车] 第{attempt}次异常: {last_error}")
|
||||||
|
# 首次失败:再对齐一次停车区(应对上游边界与本地多边形不一致)
|
||||||
|
if not snap_attempted and attempt < 3:
|
||||||
|
snap_attempted = True
|
||||||
|
new_lat, new_lng, moved, moved_m = _align_to_park_area(
|
||||||
|
user_id, latitude, longitude
|
||||||
|
)
|
||||||
|
if moved:
|
||||||
|
latitude, longitude = new_lat, new_lng
|
||||||
|
print(f"[自动还车] 已吸附到最近停车区 "
|
||||||
|
f"({latitude:.6f}, {longitude:.6f}) [{moved_m:.0f}m],准备重试")
|
||||||
if attempt < 3:
|
if attempt < 3:
|
||||||
_time.sleep(5)
|
_time.sleep(5)
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
# 全局微信凭据
|
|
||||||
# token_id: 登录后服务端下发的会话标识(重新登录小程序会失效,单会话策略)
|
|
||||||
# access_token: 登录响应中的 accessToken(JWT,30天有效),用于实时计算签名;留空则发占位签名
|
|
||||||
token_id=1672159
|
|
||||||
access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjFhNWVlMjI5ODJlNWI2ZDM1ZDA5Y2M0NzVkMDVkZjljZTc0OTg5ZGY4OGRiNjUxYjAxZTM1NDYwNjU5NGUwNmVlOGU2OTRlOGVlNjQ4NWZjIn0.eyJhdWQiOiIzIiwianRpIjoiMWE1ZWUyMjk4MmU1YjZkMzVkMDljYzQ3NWQwNWRmOWNlNzQ5ODlkZjg4ZGI2NTFiMDFlMzU0NjA2NTk0ZTA2ZWU4ZTY5NGU4ZWU2NDg1ZmMiLCJpYXQiOjE3OTMxMDA2NzcsIm5iZiI6MTc5MzEwMDY3NywiZXhwIjoxNzk1NjkyNjc3LCJzdWIiOiIyMzEwNDUiLCJzY29wZXMiOltdfQ.ild0ckS6fWSHEaftw5R3_K-4-T4KhNGu1mjZKjUTBdd60HA4elyKvMfZqsZO4vnDXlZHKRODiDFypCg9B1fUEVD02HlXwYvWZM_6sZNak56LqHLE_AsCBFWHOuojzV207qt5Is-qp7eKMEu9YLIc5meOlsUGZ9ydQqP80bPOoUi-B05NwWCR7zGwIvT3S00EoMxJdAb3y-UHqr6IPkdQkMHIIxTxac5_ejz7NEtOZCFGsb_lfCfEnXaOYmm4Uo7abDWCDTWThHIrDni-JRy9lfQmvmPysswDI0n_wc4PbydvJMrYCXwYYPGEoOzNYiooVojwHOzojnTp0F__Sdirk0D80jxos2l3OWMl5Cn4kOiGd5PAvaSv7xvfiHZ8RCDt-jFEM4QKeNKoEUqvLJq3iENnjTwcrsFDHvKTMF0Vw5gDRACSPvLBGtE-l2B9-QwZrVp_xY3IbSH5Nk_wzvVzhlAWZI_nKOFfJvVEzUAszAprXFqkueQerITbkjLLCSd-8njiSBbFipjaMrqVCdQ43dx70zfxtOkuEfCneIv7GAZcCSzQFO9mJLZ0ek6mmf-XdLWW_8xsR3aRfX7vzv_MD6E6UiRrRb27a5v9SqbcDWXTUTj9inC_qyaSmOf5OFgwQeNmFoeToc3MlfSIJqe4t7h5d9RWzS2kXoCeMoPCwQ0
|
|
||||||
@@ -1,442 +1,442 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""微信API通信模块
|
"""微信API通信模块
|
||||||
|
|
||||||
凭据模型(对照 98/ 反编译小程序与实机抓包还原):
|
凭据模型(对照 98/ 反编译小程序与实机抓包还原):
|
||||||
- token_id:登录后服务端下发的会话标识(单会话:小程序重新登录即失效)。
|
- token_id:登录后服务端下发的会话标识(单会话:小程序重新登录即失效)。
|
||||||
上游目前唯一强校验的头,必填。
|
上游目前唯一强校验的头,必填。
|
||||||
- access_token:登录响应里的 JWT(30 天有效)。小程序用它在本地实时计算签名:
|
- access_token:登录响应里的 JWT(30 天有效)。小程序用它在本地实时计算签名:
|
||||||
hsf-x-signature = sha1(access_token + base64(签名串))。选填。
|
hsf-x-signature = sha1(access_token + base64(签名串))。选填。
|
||||||
|
|
||||||
签名策略(双模式 + 强验证开关):
|
签名策略(双模式 + 强验证开关):
|
||||||
- 常规模式:有真实 access_token 就实时计算签名;否则生成形似合法的
|
- 常规模式:有真实 access_token 就实时计算签名;否则生成形似合法的
|
||||||
sha1 伪装签名(40 位 hex、随请求变化,防上游日志识别出固定异常值)。
|
sha1 伪装签名(40 位 hex、随请求变化,防上游日志识别出固定异常值)。
|
||||||
- 强验证模式(管理端开关,server_config.json 持久化):模拟上游开启
|
- 强验证模式(管理端开关,server_config.json 持久化):模拟上游开启
|
||||||
签名校验后的行为——没有真实 access_token 的凭据直接拒绝发起请求,
|
签名校验后的行为——没有真实 access_token 的凭据直接拒绝发起请求,
|
||||||
提前给出明确错误,而不是发出必然失败的请求。
|
提前给出明确错误,而不是发出必然失败的请求。
|
||||||
"""
|
"""
|
||||||
import base64
|
import base64
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
import requests
|
import requests
|
||||||
import gzip
|
import gzip
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# 旧占位签名值(仅用于识别"未配置 accessToken"的存量配置,不再对外发送)
|
# 旧占位签名值(仅用于识别"未配置 accessToken"的存量配置,不再对外发送)
|
||||||
_DUMMY_SIGNATURE = "xiaobai"
|
_DUMMY_SIGNATURE = "xiaobai"
|
||||||
|
|
||||||
|
|
||||||
def fake_signature(timestamp: str, token_id: str) -> str:
|
def fake_signature(timestamp: str, token_id: str) -> str:
|
||||||
"""未配置 accessToken 时生成形似合法的签名:40 位小写 hex(sha1 输出格式),
|
"""未配置 accessToken 时生成形似合法的签名:40 位小写 hex(sha1 输出格式),
|
||||||
且随时间戳/凭据变化,与真实流量的日志特征一致,避免上游从日志中识别出异常固定值。"""
|
且随时间戳/凭据变化,与真实流量的日志特征一致,避免上游从日志中识别出异常固定值。"""
|
||||||
return hashlib.sha1(f"{timestamp}{token_id}".encode("utf-8")).hexdigest()
|
return hashlib.sha1(f"{timestamp}{token_id}".encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
BASE_URL = "https://bike.sdlongren.com"
|
BASE_URL = "https://bike.sdlongren.com"
|
||||||
|
|
||||||
# 强验证开关的持久化文件
|
# 强验证开关的持久化文件
|
||||||
_SERVER_CONFIG_PATH = Path(__file__).parent / "server_config.json"
|
_SERVER_CONFIG_PATH = Path(__file__).parent / "server_config.json"
|
||||||
|
|
||||||
# 从配置文件加载全局凭据
|
# 从配置文件加载全局凭据
|
||||||
_TOKEN_CONFIG_PATH = Path(__file__).parent / "token_config.txt"
|
_TOKEN_CONFIG_PATH = Path(__file__).parent / "token_config.txt"
|
||||||
|
|
||||||
|
|
||||||
# ========== 强验证开关 ==========
|
# ========== 强验证开关 ==========
|
||||||
def _load_server_config() -> dict:
|
def _load_server_config() -> dict:
|
||||||
try:
|
try:
|
||||||
if _SERVER_CONFIG_PATH.exists():
|
if _SERVER_CONFIG_PATH.exists():
|
||||||
return json.loads(_SERVER_CONFIG_PATH.read_text("utf-8"))
|
return json.loads(_SERVER_CONFIG_PATH.read_text("utf-8"))
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|
||||||
def is_strict_mode() -> bool:
|
def is_strict_mode() -> bool:
|
||||||
"""上游强签名验证开关:开启后无真实 accessToken 的凭据将被拒绝发起请求"""
|
"""上游强签名验证开关:开启后无真实 accessToken 的凭据将被拒绝发起请求"""
|
||||||
return bool(_load_server_config().get("require_access_token"))
|
return bool(_load_server_config().get("require_access_token"))
|
||||||
|
|
||||||
|
|
||||||
def set_strict_mode(enabled: bool) -> bool:
|
def set_strict_mode(enabled: bool) -> bool:
|
||||||
try:
|
try:
|
||||||
cfg = _load_server_config()
|
cfg = _load_server_config()
|
||||||
cfg["require_access_token"] = bool(enabled)
|
cfg["require_access_token"] = bool(enabled)
|
||||||
_SERVER_CONFIG_PATH.write_text(json.dumps(cfg, ensure_ascii=False, indent=2),
|
_SERVER_CONFIG_PATH.write_text(json.dumps(cfg, ensure_ascii=False, indent=2),
|
||||||
encoding="utf-8")
|
encoding="utf-8")
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[强验证开关] 保存失败: {e}")
|
print(f"[强验证开关] 保存失败: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def has_real_access_token(access_token) -> bool:
|
def has_real_access_token(access_token) -> bool:
|
||||||
"""是否为可用于计算签名的真实 accessToken(排除空值与占位符)"""
|
"""是否为可用于计算签名的真实 accessToken(排除空值与占位符)"""
|
||||||
return bool(access_token) and access_token != _DUMMY_SIGNATURE
|
return bool(access_token) and access_token != _DUMMY_SIGNATURE
|
||||||
|
|
||||||
|
|
||||||
def parse_access_token_expiry(access_token) -> dict:
|
def parse_access_token_expiry(access_token) -> dict:
|
||||||
"""从 accessToken(JWT)解析登录态有效期。
|
"""从 accessToken(JWT)解析登录态有效期。
|
||||||
|
|
||||||
小程序登录响应中的 accessToken 是 RS256 JWT,payload 里带标准
|
小程序登录响应中的 accessToken 是 RS256 JWT,payload 里带标准
|
||||||
iat / nbf / exp(实测有效期 30 天)。只解码不验签——我们只需要
|
iat / nbf / exp(实测有效期 30 天)。只解码不验签——我们只需要
|
||||||
展示大致过期时间,签名校验由上游负责。
|
展示大致过期时间,签名校验由上游负责。
|
||||||
返回:{"parseable": bool, "expire_at": ts|None, "expire_time": "YYYY-MM-DD HH:MM"|None,
|
返回:{"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}
|
"remaining_seconds": int|None, "source": "exp"|"iat+30d"|None, "reason": str}
|
||||||
"""
|
"""
|
||||||
import base64 as _b64
|
import base64 as _b64
|
||||||
import datetime as _dt
|
import datetime as _dt
|
||||||
import json as _json
|
import json as _json
|
||||||
|
|
||||||
token = (access_token or "").strip()
|
token = (access_token or "").strip()
|
||||||
tz = _dt.timezone(_dt.timedelta(hours=8))
|
tz = _dt.timezone(_dt.timedelta(hours=8))
|
||||||
result = {"parseable": False, "expire_at": None, "expire_time": None,
|
result = {"parseable": False, "expire_at": None, "expire_time": None,
|
||||||
"remaining_seconds": None, "source": None, "reason": ""}
|
"remaining_seconds": None, "source": None, "reason": ""}
|
||||||
|
|
||||||
def _fmt(ts: int) -> str:
|
def _fmt(ts: int) -> str:
|
||||||
return _dt.datetime.fromtimestamp(ts, tz).strftime("%Y-%m-%d %H:%M")
|
return _dt.datetime.fromtimestamp(ts, tz).strftime("%Y-%m-%d %H:%M")
|
||||||
|
|
||||||
if not has_real_access_token(token):
|
if not has_real_access_token(token):
|
||||||
result["reason"] = "未填写 AccessToken"
|
result["reason"] = "未填写 AccessToken"
|
||||||
return result
|
return result
|
||||||
parts = token.split(".")
|
parts = token.split(".")
|
||||||
if len(parts) != 3 or not token.startswith("ey"):
|
if len(parts) != 3 or not token.startswith("ey"):
|
||||||
result["reason"] = "不是标准 JWT 格式,无法解析过期时间"
|
result["reason"] = "不是标准 JWT 格式,无法解析过期时间"
|
||||||
return result
|
return result
|
||||||
try:
|
try:
|
||||||
pad = parts[1] + "=" * (-len(parts[1]) % 4)
|
pad = parts[1] + "=" * (-len(parts[1]) % 4)
|
||||||
payload = _json.loads(_b64.urlsafe_b64decode(pad))
|
payload = _json.loads(_b64.urlsafe_b64decode(pad))
|
||||||
except Exception:
|
except Exception:
|
||||||
result["reason"] = "JWT payload 解码失败"
|
result["reason"] = "JWT payload 解码失败"
|
||||||
return result
|
return result
|
||||||
|
|
||||||
exp = payload.get("exp") if isinstance(payload, dict) else None
|
exp = payload.get("exp") if isinstance(payload, dict) else None
|
||||||
iat = payload.get("iat") if isinstance(payload, dict) else None
|
iat = payload.get("iat") if isinstance(payload, dict) else None
|
||||||
try:
|
try:
|
||||||
exp = int(exp) if exp is not None else None
|
exp = int(exp) if exp is not None else None
|
||||||
iat = int(iat) if iat is not None else None
|
iat = int(iat) if iat is not None else None
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
exp = iat = None
|
exp = iat = None
|
||||||
|
|
||||||
if exp:
|
if exp:
|
||||||
result.update(parseable=True, expire_at=exp, expire_time=_fmt(exp),
|
result.update(parseable=True, expire_at=exp, expire_time=_fmt(exp),
|
||||||
source="exp")
|
source="exp")
|
||||||
elif iat:
|
elif iat:
|
||||||
expire = iat + 30 * 86400 # 实测 accessToken 有效期 30 天
|
expire = iat + 30 * 86400 # 实测 accessToken 有效期 30 天
|
||||||
result.update(parseable=True, expire_at=expire, expire_time=_fmt(expire),
|
result.update(parseable=True, expire_at=expire, expire_time=_fmt(expire),
|
||||||
source="iat+30d")
|
source="iat+30d")
|
||||||
else:
|
else:
|
||||||
result["reason"] = "JWT 中没有 exp/iat 字段,无法推算有效期"
|
result["reason"] = "JWT 中没有 exp/iat 字段,无法推算有效期"
|
||||||
return result
|
return result
|
||||||
|
|
||||||
result["remaining_seconds"] = int(result["expire_at"] - _dt.datetime.now(tz).timestamp())
|
result["remaining_seconds"] = int(result["expire_at"] - _dt.datetime.now(tz).timestamp())
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def _strict_reject() -> dict:
|
def _strict_reject() -> dict:
|
||||||
return {"rtn_code": 403,
|
return {"rtn_code": 403,
|
||||||
"message": "已开启上游强签名验证:请先填写 AccessToken(从微信小程序登录响应中获取)"}
|
"message": "已开启上游强签名验证:请先填写 AccessToken(从微信小程序登录响应中获取)"}
|
||||||
|
|
||||||
|
|
||||||
def _load_token_config():
|
def _load_token_config():
|
||||||
"""从 token_config.txt 加载全局凭据。
|
"""从 token_config.txt 加载全局凭据。
|
||||||
|
|
||||||
token_id:必填(重新登录小程序会失效,单会话策略)。
|
token_id:必填(重新登录小程序会失效,单会话策略)。
|
||||||
access_token(旧键名 wx_signature 兼容读取):选填,用于实时计算签名。
|
access_token(旧键名 wx_signature 兼容读取):选填,用于实时计算签名。
|
||||||
"""
|
"""
|
||||||
config = {"token_id": "", "access_token": ""}
|
config = {"token_id": "", "access_token": ""}
|
||||||
try:
|
try:
|
||||||
if _TOKEN_CONFIG_PATH.exists():
|
if _TOKEN_CONFIG_PATH.exists():
|
||||||
for line in _TOKEN_CONFIG_PATH.read_text("utf-8").splitlines():
|
for line in _TOKEN_CONFIG_PATH.read_text("utf-8").splitlines():
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if line and not line.startswith("#") and "=" in line:
|
if line and not line.startswith("#") and "=" in line:
|
||||||
k, v = line.split("=", 1)
|
k, v = line.split("=", 1)
|
||||||
k = k.strip()
|
k = k.strip()
|
||||||
if k == "wx_signature": # 旧配置键名兼容
|
if k == "wx_signature": # 旧配置键名兼容
|
||||||
k = "access_token"
|
k = "access_token"
|
||||||
config[k] = v.strip()
|
config[k] = v.strip()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
_TOKEN_CONFIG = _load_token_config()
|
_TOKEN_CONFIG = _load_token_config()
|
||||||
_GLOBAL_TOKEN_ID = _TOKEN_CONFIG.get("token_id", "")
|
_GLOBAL_TOKEN_ID = _TOKEN_CONFIG.get("token_id", "")
|
||||||
_GLOBAL_ACCESS_TOKEN = _TOKEN_CONFIG.get("access_token", "")
|
_GLOBAL_ACCESS_TOKEN = _TOKEN_CONFIG.get("access_token", "")
|
||||||
|
|
||||||
# 全局凭据只来自 token_config.txt / 管理后台保存,代码中不硬编码
|
# 全局凭据只来自 token_config.txt / 管理后台保存,代码中不硬编码
|
||||||
if not _GLOBAL_TOKEN_ID:
|
if not _GLOBAL_TOKEN_ID:
|
||||||
print("[全局凭据] 警告: token_config.txt 中未配置 token_id,"
|
print("[全局凭据] 警告: token_config.txt 中未配置 token_id,"
|
||||||
"地图采集等全局请求将无法通过上游校验,请在管理后台填写")
|
"地图采集等全局请求将无法通过上游校验,请在管理后台填写")
|
||||||
|
|
||||||
HEADERS = {
|
HEADERS = {
|
||||||
"Host": "bike.sdlongren.com",
|
"Host": "bike.sdlongren.com",
|
||||||
"hsf-x-signature": "",
|
"hsf-x-signature": "",
|
||||||
"hsf-x-timestamp": "",
|
"hsf-x-timestamp": "",
|
||||||
"hsf-x-tokenid": _GLOBAL_TOKEN_ID,
|
"hsf-x-tokenid": _GLOBAL_TOKEN_ID,
|
||||||
"xweb_xhr": "1",
|
"xweb_xhr": "1",
|
||||||
"platform": "xiaobai",
|
"platform": "xiaobai",
|
||||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
"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",
|
"(KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 MicroMessenger/7.0",
|
||||||
"content-type": "application/json",
|
"content-type": "application/json",
|
||||||
"accept": "*/*",
|
"accept": "*/*",
|
||||||
"accept-language": "*",
|
"accept-language": "*",
|
||||||
"sec-fetch-site": "cross-site",
|
"sec-fetch-site": "cross-site",
|
||||||
"sec-fetch-mode": "cors",
|
"sec-fetch-mode": "cors",
|
||||||
"sec-fetch-dest": "empty",
|
"sec-fetch-dest": "empty",
|
||||||
"referer": "https://servicewechat.com/wx10426ca961518f43/108/page-frame.html",
|
"referer": "https://servicewechat.com/wx10426ca961518f43/108/page-frame.html",
|
||||||
}
|
}
|
||||||
|
|
||||||
SEARCH_BIKE_URL = "https://bike.sdlongren.com/project/search_bicycle"
|
SEARCH_BIKE_URL = "https://bike.sdlongren.com/project/search_bicycle"
|
||||||
SEARCH_HEADERS = {
|
SEARCH_HEADERS = {
|
||||||
"Host": "bike.sdlongren.com",
|
"Host": "bike.sdlongren.com",
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"Accept": "*/*",
|
"Accept": "*/*",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def build_sign_string(method: str, path: str, timestamp: str, token_id: str,
|
def build_sign_string(method: str, path: str, timestamp: str, token_id: str,
|
||||||
params: dict = None) -> str:
|
params: dict = None) -> str:
|
||||||
"""还原小程序 c(method, path, ts, params, needToken) 的签名串"""
|
"""还原小程序 c(method, path, ts, params, needToken) 的签名串"""
|
||||||
s = f"{method.upper()}$Hsf-X-Timestamp:{timestamp}Hsf-X-TokenId:{token_id}${path}"
|
s = f"{method.upper()}$Hsf-X-Timestamp:{timestamp}Hsf-X-TokenId:{token_id}${path}"
|
||||||
if params:
|
if params:
|
||||||
s += "?"
|
s += "?"
|
||||||
for k in sorted(params.keys()):
|
for k in sorted(params.keys()):
|
||||||
v = params[k]
|
v = params[k]
|
||||||
# 与小程序一致:空字符串值只拼 key,嵌套对象/数组跳过
|
# 与小程序一致:空字符串值只拼 key,嵌套对象/数组跳过
|
||||||
if not k or (isinstance(v, str) and v == ""):
|
if not k or (isinstance(v, str) and v == ""):
|
||||||
s += f"{k}&"
|
s += f"{k}&"
|
||||||
elif isinstance(v, (dict, list)):
|
elif isinstance(v, (dict, list)):
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
s += f"{k}={v}&"
|
s += f"{k}={v}&"
|
||||||
s = s.rstrip("&")
|
s = s.rstrip("&")
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
def compute_signature(access_token: str, method: str, path: str, timestamp: str,
|
def compute_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||||
token_id: str, params: dict = None) -> str:
|
token_id: str, params: dict = None) -> str:
|
||||||
"""小程序算法:sha1(accessToken + base64(sign_str))"""
|
"""小程序算法:sha1(accessToken + base64(sign_str))"""
|
||||||
sign_str = build_sign_string(method, path, timestamp, token_id, params)
|
sign_str = build_sign_string(method, path, timestamp, token_id, params)
|
||||||
b64 = base64.b64encode(sign_str.encode("utf-8")).decode("ascii")
|
b64 = base64.b64encode(sign_str.encode("utf-8")).decode("ascii")
|
||||||
return hashlib.sha1(f"{access_token}{b64}".encode("utf-8")).hexdigest()
|
return hashlib.sha1(f"{access_token}{b64}".encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def make_signature(access_token: str, method: str, path: str, timestamp: str,
|
def make_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||||
token_id: str, params: dict = None) -> str:
|
token_id: str, params: dict = None) -> str:
|
||||||
"""有真实 accessToken 就按小程序算法实时签名;
|
"""有真实 accessToken 就按小程序算法实时签名;
|
||||||
没有则生成形似合法的 sha1 签名(40 位 hex、随请求变化),防上游日志识别。"""
|
没有则生成形似合法的 sha1 签名(40 位 hex、随请求变化),防上游日志识别。"""
|
||||||
if has_real_access_token(access_token):
|
if has_real_access_token(access_token):
|
||||||
return compute_signature(access_token, method, path, timestamp,
|
return compute_signature(access_token, method, path, timestamp,
|
||||||
token_id, params)
|
token_id, params)
|
||||||
return fake_signature(timestamp, token_id)
|
return fake_signature(timestamp, token_id)
|
||||||
|
|
||||||
|
|
||||||
def get_headers(timestamp: str = None) -> dict:
|
def get_headers(timestamp: str = None) -> dict:
|
||||||
"""生成带时间戳的请求头"""
|
"""生成带时间戳的请求头"""
|
||||||
ts = timestamp or str(int(time.time()))
|
ts = timestamp or str(int(time.time()))
|
||||||
headers = HEADERS.copy()
|
headers = HEADERS.copy()
|
||||||
headers["hsf-x-timestamp"] = ts
|
headers["hsf-x-timestamp"] = ts
|
||||||
return headers
|
return headers
|
||||||
|
|
||||||
|
|
||||||
def get_signature_headers(timestamp: str = None) -> dict:
|
def get_signature_headers(timestamp: str = None) -> dict:
|
||||||
"""车辆查询接口(/project/search_bicycle)用的简化签名头。
|
"""车辆查询接口(/project/search_bicycle)用的简化签名头。
|
||||||
有全局 accessToken 时按小程序算法计算(针对该路径);否则生成
|
有全局 accessToken 时按小程序算法计算(针对该路径);否则生成
|
||||||
sha1(时间戳+token_id) 占位值(上游目前不校验)。"""
|
sha1(时间戳+token_id) 占位值(上游目前不校验)。"""
|
||||||
ts = timestamp or str(int(time.time()))
|
ts = timestamp or str(int(time.time()))
|
||||||
token_id = HEADERS.get("hsf-x-tokenid", "")
|
token_id = HEADERS.get("hsf-x-tokenid", "")
|
||||||
if has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
if has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||||
sig = compute_signature(_GLOBAL_ACCESS_TOKEN, "POST", "/project/search_bicycle",
|
sig = compute_signature(_GLOBAL_ACCESS_TOKEN, "POST", "/project/search_bicycle",
|
||||||
ts, token_id)
|
ts, token_id)
|
||||||
else:
|
else:
|
||||||
sig = fake_signature(ts, token_id)
|
sig = fake_signature(ts, token_id)
|
||||||
return {
|
return {
|
||||||
"hsf-x-timestamp": ts,
|
"hsf-x-timestamp": ts,
|
||||||
"hsf-x-tokenid": token_id,
|
"hsf-x-tokenid": token_id,
|
||||||
"hsf-x-signature": sig,
|
"hsf-x-signature": sig,
|
||||||
"platform": "xiaobai",
|
"platform": "xiaobai",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _normalize_token_invalid(result: dict, scope: str):
|
def _normalize_token_invalid(result: dict, scope: str):
|
||||||
"""上游返回 102001(token_id 失效,通常是小程序重新登录把旧会话踢掉)时
|
"""上游返回 102001(token_id 失效,通常是小程序重新登录把旧会话踢掉)时
|
||||||
统一改写响应:scope='user' 面向用户提示重新配置;scope='global' 面向管理员。
|
统一改写响应:scope='user' 面向用户提示重新配置;scope='global' 面向管理员。
|
||||||
注意 global 文案刻意不含 Token 字样,避免前端误弹用户级凭据弹窗。"""
|
注意 global 文案刻意不含 Token 字样,避免前端误弹用户级凭据弹窗。"""
|
||||||
if isinstance(result, dict) and result.get("rtn_code") == 102001:
|
if isinstance(result, dict) and result.get("rtn_code") == 102001:
|
||||||
result["token_invalid"] = True
|
result["token_invalid"] = True
|
||||||
if scope == "user":
|
if scope == "user":
|
||||||
result["message"] = "Token失效,微信凭据已过期,请在个人中心重新配置"
|
result["message"] = "Token失效,微信凭据已过期,请在个人中心重新配置"
|
||||||
else:
|
else:
|
||||||
result["message"] = "地图数据暂不可用:服务器全局凭据已失效,请联系管理员更新"
|
result["message"] = "地图数据暂不可用:服务器全局凭据已失效,请联系管理员更新"
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def request_api(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
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."""
|
"""Share global map reads across users, collection jobs and worker processes."""
|
||||||
if method.upper() == "GET" and path == "/project/map":
|
if method.upper() == "GET" and path == "/project/map":
|
||||||
from map_cache import shared_map_cache
|
from map_cache import shared_map_cache
|
||||||
bike_type = str((params or {}).get("type", "1")).strip()
|
bike_type = str((params or {}).get("type", "1")).strip()
|
||||||
return shared_map_cache.get(bike_type, lambda: _request_api_uncached(
|
return shared_map_cache.get(bike_type, lambda: _request_api_uncached(
|
||||||
method, path, params={**(params or {}), "type": bike_type}, data=data))
|
method, path, params={**(params or {}), "type": bike_type}, data=data))
|
||||||
return _request_api_uncached(method, path, params=params, 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:
|
def _request_api_uncached(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
||||||
"""通用 API 请求(使用全局凭据;强验证模式下必须有全局 accessToken)"""
|
"""通用 API 请求(使用全局凭据;强验证模式下必须有全局 accessToken)"""
|
||||||
if is_strict_mode() and not has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
if is_strict_mode() and not has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||||
return _strict_reject()
|
return _strict_reject()
|
||||||
url = f"{BASE_URL}{path}"
|
url = f"{BASE_URL}{path}"
|
||||||
ts = str(int(time.time()))
|
ts = str(int(time.time()))
|
||||||
token_id = HEADERS["hsf-x-tokenid"]
|
token_id = HEADERS["hsf-x-tokenid"]
|
||||||
headers = get_headers(ts)
|
headers = get_headers(ts)
|
||||||
headers["hsf-x-signature"] = make_signature(
|
headers["hsf-x-signature"] = make_signature(
|
||||||
_GLOBAL_ACCESS_TOKEN, method, path, ts, token_id,
|
_GLOBAL_ACCESS_TOKEN, method, path, ts, token_id,
|
||||||
params if method.upper() == "GET" else data)
|
params if method.upper() == "GET" else data)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if method.upper() == "GET":
|
if method.upper() == "GET":
|
||||||
resp = requests.get(url, params=params, headers=headers,
|
resp = requests.get(url, params=params, headers=headers,
|
||||||
timeout=10, verify=True)
|
timeout=10, verify=True)
|
||||||
else:
|
else:
|
||||||
resp = requests.post(url, json=data, headers=headers,
|
resp = requests.post(url, json=data, headers=headers,
|
||||||
timeout=10, verify=True)
|
timeout=10, verify=True)
|
||||||
content = resp.content
|
content = resp.content
|
||||||
if resp.headers.get("Content-Encoding") == "gzip" or content[:2] == b'\x1f\x8b':
|
if resp.headers.get("Content-Encoding") == "gzip" or content[:2] == b'\x1f\x8b':
|
||||||
try:
|
try:
|
||||||
content = gzip.decompress(content)
|
content = gzip.decompress(content)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return _normalize_token_invalid(json.loads(content), "global")
|
return _normalize_token_invalid(json.loads(content), "global")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"error": str(e), "rtn_code": -1}
|
return {"error": str(e), "rtn_code": -1}
|
||||||
|
|
||||||
|
|
||||||
def request_with_user_auth(user_id: int, method: str, path: str,
|
def request_with_user_auth(user_id: int, method: str, path: str,
|
||||||
params: dict = None, data: dict = None,
|
params: dict = None, data: dict = None,
|
||||||
_silent: bool = False) -> dict:
|
_silent: bool = False) -> dict:
|
||||||
"""使用用户凭据(token_id 必填 + access_token 选填)发起 API 请求"""
|
"""使用用户凭据(token_id 必填 + access_token 选填)发起 API 请求"""
|
||||||
from db import get_user_auth
|
from db import get_user_auth
|
||||||
token_id, access_token = get_user_auth(user_id)
|
token_id, access_token = get_user_auth(user_id)
|
||||||
if not token_id:
|
if not token_id:
|
||||||
return {"rtn_code": 401, "message": "用户未配置 Token ID"}
|
return {"rtn_code": 401, "message": "用户未配置 Token ID"}
|
||||||
if is_strict_mode() and not has_real_access_token(access_token):
|
if is_strict_mode() and not has_real_access_token(access_token):
|
||||||
return _strict_reject()
|
return _strict_reject()
|
||||||
|
|
||||||
ts = str(int(time.time()))
|
ts = str(int(time.time()))
|
||||||
headers = dict(HEADERS)
|
headers = dict(HEADERS)
|
||||||
headers["hsf-x-timestamp"] = ts
|
headers["hsf-x-timestamp"] = ts
|
||||||
headers["hsf-x-tokenid"] = token_id
|
headers["hsf-x-tokenid"] = token_id
|
||||||
headers["hsf-x-signature"] = make_signature(
|
headers["hsf-x-signature"] = make_signature(
|
||||||
access_token, method, path, ts, token_id,
|
access_token, method, path, ts, token_id,
|
||||||
params if method.upper() == "GET" else data)
|
params if method.upper() == "GET" else data)
|
||||||
|
|
||||||
url = f"{BASE_URL}{path}"
|
url = f"{BASE_URL}{path}"
|
||||||
|
|
||||||
if not _silent:
|
if not _silent:
|
||||||
from db import get_db
|
from db import get_db
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,))
|
cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,))
|
||||||
row = cursor.fetchone()
|
row = cursor.fetchone()
|
||||||
conn.close()
|
conn.close()
|
||||||
user_email = row["email"] if row else None
|
user_email = row["email"] if row else None
|
||||||
print(f"[request_with_user_auth] user={user_email}, url={url}")
|
print(f"[request_with_user_auth] user={user_email}, url={url}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if method.upper() == "GET":
|
if method.upper() == "GET":
|
||||||
resp = requests.get(url, params=params, headers=headers,
|
resp = requests.get(url, params=params, headers=headers,
|
||||||
timeout=10, verify=True)
|
timeout=10, verify=True)
|
||||||
else:
|
else:
|
||||||
resp = requests.request(method, url, params=params, json=data,
|
resp = requests.request(method, url, params=params, json=data,
|
||||||
headers=headers, timeout=10, verify=True)
|
headers=headers, timeout=10, verify=True)
|
||||||
if not _silent:
|
if not _silent:
|
||||||
print(f"[request_with_user_auth] response status={resp.status_code}, "
|
print(f"[request_with_user_auth] response status={resp.status_code}, "
|
||||||
f"body={resp.text[:200]}")
|
f"body={resp.text[:200]}")
|
||||||
return _normalize_token_invalid(resp.json(), "user")
|
return _normalize_token_invalid(resp.json(), "user")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if not _silent:
|
if not _silent:
|
||||||
print(f"[request_with_user_auth] request error: {e}")
|
print(f"[request_with_user_auth] request error: {e}")
|
||||||
return {"rtn_code": -1, "error": str(e)}
|
return {"rtn_code": -1, "error": str(e)}
|
||||||
|
|
||||||
|
|
||||||
def get_token_config():
|
def get_token_config():
|
||||||
"""获取当前全局凭据"""
|
"""获取当前全局凭据"""
|
||||||
return {
|
return {
|
||||||
"token_id": HEADERS.get("hsf-x-tokenid", ""),
|
"token_id": HEADERS.get("hsf-x-tokenid", ""),
|
||||||
"access_token": _GLOBAL_ACCESS_TOKEN,
|
"access_token": _GLOBAL_ACCESS_TOKEN,
|
||||||
"has_access_token": has_real_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):
|
def save_token_config(token_id: str, access_token: str):
|
||||||
"""保存全局凭据到文件并更新内存"""
|
"""保存全局凭据到文件并更新内存"""
|
||||||
global _GLOBAL_ACCESS_TOKEN
|
global _GLOBAL_ACCESS_TOKEN
|
||||||
try:
|
try:
|
||||||
cfg = {
|
cfg = {
|
||||||
"token_id": token_id or "",
|
"token_id": token_id or "",
|
||||||
"access_token": access_token or "",
|
"access_token": access_token or "",
|
||||||
}
|
}
|
||||||
_TOKEN_CONFIG_PATH.write_text(
|
_TOKEN_CONFIG_PATH.write_text(
|
||||||
"# 全局微信凭据\n"
|
"# 全局微信凭据\n"
|
||||||
"# token_id: 登录后服务端下发的会话标识(重新登录小程序会失效,单会话策略)\n"
|
"# token_id: 登录后服务端下发的会话标识(重新登录小程序会失效,单会话策略)\n"
|
||||||
"# access_token: 登录响应中的 accessToken(JWT,30天有效),用于实时计算签名;留空则发占位签名\n"
|
"# access_token: 登录响应中的 accessToken(JWT,30天有效),用于实时计算签名;留空则发占位签名\n"
|
||||||
f"token_id={cfg['token_id']}\n"
|
f"token_id={cfg['token_id']}\n"
|
||||||
f"access_token={cfg['access_token']}\n",
|
f"access_token={cfg['access_token']}\n",
|
||||||
encoding="utf-8")
|
encoding="utf-8")
|
||||||
HEADERS["hsf-x-tokenid"] = cfg["token_id"]
|
HEADERS["hsf-x-tokenid"] = cfg["token_id"]
|
||||||
_GLOBAL_ACCESS_TOKEN = cfg["access_token"]
|
_GLOBAL_ACCESS_TOKEN = cfg["access_token"]
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[token配置] 保存失败: {e}")
|
print(f"[token配置] 保存失败: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
# =====================================================================
|
# =====================================================================
|
||||||
# 上游错误文案 → 用户可读文案
|
# 上游错误文案 → 用户可读文案
|
||||||
# 上游返回的 message 经常是英文原始错误(如 "non")或内部术语,直接透传
|
# 上游返回的 message 经常是英文原始错误(如 "non")或内部术语,直接透传
|
||||||
# 用户看不懂。这里做统一映射;匹配不到时原样返回(上游文案本身可读时
|
# 用户看不懂。这里做统一映射;匹配不到时原样返回(上游文案本身可读时
|
||||||
# 保持原样最安全)。所有面向用户的出口建议走这个函数。
|
# 保持原样最安全)。所有面向用户的出口建议走这个函数。
|
||||||
# =====================================================================
|
# =====================================================================
|
||||||
|
|
||||||
_UPSTREAM_MESSAGE_MAP = (
|
_UPSTREAM_MESSAGE_MAP = (
|
||||||
# (命中关键词列表, 展示文案, 类别) 类别: occupied=车辆被占用 / unpaid=未支付
|
# (命中关键词列表, 展示文案, 类别) 类别: occupied=车辆被占用 / unpaid=未支付
|
||||||
# 认证/凭据
|
# 认证/凭据
|
||||||
(("token", "登录"), "登录状态已过期,请重新登录并更新凭据", "auth"),
|
(("token", "登录"), "登录状态已过期,请重新登录并更新凭据", "auth"),
|
||||||
(("signature", "签名"), "请求签名校验失败,请重新登录小程序并更新 AccessToken", "auth"),
|
(("signature", "签名"), "请求签名校验失败,请重新登录小程序并更新 AccessToken", "auth"),
|
||||||
# 车辆状态
|
# 车辆状态
|
||||||
(("使用中", "骑行中"), "这辆车正在被别人骑行,换一辆试试", "occupied"),
|
(("使用中", "骑行中"), "这辆车正在被别人骑行,换一辆试试", "occupied"),
|
||||||
(("占用",), "这辆车当前被占用,换一辆试试", "occupied"),
|
(("占用",), "这辆车当前被占用,换一辆试试", "occupied"),
|
||||||
(("已被", "锁定"), "这辆车已被锁定或预约,换一辆试试", "occupied"),
|
(("已被", "锁定"), "这辆车已被锁定或预约,换一辆试试", "occupied"),
|
||||||
# 订单/支付
|
# 订单/支付
|
||||||
(("未支付", "待支付"), "你有一笔未支付的订单,请先支付后再用车", "unpaid"),
|
(("未支付", "待支付"), "你有一笔未支付的订单,请先支付后再用车", "unpaid"),
|
||||||
(("余额", "欠费"), "账户余额不足,请先充值", "unpaid"),
|
(("余额", "欠费"), "账户余额不足,请先充值", "unpaid"),
|
||||||
# 业务拒绝
|
# 业务拒绝
|
||||||
(("超出", "范围"), "当前位置不在服务区内,请到规定的还车点操作", "deny"),
|
(("超出", "范围"), "当前位置不在服务区内,请到规定的还车点操作", "deny"),
|
||||||
(("频繁", "稍后再试"), "操作太频繁了,请稍等几秒再试", "deny"),
|
(("频繁", "稍后再试"), "操作太频繁了,请稍等几秒再试", "deny"),
|
||||||
)
|
)
|
||||||
|
|
||||||
# 保留关键词:内部逻辑(自动开锁避让重试等)需要按类别分支,调用方仍可拿到
|
# 保留关键词:内部逻辑(自动开锁避让重试等)需要按类别分支,调用方仍可拿到
|
||||||
UPSTREAM_MSG_CATEGORY_KEYWORDS = {
|
UPSTREAM_MSG_CATEGORY_KEYWORDS = {
|
||||||
"occupied": ("使用中", "占用", "已被", "骑行", "锁定"),
|
"occupied": ("使用中", "占用", "已被", "骑行", "锁定"),
|
||||||
"unpaid": ("未支付", "待支付", "non"),
|
"unpaid": ("未支付", "待支付", "non"),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def upstream_msg_category(message) -> str:
|
def upstream_msg_category(message) -> str:
|
||||||
"""上游 message 的机器可读类别(occupied/unpaid/auth/deny/'')。"""
|
"""上游 message 的机器可读类别(occupied/unpaid/auth/deny/'')。"""
|
||||||
msg = str(message or "").lower()
|
msg = str(message or "").lower()
|
||||||
for keys, _, cat in _UPSTREAM_MESSAGE_MAP:
|
for keys, _, cat in _UPSTREAM_MESSAGE_MAP:
|
||||||
if any(k in msg for k in keys):
|
if any(k in msg for k in keys):
|
||||||
return cat
|
return cat
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
def friendly_upstream_message(message, fallback="操作失败,请稍后重试"):
|
def friendly_upstream_message(message, fallback="操作失败,请稍后重试"):
|
||||||
"""把上游 message 翻译成用户可读文案;映射不到原样返回(无 fallback)。"""
|
"""把上游 message 翻译成用户可读文案;映射不到原样返回(无 fallback)。"""
|
||||||
msg = str(message or "")
|
msg = str(message or "")
|
||||||
if not msg.strip():
|
if not msg.strip():
|
||||||
return fallback
|
return fallback
|
||||||
for keys, text, _ in _UPSTREAM_MESSAGE_MAP:
|
for keys, text, _ in _UPSTREAM_MESSAGE_MAP:
|
||||||
if any(k in msg for k in keys):
|
if any(k in msg for k in keys):
|
||||||
return text
|
return text
|
||||||
return msg
|
return msg
|
||||||
|
|||||||
Reference in New Issue
Block a user