Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33df0b0b11 | ||
|
|
c6531ba8e3 | ||
|
|
c1014ff912 | ||
|
|
246f81137a | ||
|
|
9bdef68650 | ||
|
|
9b1aac9942 | ||
|
|
7181973c1f | ||
|
|
57eae3ac82 | ||
|
|
ff80c31b04 | ||
|
|
e01bd67cd8 | ||
|
|
e51d77d42a | ||
|
|
75f040d90a | ||
|
|
bd147e9f4b | ||
|
|
d4bedb30e0 | ||
|
|
bec9a19b32 | ||
|
|
bd41866a3d | ||
|
|
be3c8f775e | ||
|
|
e3a8df65f1 | ||
|
|
8fa8847384 | ||
|
|
f0537e446b |
@@ -1,24 +0,0 @@
|
||||
.git
|
||||
.gitignore
|
||||
__pycache__
|
||||
**/__pycache__
|
||||
.pytest_cache
|
||||
node_modules
|
||||
*.db
|
||||
*.db-*
|
||||
*.sqlite*
|
||||
*.zip
|
||||
*.log
|
||||
*.pem
|
||||
*.key
|
||||
*.crt
|
||||
*config.txt*
|
||||
server_config.json
|
||||
secret_key.txt
|
||||
backups
|
||||
downloads
|
||||
artifacts
|
||||
temp
|
||||
tests
|
||||
test_*.py
|
||||
.reasonix
|
||||
@@ -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
|
||||
+17
@@ -12,3 +12,20 @@ server_config.json
|
||||
.reasonix/
|
||||
*.zip
|
||||
*.log
|
||||
temp/
|
||||
.pytest_cache/
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
downloads/*.exe
|
||||
token_config.txt.old-bak
|
||||
scripts/.pack_baseline.json
|
||||
update.zip
|
||||
# ===== 敏感文件:证书 / 私钥 / 凭据一律不进库 =====
|
||||
*.pem
|
||||
*.key
|
||||
*.crt
|
||||
*.ca-bundle
|
||||
token_config.txt
|
||||
*.db
|
||||
artifacts/
|
||||
walk_cache.db
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
FROM python:3.11-slim
|
||||
ENV TZ=Asia/Shanghai PYTHONUNBUFFERED=1 XBNIU_PREVIEW=1 XBNIU_DB_PATH=/data/preview.db PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
WORKDIR /app
|
||||
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g; s|security.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list 2>/dev/null || true
|
||||
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || true
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt gunicorn==23.0.0
|
||||
COPY . .
|
||||
RUN mkdir -p /data
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=20s --timeout=5s --start-period=20s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/healthz', timeout=3)"
|
||||
CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "1", "--threads", "4", "--timeout", "60", "preview_server:app"]
|
||||
@@ -1,188 +1,159 @@
|
||||
# 小白超人电动车地图
|
||||
|
||||
基于 Flask 的共享电动车位置追踪与租赁管理系统。通过微信小程序接口采集车辆位置,提供地图展示、历史轨迹、数据分析与租赁到期提醒功能。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- **车辆位置采集**:自适应频率调用微信小程序接口抓取车辆数据(白天 5-10 分钟/次,夜间 30-60 分钟/次)
|
||||
- **地图展示**:按车辆状态(可用 / 使用中 / 已锁定 / 已预约 / 低电量)分色标记
|
||||
- **地图共享快照**:同一车辆类型的全局地图请求共用 60 秒快照,SQLite 租约合并跨线程/进程的并发刷新;失败也在同一窗口退避,不把过期成功结果当新数据返回。页面按快照到期时间自动刷新,返回前台时立即补刷,更新时间来自当前地图快照。
|
||||
- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹
|
||||
- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图
|
||||
- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知)
|
||||
- **自动清理**:30 天前历史数据自动归档,定期 VACUUM 释放空间
|
||||
|
||||
## 技术栈
|
||||
|
||||
- **后端**:Flask + SQLite(原生 `sqlite3`)
|
||||
- **架构**:Blueprint 分模块(auth / map_api / rental / admin)
|
||||
- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`)
|
||||
- **采集调度**:threading 后台线程 + 自适应间隔
|
||||
- **通知**:SMTP 邮件 + 内部计时器
|
||||
- **前端**:Jinja2 模板 + 百度 BMapGL 地图 + ECharts 图表
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
xbniu_map/
|
||||
├── app.py # 应用入口 + 数据采集调度 + 分析 API
|
||||
├── db.py # SQLite 连接与表初始化
|
||||
├── wechat.py # 微信小程序接口封装
|
||||
├── email_utils.py # 邮件发送
|
||||
├── timer.py # 订单到期计时器管理
|
||||
├── generate_icons.py # 地图标记图标生成
|
||||
├── routes/
|
||||
│ ├── auth.py # 用户注册 / 登录 / 微信授权
|
||||
│ ├── map_api.py # 地图数据接口
|
||||
│ ├── rental.py # 租赁 / 提醒
|
||||
│ └── admin.py # 后台管理
|
||||
├── templates/
|
||||
│ ├── map.html # 主地图页
|
||||
│ ├── analysis.html # 数据分析页
|
||||
│ ├── admin.html # 后台管理页
|
||||
│ └── ring_progress.html # 状态环形图组件
|
||||
├── static/ # 地图标记图标(分色)
|
||||
└── requirements.txt
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
启动前需准备以下敏感文件(不上传到 Git,已在 `.gitignore` 排除):
|
||||
|
||||
| 文件 | 用途 | 示例 |
|
||||
|------|------|------|
|
||||
| `token_config.txt` | 全局默认微信 token | `token_id=1234567` |
|
||||
| `key.pem` / `private.key` | HTTPS 私钥 | `/BEGIN PRIVATE KEY/` |
|
||||
| `cert.pem` / `certificate.crt` / `ca_bundle.crt` | HTTPS 证书链 | `/BEGIN CERTIFICATE/` |
|
||||
|
||||
用户级授权凭据(`token_id` + `wx_signature`)存储在 `users.db` 的 `users` 表中,通过登录后从微信小程序抓包获取。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 1. 安装依赖
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 2. 准备敏感文件(见上方配置说明)
|
||||
|
||||
# 3. 启动服务
|
||||
python app.py
|
||||
# 默认监听 127.0.0.1:98,对外由 nginx 反代提供 HTTPS
|
||||
```
|
||||
|
||||
## 打包分发
|
||||
|
||||
```bash
|
||||
# 重新生成 1.zip(仅源码、模板、必要静态资源、测试和脚本)
|
||||
pwsh -File scripts/pack_zip.ps1
|
||||
```
|
||||
|
||||
打包排除证书/密钥/token/数据库/备份/缓存,以及安装包、截图和运行日志;打包脚本会自动
|
||||
校验关键文件是否在位(campus/alerts/subscribe/export 等新模块缺失会直接报错)。
|
||||
|
||||
## 抓包工具下载
|
||||
|
||||
「填写凭证」等弹窗里的下载按钮指向 `/download/capture-tool.exe`,对应磁盘文件
|
||||
`downloads/xbniu-capture-tool.exe`(约 160MB,不在版本库及源码包 1.zip 中,部署时另行提供)。
|
||||
|
||||
- 公开访问,无需登录:用户注册前就要先拿到工具,否则形成死循环。
|
||||
- 路由带 `conditional=True` 并显式返回 `Accept-Ranges: bytes`,支持断点续传。
|
||||
- 文件缺失时返回 `404 {"rtn_code": 404, "message": "安装包暂未上传"}`。
|
||||
- 微信/QQ/支付宝/钉钉/微博/抖音等内置浏览器会拦截 exe 下载,前端改为弹出
|
||||
「复制链接到外部浏览器」提示。
|
||||
|
||||
**nginx 注意**:大文件经 `proxy_pass` 下载时,若带宽较低可能被默认的
|
||||
`proxy_read_timeout 60s` 中断,建议在对应 `location` 上放宽:
|
||||
|
||||
```nginx
|
||||
location /download/ {
|
||||
proxy_pass http://127.0.0.1:98;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_max_temp_file_size 0; # 不缓冲大文件,直接透传
|
||||
}
|
||||
```
|
||||
|
||||
## 数据库表结构
|
||||
|
||||
| 表 | 用途 |
|
||||
|----|------|
|
||||
| `users` | 用户账号、微信授权凭据 |
|
||||
| `sessions` | 登录会话 token |
|
||||
| `reminders` | 租赁提醒订阅 |
|
||||
| `rentals` | 租车记录 + 多级通知状态(notified_10/5/3/2/1/0)|
|
||||
| `bike_history` | 车辆位置历史(含状态、电量)|
|
||||
| `snapshots` | 整体快照(总数、状态分布)|
|
||||
|
||||
## 核心机制
|
||||
|
||||
### 自适应采集
|
||||
|
||||
```python
|
||||
def get_adaptive_interval():
|
||||
# 夜间(23:00-07:00):1800-3600s(30-60 分钟)
|
||||
# 白天:300-600s(5-10 分钟)
|
||||
```
|
||||
|
||||
后台线程循环执行 `snapshot_bike_positions()`,调用 `/project/map?type=3` 拉取全部车辆,写入 `bike_history`。
|
||||
|
||||
### 数据清理
|
||||
|
||||
每 23 小时执行一次:删除 30 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
||||
|
||||
### 订单到期提醒
|
||||
|
||||
`timer.py` 在启动时恢复未到期的计时器(`restore_active_timers`),并在到期前 10/5/3/2/1/0 分钟触发邮件通知。每条 `rentals` 记录的 `notified_*` 字段标记对应级别是否已发送,避免重复通知。
|
||||
|
||||
## 主要接口
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| POST | `/api/collect_now` | 手动触发一次采集 |
|
||||
| GET | `/api/bike_history?code=xxx` | 查询指定车辆历史轨迹 |
|
||||
| GET | `/api/analysis/overview` | 状态分布 + 时段分布 + Top10 |
|
||||
| GET | `/api/analysis/heatmap?code=xxx` | 热力图数据 |
|
||||
|
||||
具体路由详见 `routes/*.py`。
|
||||
|
||||
## 注意事项
|
||||
|
||||
- `token_id` 与 `wx_signature` 来自微信小程序抓包,**修改后需重启服务或通过后台保存**
|
||||
- `users.db` 包含用户授权信息与历史轨迹,**不可公开**
|
||||
- HTTPS 证书文件(`*.pem` `*.crt` `*.key`)若损坏会导致小程序接口无法访问
|
||||
- 服务监听端口默认 98(非特权端口)
|
||||
|
||||
|
||||
|
||||
## preview 分支(v1.7.0)
|
||||
|
||||
本分支完善了地图状态与电量的一致性、5/8 位车牌查询、定位重试与地图中心查找、最近可用车辆推荐、地图快捷筛选、附近车辆列表、校园地点搜索及常用地点、手机操作与弹窗焦点、订阅规则编辑/复制/最近执行结果、订单筛选与分页、首次使用引导及浅色/深色/跟随系统主题。不包含步行导航。
|
||||
|
||||
### 预览环境
|
||||
|
||||
使用 `Dockerfile.preview`,监听 8080,健康检查 `GET /healthz`。容器以一个 Gunicorn worker、四个线程运行,保持订单与计时器状态一致;预览启动入口会恢复该环境的计时器并启动订阅和凭证告警调度。
|
||||
|
||||
- `XBNIU_PREVIEW=1`:标识预览环境,启用演示与独立测试账号入口。
|
||||
- `XBNIU_DB_PATH=/data/preview.db`:独立数据库;将独立持久卷挂载到 `/data`,不要挂载生产数据库。
|
||||
- **演示体验**:`demo@preview.local` / `preview123`,车辆与开锁、还车等操作使用模拟数据。演示账号不能保存真实微信凭证。
|
||||
- **创建独立测试账号**:每个浏览器获得独立账号和登录令牌;在“微信凭证”中配置自己的 Token ID / AccessToken 后使用真实上游接口,开锁、还车和支付也会真实执行。切换演示体验后再次点击测试账号入口可恢复当前浏览器的测试账号。清理浏览器存储会丢失该入口的登录状态。
|
||||
- 普通账号的真实请求没有全局外发拦截;各账号分别使用自己的微信凭证,预览地图按账号和车型缓存 60 秒,失败退避 5 秒。
|
||||
- 测试账号可在凭证页填写真实告警邮箱。邮件配置支持 `SMTP_HOST`、`SMTP_PORT`、`SMTP_USER`、`SMTP_PASS`、`SMTP_STARTTLS` 环境变量;未配置 SMTP 时不会宣称邮件发送成功。
|
||||
- `.dockerignore` 排除数据库、证书、密钥、配置凭据、备份、下载与截图,镜像不携带本地生产数据。
|
||||
|
||||
### 前端结构
|
||||
|
||||
`bike-data.js` 管理车辆规则;`map.js` 管理地图渲染与定位;`map-account.js`、`map-orders.js`、`map-history.js`、`map-subscriptions.js`、`map-rental.js`、`map-sharing.js` 分别管理业务功能;`map-discovery.js` 管理筛选、附近列表与常用地点;`api-client.js` 处理请求超时与提交锁;`ui-preferences.js` 和 `ui-dialogs.js` 处理主题及弹窗焦点;`map-boot.js` 负责启动。所有地图资源共用内容哈希版本,更新任一依赖会使整个资源包失效。
|
||||
|
||||
### 验证
|
||||
|
||||
```powershell
|
||||
python -X utf8 -m pytest tests -q
|
||||
node --test tests/test_api_client.cjs tests/test_bike_data.cjs tests/test_bike_clusters.cjs tests/test_map_refresh.cjs tests/test_order_return.cjs tests/test_settings_navigation.cjs
|
||||
```
|
||||
|
||||
浏览器验收采用演示账号;真实上游链路用替身请求验证路由与账号隔离,不在自动化验收中执行真实车辆操作。
|
||||
|
||||
|
||||
### 手机界面
|
||||
|
||||
地图默认只保留找车入口、状态图例、最近车辆按钮和车牌查询。地点、常用地点、筛选与附近列表收进同一个按需展开的亚克力面板;列表与筛选互相切换,选中车辆或点击地图即可收起。定位提示不再悬浮遮挡地图,首次进入也不会主动弹出定位权限请求;已授权的设备会恢复定位。数据分析及演示/真实测试切换位于设置,预览标识缩为校名旁的小标签。
|
||||
# 小白超人电动车地图
|
||||
|
||||
基于 Flask 的共享电动车位置追踪与租赁管理系统。通过微信小程序接口采集车辆位置,提供地图展示、历史轨迹、数据分析与租赁到期提醒功能。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- **车辆位置采集**:自适应频率调用微信小程序接口抓取车辆数据(白天 5-10 分钟/次,夜间 30-60 分钟/次)
|
||||
- **地图展示**:按车辆状态(可用 / 使用中 / 已锁定 / 已预约 / 低电量)分色标记
|
||||
- **地图共享快照**:同一车辆类型的全局地图请求共用 60 秒快照,SQLite 租约合并跨线程/进程的并发刷新;失败也在同一窗口退避,不把过期成功结果当新数据返回。页面按快照到期时间自动刷新,返回前台时立即补刷,更新时间来自当前地图快照。
|
||||
- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹
|
||||
- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图
|
||||
- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知)
|
||||
- **自动清理**:30 天前历史数据自动归档,定期 VACUUM 释放空间
|
||||
|
||||
## 技术栈
|
||||
|
||||
- **后端**:Flask + SQLite(原生 `sqlite3`)
|
||||
- **架构**:Blueprint 分模块(auth / map_api / rental / admin)
|
||||
- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`)
|
||||
- **采集调度**:threading 后台线程 + 自适应间隔
|
||||
- **通知**:SMTP 邮件 + 内部计时器
|
||||
- **前端**:Jinja2 模板 + 百度地图 JS API GL(BMapGL)+ ECharts 图表
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
xbniu_map/
|
||||
├── app.py # 应用入口 + 数据采集调度 + 分析 API
|
||||
├── db.py # SQLite 连接与表初始化
|
||||
├── wechat.py # 微信小程序接口封装
|
||||
├── email_utils.py # 邮件发送
|
||||
├── timer.py # 订单到期计时器管理
|
||||
├── generate_icons.py # 地图标记图标生成
|
||||
├── routes/
|
||||
│ ├── auth.py # 用户注册 / 登录 / 微信授权
|
||||
│ ├── map_api.py # 地图数据接口
|
||||
│ ├── rental.py # 租赁 / 提醒
|
||||
│ └── admin.py # 后台管理
|
||||
├── templates/
|
||||
│ ├── map.html # 主地图页
|
||||
│ ├── analysis.html # 数据分析页
|
||||
│ ├── admin.html # 后台管理页
|
||||
│ └── ring_progress.html # 状态环形图组件
|
||||
├── static/ # 地图标记图标(分色)
|
||||
│ └── js/
|
||||
│ ├── map.js # 主逻辑(地图/定位/订单/卡片/登录等)
|
||||
│ ├── navigation.js # 跟随式导航 + 步行距离精算
|
||||
│ ├── share.js # 共享电动车
|
||||
│ ├── subscribe.js # 车辆订阅
|
||||
│ └── bike-clusters.js# 车辆聚类
|
||||
└── requirements.txt
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
启动前需准备以下敏感文件(不上传到 Git,已在 `.gitignore` 排除):
|
||||
|
||||
| 文件 | 用途 | 示例 |
|
||||
|------|------|------|
|
||||
| `token_config.txt` | 全局默认微信 token | `token_id=1234567` |
|
||||
| `key.pem` / `private.key` | HTTPS 私钥 | `/BEGIN PRIVATE KEY/` |
|
||||
| `cert.pem` / `certificate.crt` / `ca_bundle.crt` | HTTPS 证书链 | `/BEGIN CERTIFICATE/` |
|
||||
|
||||
用户级授权凭据(`token_id` + `wx_signature`)存储在 `users.db` 的 `users` 表中,通过登录后从微信小程序抓包获取。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 1. 安装依赖
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 2. 准备敏感文件(见上方配置说明)
|
||||
|
||||
# 3. 启动服务
|
||||
python app.py
|
||||
# 默认监听 127.0.0.1:98,对外由 nginx 反代提供 HTTPS
|
||||
```
|
||||
|
||||
## 打包分发
|
||||
|
||||
```bash
|
||||
# 重新生成 1.zip(仅源码、模板、必要静态资源、测试和脚本)
|
||||
pwsh -File scripts/pack_zip.ps1
|
||||
```
|
||||
|
||||
打包排除证书/密钥/token/数据库/备份/缓存,以及安装包、截图和运行日志;打包脚本会自动
|
||||
校验关键文件是否在位(campus/alerts/subscribe/export 等新模块缺失会直接报错)。
|
||||
|
||||
## 抓包工具下载
|
||||
|
||||
「填写凭证」等弹窗里的下载按钮指向 `/download/capture-tool.exe`,对应磁盘文件
|
||||
`downloads/xbniu-capture-tool.exe`(约 160MB,不在版本库及源码包 1.zip 中,部署时另行提供)。
|
||||
|
||||
- 公开访问,无需登录:用户注册前就要先拿到工具,否则形成死循环。
|
||||
- 路由带 `conditional=True` 并显式返回 `Accept-Ranges: bytes`,支持断点续传。
|
||||
- 文件缺失时返回 `404 {"rtn_code": 404, "message": "安装包暂未上传"}`。
|
||||
- 微信/QQ/支付宝/钉钉/微博/抖音等内置浏览器会拦截 exe 下载,前端改为弹出
|
||||
「复制链接到外部浏览器」提示。
|
||||
|
||||
**nginx 注意**:大文件经 `proxy_pass` 下载时,若带宽较低可能被默认的
|
||||
`proxy_read_timeout 60s` 中断,建议在对应 `location` 上放宽:
|
||||
|
||||
```nginx
|
||||
location /download/ {
|
||||
proxy_pass http://127.0.0.1:98;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_max_temp_file_size 0; # 不缓冲大文件,直接透传
|
||||
}
|
||||
```
|
||||
|
||||
## 数据库表结构
|
||||
|
||||
| 表 | 用途 |
|
||||
|----|------|
|
||||
| `users` | 用户账号、微信授权凭据 |
|
||||
| `sessions` | 登录会话 token |
|
||||
| `reminders` | 租赁提醒订阅 |
|
||||
| `rentals` | 租车记录 + 多级通知状态(notified_10/5/3/2/1/0)|
|
||||
| `bike_history` | 车辆位置历史(含状态、电量)|
|
||||
| `snapshots` | 整体快照(总数、状态分布)|
|
||||
|
||||
## 核心机制
|
||||
|
||||
### 自适应采集
|
||||
|
||||
```python
|
||||
def get_adaptive_interval():
|
||||
# 夜间(23:00-07:00):1800-3600s(30-60 分钟)
|
||||
# 白天:300-600s(5-10 分钟)
|
||||
```
|
||||
|
||||
后台线程循环执行 `snapshot_bike_positions()`,调用 `/project/map?type=3` 拉取全部车辆,写入 `bike_history`。
|
||||
|
||||
### 数据清理
|
||||
|
||||
每 23 小时执行一次:删除 30 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
||||
|
||||
### 订单到期提醒
|
||||
|
||||
`timer.py` 在启动时恢复未到期的计时器(`restore_active_timers`),并在到期前 10/5/3/2/1/0 分钟触发邮件通知。每条 `rentals` 记录的 `notified_*` 字段标记对应级别是否已发送,避免重复通知。
|
||||
|
||||
## 主要接口
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| POST | `/api/collect_now` | 手动触发一次采集 |
|
||||
| GET | `/api/bike_history?code=xxx` | 查询指定车辆历史轨迹 |
|
||||
| GET | `/api/analysis/overview` | 状态分布 + 时段分布 + Top10 |
|
||||
| GET | `/api/analysis/heatmap?code=xxx` | 热力图数据 |
|
||||
|
||||
具体路由详见 `routes/*.py`。
|
||||
|
||||
## 注意事项
|
||||
|
||||
- `token_id` 与 `wx_signature` 来自微信小程序抓包,**修改后需重启服务或通过后台保存**
|
||||
- `users.db` 包含用户授权信息与历史轨迹,**不可公开**
|
||||
- HTTPS 证书文件(`*.pem` `*.crt` `*.key`)若损坏会导致小程序接口无法访问
|
||||
- 服务监听端口默认 98(非特权端口)
|
||||
|
||||
|
||||
@@ -59,8 +59,16 @@ def set_alert_emails(emails) -> int:
|
||||
return len(cleaned)
|
||||
|
||||
|
||||
# ========== 去重记录 ==========
|
||||
# 免打扰策略(用户要求):同一凭据在整个生命周期内【只发一封】邮件——
|
||||
# 老版本 users 表的 token_id 列带 DEFAULT '1291378',注册时没写这一列的用户
|
||||
# 就被灌了这个假凭据。它不可能来自真实授权,所有告警检查都要跳过。
|
||||
LEGACY_DEFAULT_TOKEN_ID = "1291378"
|
||||
|
||||
|
||||
def _is_legacy_default_token(token_id) -> bool:
|
||||
return str(token_id or "").strip() == LEGACY_DEFAULT_TOKEN_ID
|
||||
|
||||
|
||||
# ========== 去重记录 ==========# 免打扰策略(用户要求):同一凭据在整个生命周期内【只发一封】邮件——
|
||||
# 不管命中的是 1天/1小时/已过期 哪一级。credential_alerts.target 含
|
||||
# 凭据标识(用户 id 或 全局+过期时间戳),用户更新凭据后 target 变化
|
||||
# 才会重新武装。查询时【不看 level】,避免 1day→1hour→expired 连发三封。
|
||||
@@ -69,8 +77,16 @@ def _now_bj_str():
|
||||
|
||||
|
||||
def _sent_already(conn, target, level=None):
|
||||
"""该凭据是否已发过提醒邮件(level 仅保留兼容签名,不再参与过滤)。"""
|
||||
"""该凭据是否已发过这一级别的提醒邮件。
|
||||
|
||||
免打扰口径:同一凭据(target 里带凭据指纹/过期时间)在 1天/1小时 之间只发一封,
|
||||
但 **expired 单独放行一封** —— 否则“还剩 1 天”那封被划掉就再也没有第二次机会。
|
||||
"""
|
||||
try:
|
||||
if level == "expired":
|
||||
return conn.execute(
|
||||
"SELECT 1 FROM credential_alerts WHERE target = ? AND level = 'expired' LIMIT 1",
|
||||
(target,)).fetchone() is not None
|
||||
return conn.execute(
|
||||
"SELECT 1 FROM credential_alerts WHERE target = ? LIMIT 1",
|
||||
(target,)).fetchone() is not None
|
||||
@@ -120,14 +136,13 @@ def _send_alert(recipients, level, owner_desc, expiry):
|
||||
if level == "expired" and not expiry.get("parseable", True):
|
||||
# 未填 AccessToken 的凭据:通过上游探测发现已失效,无法给出过期时刻
|
||||
lead = ("凭据已失效(探测到上游已拒绝该 Token),该账号的开锁/还车/地图数据"
|
||||
"已不可用,请立即在小程序重新登录并更新凭据。"
|
||||
"提示:打开一次微信小程序就会使网页凭据失效。")
|
||||
"已不可用,请到个人中心重新获取并保存凭据。")
|
||||
elif level == "expired":
|
||||
lead = "凭据已过期,该账号的上游接口(地图/开锁/还车/订单检测)已全部失效,请立即在小程序重新登录并更新凭据。"
|
||||
lead = "凭据已过期,该账号的上游接口(地图/开锁/还车/订单检测)已全部失效,请到个人中心更新凭据。"
|
||||
elif level == "1hour":
|
||||
lead = "凭据将在约 1 小时后过期,请尽快在小程序重新登录更新,避免用车高峰失效。"
|
||||
lead = "凭据将在约 1 小时后过期,请尽快更新,避免用车高峰失效。"
|
||||
else:
|
||||
lead = "凭据将在约 1 天后过期,请安排在小程序重新登录更新。"
|
||||
lead = "凭据将在约 1 天后过期,请安排时间更新。"
|
||||
details = [("凭据归属", owner_desc), ("当前级别", level_text),
|
||||
("有效期至", expire_time), ("提醒时间", _now_bj_str())]
|
||||
plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details)
|
||||
@@ -163,6 +178,8 @@ def check_user_credentials():
|
||||
for u in users:
|
||||
if not (u["access_token"] or "").strip():
|
||||
continue # 没填 AccessToken 走 check_user_credentials_alive 的失效探测
|
||||
if _is_legacy_default_token(u["token_id"]):
|
||||
continue # 注册遗留的默认值,不是真凭据
|
||||
expiry = parse_access_token_expiry(u["access_token"])
|
||||
if not expiry.get("parseable") or expiry.get("expire_at") is None:
|
||||
continue
|
||||
@@ -186,44 +203,35 @@ def check_user_credentials():
|
||||
return sent
|
||||
|
||||
|
||||
# 只填了 token_id 的用户:无法解析有效期(三级预警做不了),
|
||||
# 但可以用一次极轻量的上游探测判断凭据「当前是否还活着」,
|
||||
# 死了就发"已失效"邮件。credential_alerts 按 target 去重保证只发一次,
|
||||
# 用户重新配置凭据后 target 变化 → 自动重新武装。
|
||||
# 只填了 token_id 的用户:**不发「凭据失效」邮件**。
|
||||
#
|
||||
# 原因(实测):没有 access_token 时签名只能用假签名(wechat.fake_signature),
|
||||
# 上游对假签名一律回 102001。这跟「token 过期」是同一个错误码,无法区分。
|
||||
# 以前这里把它当过期发信,结果**所有只填 token_id 的用户都会被判过期**,
|
||||
# 上线后给全站发了一批「凭据已过期」的误报邮件。
|
||||
#
|
||||
# 现在的口径:只探测、只记日志,不发信。真正的到期提醒交给
|
||||
# check_user_credentials()(有 access_token 才能解析 exp),不猜。
|
||||
def check_user_credentials_alive():
|
||||
"""探测未填 AccessToken 用户的凭据是否已失效(102001)。返回发送条数。"""
|
||||
from wechat import request_with_user_auth
|
||||
sent = 0
|
||||
"""统计未填 AccessToken 的用户(仅日志,不发邮件、也不探测)。
|
||||
|
||||
没有 access_token 时签名只能用假签名,上游一律回 102001,跟「token 过期」
|
||||
是同一个错误码、无法区分;再去探测只会浪费上游配额,所以这里干脆不请求。
|
||||
真要给这批用户做到期提醒,得先让他们补上 access_token。
|
||||
"""
|
||||
conn = get_db()
|
||||
try:
|
||||
users = conn.execute(
|
||||
"SELECT id, email, token_id, alert_email FROM users "
|
||||
rows = conn.execute(
|
||||
"SELECT id, token_id FROM users "
|
||||
"WHERE token_id IS NOT NULL AND token_id != '' "
|
||||
" AND (access_token IS NULL OR access_token = '')").fetchall()
|
||||
admin_emails = set(get_alert_emails())
|
||||
for u in users:
|
||||
target = f"user-alive:{u['id']}"
|
||||
if _sent_already(conn, target, "expired"):
|
||||
continue
|
||||
try:
|
||||
# /user/info 是最轻的已登录接口;_silent 避免日志刷屏
|
||||
res = request_with_user_auth(u["id"], "GET", "/user/info", _silent=True)
|
||||
except Exception:
|
||||
continue # 网络异常不判死刑,等下一轮
|
||||
if not isinstance(res, dict) or res.get("rtn_code") != 102001:
|
||||
continue # 正常或其他错误(非凭据失效)都不打扰
|
||||
recipients = set(admin_emails)
|
||||
recv = (u["alert_email"] or "").strip() or (u["email"] or "").strip()
|
||||
if recv:
|
||||
recipients.add(recv)
|
||||
if _send_alert(recipients, "expired", f"用户 {u['email']}",
|
||||
{"parseable": False, "expire_time": "未知(未填 AccessToken)"}):
|
||||
_mark_sent(conn, target, "expired")
|
||||
sent += 1
|
||||
finally:
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return sent
|
||||
unknown = [r for r in rows if not _is_legacy_default_token(r["token_id"])]
|
||||
if unknown:
|
||||
print(f"[凭据告警] {len(unknown)} 个用户只有 token_id、没有 access_token,"
|
||||
f"无法核验有效期(到期提醒需要 access_token)")
|
||||
return 0
|
||||
|
||||
|
||||
def check_global_credential():
|
||||
|
||||
@@ -34,7 +34,6 @@ import random
|
||||
import threading
|
||||
import urllib3
|
||||
from pathlib import Path
|
||||
from runtime_mode import PREVIEW_MODE
|
||||
from flask import Flask, jsonify, request, render_template, session
|
||||
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
@@ -51,9 +50,6 @@ def _load_or_create_secret_key() -> str:
|
||||
"""secret_key 不再写死在源码:优先环境变量,否则随机生成一次并持久化到
|
||||
secret_key.txt(已 gitignore)。key 变化只会使管理员后台 session 失效,
|
||||
普通用户登录态存数据库(sessions 表),不受影响。"""
|
||||
if PREVIEW_MODE:
|
||||
import secrets
|
||||
return os.environ.get("XBNIU_SECRET_KEY") or secrets.token_hex(32)
|
||||
env_key = os.environ.get("XBNIU_SECRET_KEY", "").strip()
|
||||
if env_key:
|
||||
return env_key
|
||||
@@ -97,14 +93,6 @@ app.register_blueprint(share_bp)
|
||||
app.register_blueprint(download_bp)
|
||||
app.register_blueprint(export_bp)
|
||||
app.register_blueprint(subscribe_bp)
|
||||
if PREVIEW_MODE:
|
||||
from preview_data import install_preview
|
||||
install_preview(app)
|
||||
|
||||
@app.get("/healthz")
|
||||
def healthz():
|
||||
return jsonify(status="ok", mode="preview" if PREVIEW_MODE else "production")
|
||||
|
||||
|
||||
|
||||
# ========== 未认证数据接口限速 ==========
|
||||
@@ -404,12 +392,31 @@ def api_analysis_heatmap():
|
||||
# 数据分析页/批量车辆轨迹全部 404。以下实现与前端 analysis.html 期望的 JSON 结构对齐。
|
||||
|
||||
# 状态分类(与 map.html / analysis.html 图例一致)
|
||||
_HISTORY_STATES = ["available", "used", "locked", "reserved", "low", "unknown"]
|
||||
_HISTORY_STATES = ["available", "used", "locked", "reserved", "low"]
|
||||
|
||||
|
||||
def _classify_bike_state(state, status, electric):
|
||||
from bike_data import classify
|
||||
return classify(state, status, electric)
|
||||
try:
|
||||
state = int(state)
|
||||
except (TypeError, ValueError):
|
||||
state = 1
|
||||
try:
|
||||
status = int(status)
|
||||
except (TypeError, ValueError):
|
||||
status = 1
|
||||
try:
|
||||
electric = float(electric)
|
||||
except (TypeError, ValueError):
|
||||
electric = 100.0
|
||||
if state == 10 or electric < 20:
|
||||
return "low"
|
||||
if state == 4:
|
||||
return "locked"
|
||||
if state == 2:
|
||||
return "reserved"
|
||||
if state == 1 and status == 1:
|
||||
return "used"
|
||||
return "available"
|
||||
|
||||
|
||||
@app.route("/api/history/stats")
|
||||
@@ -647,35 +654,76 @@ def api_history_heatmap():
|
||||
|
||||
|
||||
# ========== 启动 ==========
|
||||
# 后台线程原来只挂在 `if __name__ == "__main__":` 里,换成 gunicorn/`flask run`
|
||||
# 或任何 WSGI 启动方式时全都不会启动(且静默)——定时采集、订单巡检、
|
||||
# 自动还车、订阅提醒、凭据告警会一起残废。这里收进幂等的 bootstrap(),
|
||||
# WSGI 与 __main__ 都会调用,再由 before_request 兜住「首次请求」。
|
||||
_bootstrap_lock = threading.Lock()
|
||||
_bootstrap_done = False
|
||||
|
||||
|
||||
def bootstrap():
|
||||
"""初始化数据库并启动所有后台线程。幂等:重复调用只会执行一次。"""
|
||||
global _bootstrap_done
|
||||
with _bootstrap_lock:
|
||||
if _bootstrap_done:
|
||||
return False
|
||||
_bootstrap_done = True
|
||||
|
||||
print("[启动] bootstrap: 初始化数据库 + 启动后台线程")
|
||||
try:
|
||||
init_db()
|
||||
except Exception as exc:
|
||||
print(f"[启动] init_db 失败: {exc}")
|
||||
|
||||
steps = [
|
||||
("恢复计时器", restore_active_timers),
|
||||
("补还超期订单", _sweep_on_boot),
|
||||
("订单巡检", start_all_order_checkers),
|
||||
("数据采集", start_snapshot_scheduler),
|
||||
]
|
||||
for name, fn in steps:
|
||||
try:
|
||||
fn()
|
||||
except Exception as exc:
|
||||
print(f"[启动] {name} 失败: {exc}")
|
||||
|
||||
try:
|
||||
from subscribe import start_subscribe_scheduler
|
||||
start_subscribe_scheduler()
|
||||
except Exception as exc:
|
||||
print(f"[启动] 订阅调度失败: {exc}")
|
||||
|
||||
try:
|
||||
from alerts import start_alert_scheduler
|
||||
start_alert_scheduler()
|
||||
except Exception as exc:
|
||||
print(f"[启动] 告警调度失败: {exc}")
|
||||
|
||||
print("[启动] bootstrap 完成")
|
||||
return True
|
||||
|
||||
|
||||
def _sweep_on_boot():
|
||||
"""启动时把「expired=0 且已过期」的僵尸单捞一遍(带 5 分钟节流)。"""
|
||||
try:
|
||||
from timer import sweep_overdue_rentals
|
||||
n = sweep_overdue_rentals(force=True)
|
||||
if n:
|
||||
print(f"[启动] 补还超期订单 {n} 单")
|
||||
except Exception as exc:
|
||||
print(f"[启动] 补还超期订单失败: {exc}")
|
||||
|
||||
|
||||
@app.before_request
|
||||
def _ensure_bootstrap():
|
||||
"""WSGI 部署(gunicorn 等)不会走 __main__,靠首个请求把后台线程拉起来。"""
|
||||
if not _bootstrap_done:
|
||||
bootstrap()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from pathlib import Path
|
||||
|
||||
# 初始化数据库
|
||||
init_db()
|
||||
|
||||
if PREVIEW_MODE:
|
||||
from preview_data import seed_preview
|
||||
seed_preview()
|
||||
app.run(host=os.environ.get("XBCR_HOST", "127.0.0.1"), port=int(os.environ.get("XBCR_PORT", 9989)), debug=False)
|
||||
sys.exit(0)
|
||||
|
||||
# 恢复未过期的计时器
|
||||
restore_active_timers()
|
||||
|
||||
# 启动用户订单检测
|
||||
start_all_order_checkers()
|
||||
|
||||
# 启动数据采集
|
||||
start_snapshot_scheduler()
|
||||
|
||||
# 启动订阅提醒调度(定时查看教学楼附近车辆 → 邮件)
|
||||
from subscribe import start_subscribe_scheduler
|
||||
start_subscribe_scheduler()
|
||||
|
||||
# 启动凭据到期告警调度(1天/1小时/已过期 三级)
|
||||
from alerts import start_alert_scheduler
|
||||
start_alert_scheduler()
|
||||
|
||||
bootstrap()
|
||||
PORT = 98
|
||||
# 只监听本机回环:对外统一走 nginx 的 HTTPS(同机回环转发到本端口)。
|
||||
# 绑定 0.0.0.0 会让明文 HTTP 绕过 nginx 直接暴露,token/凭据可被局域网窃听。
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
"""Vehicle state contract shared by statistics and exports; mirrors BikeData.state."""
|
||||
import math
|
||||
|
||||
|
||||
def battery(value):
|
||||
if value is None or isinstance(value, bool) or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
try:
|
||||
n = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return n if math.isfinite(n) and 0 <= n <= 100 else None
|
||||
|
||||
|
||||
def classify(state, status, electric):
|
||||
try:
|
||||
state, status = int(state), int(status)
|
||||
except (TypeError, ValueError):
|
||||
return "unknown"
|
||||
electric = battery(electric)
|
||||
if state == 1 and status == 1:
|
||||
return "used"
|
||||
if state == 4:
|
||||
return "locked"
|
||||
if state == 2:
|
||||
return "reserved"
|
||||
if state == 10 or (electric is not None and electric < 20):
|
||||
return "low"
|
||||
if state == 1 and status == 0:
|
||||
return "available"
|
||||
return "unknown"
|
||||
@@ -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]
|
||||
|
||||
|
||||
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):
|
||||
|
||||
@@ -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-----
|
||||
@@ -4,12 +4,7 @@
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
import os
|
||||
from runtime_mode import PREVIEW_MODE
|
||||
DB_PATH = Path(os.environ.get("XBNIU_DB_PATH") or (Path(__file__).parent / ("preview.db" if PREVIEW_MODE else "users.db")))
|
||||
if PREVIEW_MODE and DB_PATH.name == "users.db":
|
||||
raise RuntimeError("Preview mode must use a separate database")
|
||||
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
DB_PATH = Path(__file__).parent / "users.db"
|
||||
|
||||
DEFAULT_RENTAL_SETTINGS = {
|
||||
"reminder_enabled": True,
|
||||
@@ -88,6 +83,22 @@ def init_db():
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
|
||||
# 老库的 token_id 列带 DEFAULT '1291378'(建表时留下的),注册时没写这一列的用户
|
||||
# 会被灌成这个假凭据 → 巡检拿它去探测、必被上游 102001 拒绝 →
|
||||
# 全站收到「凭据已过期」误报邮件。这里启动时自动清掉:值等于该默认值且没有
|
||||
# access_token 的,一律视为「未配置凭据」。
|
||||
# 新库/新注册都不会再写入默认值(auth 注册显式传 NULL)。
|
||||
try:
|
||||
cursor.execute("""
|
||||
UPDATE users SET token_id = NULL
|
||||
WHERE token_id = '1291378'
|
||||
AND (access_token IS NULL OR access_token = '')
|
||||
""")
|
||||
if cursor.rowcount:
|
||||
print(f"[迁移] 清理 {cursor.rowcount} 个注册遗留的默认 token_id(1291378)")
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -368,12 +379,6 @@ def init_db():
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
|
||||
for column in ("last_run_at TEXT", "last_run_status TEXT", "last_run_message TEXT"):
|
||||
try:
|
||||
cursor.execute("ALTER TABLE subscribe_rules ADD COLUMN " + column)
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
|
||||
# ===== 凭据告警去重(同一凭据同一级别只发一次) =====
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS credential_alerts (
|
||||
|
||||
+48
-48
@@ -1,48 +1,48 @@
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page()
|
||||
page.goto('http://127.0.0.1:5000/analysis')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug1.png')
|
||||
print("Page loaded, took debug1.png")
|
||||
|
||||
# 点击加载轨迹
|
||||
page.click('button:has-text("加载轨迹")')
|
||||
page.wait_for_timeout(4000)
|
||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug2.png')
|
||||
print("After loading trajectory, took debug2.png")
|
||||
|
||||
# 检查 traj-map 容器内的 DOM 结构
|
||||
html = page.evaluate('''() => {
|
||||
const el = document.getElementById("traj-map");
|
||||
if (!el) return "NOT FOUND";
|
||||
let info = "children: " + el.children.length + "\\n";
|
||||
let canvas = el.querySelectorAll("canvas");
|
||||
let mapdiv = el.querySelectorAll("div");
|
||||
info += "canvas count: " + canvas.length + "\\n";
|
||||
info += "div count: " + mapdiv.length + "\\n";
|
||||
for (let c of canvas) {
|
||||
info += " canvas: " + c.width + "x" + c.height + "\\n";
|
||||
}
|
||||
// 检查 pointer-events
|
||||
let allEls = Array.from(el.querySelectorAll("*"));
|
||||
let blocking = [];
|
||||
for (let e of allEls) {
|
||||
let style = window.getComputedStyle(e);
|
||||
let rect = e.getBoundingClientRect();
|
||||
if (rect.width > 0 && rect.height > 0) {
|
||||
let pe = style.pointerEvents;
|
||||
let vis = style.visibility;
|
||||
let op = style.opacity;
|
||||
let z = style.zIndex;
|
||||
let disp = style.display;
|
||||
blocking.push(e.className + " ptr:" + pe + " vis:" + vis + " z:" + z + " op:" + op + " disp:" + disp);
|
||||
}
|
||||
}
|
||||
return info + "\\nall elements:\\n" + blocking.join("\\n");
|
||||
}''')
|
||||
print(html)
|
||||
|
||||
browser.close()
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page()
|
||||
page.goto('http://127.0.0.1:5000/analysis')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug1.png')
|
||||
print("Page loaded, took debug1.png")
|
||||
|
||||
# 点击加载轨迹
|
||||
page.click('button:has-text("加载轨迹")')
|
||||
page.wait_for_timeout(4000)
|
||||
page.screenshot(path='d:/Downloads/unpack/98/xbniu_map/debug2.png')
|
||||
print("After loading trajectory, took debug2.png")
|
||||
|
||||
# 检查 traj-map 容器内的 DOM 结构
|
||||
html = page.evaluate('''() => {
|
||||
const el = document.getElementById("traj-map");
|
||||
if (!el) return "NOT FOUND";
|
||||
let info = "children: " + el.children.length + "\\n";
|
||||
let canvas = el.querySelectorAll("canvas");
|
||||
let mapdiv = el.querySelectorAll("div");
|
||||
info += "canvas count: " + canvas.length + "\\n";
|
||||
info += "div count: " + mapdiv.length + "\\n";
|
||||
for (let c of canvas) {
|
||||
info += " canvas: " + c.width + "x" + c.height + "\\n";
|
||||
}
|
||||
// 检查 pointer-events
|
||||
let allEls = Array.from(el.querySelectorAll("*"));
|
||||
let blocking = [];
|
||||
for (let e of allEls) {
|
||||
let style = window.getComputedStyle(e);
|
||||
let rect = e.getBoundingClientRect();
|
||||
if (rect.width > 0 && rect.height > 0) {
|
||||
let pe = style.pointerEvents;
|
||||
let vis = style.visibility;
|
||||
let op = style.opacity;
|
||||
let z = style.zIndex;
|
||||
let disp = style.display;
|
||||
blocking.push(e.className + " ptr:" + pe + " vis:" + vis + " z:" + z + " op:" + op + " disp:" + disp);
|
||||
}
|
||||
}
|
||||
return info + "\\nall elements:\\n" + blocking.join("\\n");
|
||||
}''')
|
||||
print(html)
|
||||
|
||||
browser.close()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,172 @@
|
||||
# 百度地图 JS API GL v1.0 —— 本地速查(BMapGL)
|
||||
|
||||
> 原始文档已下载:`docs/baidu-jsapi-webgl-1.0.html`(664 KB,离线可查)
|
||||
> 来源:https://lbsyun.baidu.com/cms/jsapi/reference/jsapi_webgl_1_0.html
|
||||
>
|
||||
> **约定:改地图相关代码前先查这里 / 查本地 HTML,不要再凭记忆猜方法名和参数顺序。**
|
||||
|
||||
---
|
||||
|
||||
## 1. 我们实际在用的类
|
||||
|
||||
| 类 | 用途 | 备注 |
|
||||
|---|---|---|
|
||||
| `BMapGL.Map` | 地图实例 | 必须先 `centerAndZoom()` 初始化,否则任何操作无效 |
|
||||
| `BMapGL.Point` | 经纬度点 | **BD09**(百度坐标) |
|
||||
| `BMapGL.Marker` | 标记 | 有 `setRotation()`,可做导航箭头 |
|
||||
| `BMapGL.Icon` | 图标 | `Icon(url, Size, {anchor})` |
|
||||
| `BMapGL.Polyline` | 折线 | 路线、边界 |
|
||||
| `BMapGL.Polygon` | 多边形 | 停车区、骑行边界 |
|
||||
| `BMapGL.ViewAnimation` | 视角动画 | **官方唯一文档化的"旋转/倾斜"入口** |
|
||||
| `BMapGL.ScaleControl` | 比例尺 | |
|
||||
| `BMapGL.Geolocation` | 百度自带定位 | 我们没用,用的是 `navigator.geolocation` |
|
||||
|
||||
---
|
||||
|
||||
## 2. 踩过的坑(按踩的顺序,全部实测)
|
||||
|
||||
### 坑 1:`setHeading()` / `getHeading()` 是**没文档**的私有方法
|
||||
|
||||
在官方文档里 `heading` 只出现在 `ViewAnimationKeyFrames`,`setHeading` 这个词**完全没有**。
|
||||
它们是实例上的隐藏方法(`typeof map.setHeading === 'function'` 为真),能用但不保证稳定。
|
||||
|
||||
**文档化的旋转方式**:
|
||||
|
||||
```js
|
||||
// 关键帧里 heading = 地图旋转角度(度)
|
||||
const anim = new BMapGL.ViewAnimation(
|
||||
[{ heading: 0, percentage: 0 }, { heading: 90, percentage: 1 }],
|
||||
{ duration: 300 }
|
||||
);
|
||||
map.startViewAnimation(anim);
|
||||
// 中止:map.cancelViewAnimation(anim)
|
||||
```
|
||||
|
||||
### 坑 2:`setCenter()` 会把刚设的 heading 抹成 0
|
||||
|
||||
实测(headless + 真机同样的行为):
|
||||
|
||||
| 顺序 | `getHeading()` |
|
||||
|---|---|
|
||||
| `setHeading(90)` → `setCenter(p)` | **0**(被抹掉) |
|
||||
| `setCenter(p)` → `setHeading(90)` | 90 ✅ |
|
||||
| `setCenter(p, {callback})` 里 `setHeading(90)` | 90 ✅ |
|
||||
| `setHeading(45)` → `panBy(0,120)` | 45(平移不抹) |
|
||||
|
||||
所以正确写法是**在 setCenter 的回调里**设 heading:
|
||||
|
||||
```js
|
||||
map.setCenter(point, {
|
||||
noAnimation: true,
|
||||
callback: function () {
|
||||
map.setHeading(deg); // 或 startViewAnimation
|
||||
map.panBy(0, offsetY); // 再把我压到屏幕下方
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 坑 2.5:heading 是**逆时针**角度,方位角朝上要取反
|
||||
|
||||
实测(同一段路,路线方位角 145°,用 `map.pointToPixel()` 量目标点在屏幕的位置):
|
||||
|
||||
| 设置 | 目标点相对我的像素偏移 | 结论 |
|
||||
|---|---|---|
|
||||
| `setHeading(145)` | dx=-37, dy=-13(在左上方) | ❌ 不是正上 |
|
||||
| `setHeading(-145)` | dx=**0**, dy=-39(正上方) | ✅ 行进方向朝上 |
|
||||
|
||||
所以 **`map.setHeading(-方位角)`**。方位角是地理学的顺时针(0=北、90=东),
|
||||
BMapGL 的 heading 是逆时针,两者符号相反。
|
||||
|
||||
箭头(`Marker.setRotation`)仍按**顺时针**理解,所以箭头角度 = `罗盘角 - 方位角`。
|
||||
|
||||
### 坑 3:不支持的 WebGL 环境下 `setHeading` 会留下坏相机 → **整张底图变黑**
|
||||
|
||||
表现:调完 `getHeading()` 仍返回 0,但地图黑屏。
|
||||
处理:探测到不支持时立刻 `map.resetHeading()`,再 `map.setCenter(map.getCenter())` 重铺一次。
|
||||
所以我们的代码里 `_headingSupported` 是个三态(null/true/false),只探测一次。
|
||||
|
||||
### 坑 4:`Marker.setRotation(deg)` 才能让箭头转
|
||||
|
||||
`BMapGL.Marker` 文档里就写了 `setRotation(rotation: Number)` / `getRotation()`。
|
||||
配合 `deviceorientation` 的罗盘角度做"箭头指向手机朝向":
|
||||
|
||||
```js
|
||||
// iOS:webkitCompassHeading 已是相对正北的顺时针角度
|
||||
// 安卓:alpha 是逆时针,需要 360 - alpha
|
||||
const h = e.webkitCompassHeading ?? (360 - e.alpha) % 360;
|
||||
marker.setRotation(h);
|
||||
```
|
||||
|
||||
iOS 13+ 要权限,必须在**用户手势**里申请:
|
||||
`DeviceOrientationEvent.requestPermission()`
|
||||
|
||||
### 坑 5:`panBy(x, y)` 的正负
|
||||
|
||||
`panBy(0, +y)` 把地图整体**上移**(视觉上内容往上走)—— 用来把当前位置压到屏幕下方。
|
||||
像素大于可视区时百度会忽略这次调用。
|
||||
|
||||
### 坑 6:`setViewport(points, {margins})`
|
||||
|
||||
`margins: [上, 右, 下, 左]`,做"路线全部可见"时用来避开顶部/底部面板。
|
||||
|
||||
### 坑 7:`getMapScreenshot()` 需要初始化时开 `preserveDrawingBuffer: true`
|
||||
|
||||
否则截出来是黑屏(我们没用它)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 与本项目坐标相关(**不是 JS API,属于 Web 服务 API**)
|
||||
|
||||
`directionlite/v1/walking`:
|
||||
|
||||
| 参数 | 作用 | 坑 |
|
||||
|---|---|---|
|
||||
| `coord_type` | **输入**坐标系 | 只影响入参 |
|
||||
| `ret_coordtype` | **返回**折线坐标系 | **默认 `bd09ll`**!不传就拿到 BD09,前端再按 GCJ02 转会偏 500~900 米 |
|
||||
| `timestamp` + `sn` | 开了 SN 校验必带 | 缺 timestamp → `status=2` |
|
||||
| `steps_info` | 0/1 是否返回分段 | 只要距离时间时传 0,响应更小 |
|
||||
|
||||
我们的坐标约定:**浏览器 `navigator.geolocation` = WGS84 → 统一转 GCJ02 → 再转 BD09 给地图绘制**。
|
||||
|
||||
---
|
||||
|
||||
## 4. 本项目导航实现用到的 Map 能力清单
|
||||
|
||||
```js
|
||||
map.setCenter(point, {noAnimation, callback}) // 居中 + 回调里设 heading/panBy
|
||||
map.panBy(0, offsetY) // 把"我"压到屏幕下方
|
||||
map.setHeading(deg) / map.getHeading() // 私有,探测后使用
|
||||
map.resetHeading() // 私有,复位
|
||||
map.startViewAnimation(anim) // 文档化的旋转方案
|
||||
map.setViewport(points, {margins}) // 路线全览
|
||||
map.addEventListener('dragstart' | 'dragend' | 'moving', fn) // 拖动进入自由查看
|
||||
map.pointToPixel(point) / map.pixelToPoint(px) // 像素/经纬度互转
|
||||
new BMapGL.ViewAnimation(keyFrames, {duration, delay, iteration})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 导航的朝向策略(本项目已定稿)
|
||||
|
||||
| 东西 | 跟谁 | 实现 |
|
||||
|---|---|---|
|
||||
| **地图朝向** | **行进方向**(course-up),不跟手机 | `setHeading(行进方位角)`,在 `setCenter` 的 callback 里设 |
|
||||
| **箭头朝向** | 手机朝向(罗盘) | `Marker.setRotation(罗盘角 - 地图朝向)`;没罗盘就 0(=朝行进方向) |
|
||||
| 我在地图上的位置 | 屏幕下方约 80% | `setCenter` 后 `panBy(0, 屏高×0.20)` |
|
||||
|
||||
方位角公式(0=正北,90=正东):
|
||||
|
||||
```js
|
||||
const y = Math.sin(dLng) * Math.cos(lat2);
|
||||
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLng);
|
||||
const bearing = (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
|
||||
```
|
||||
|
||||
罗盘角度:
|
||||
- iOS `e.webkitCompassHeading` —— 已经是"相对正北的顺时针角度",**直接用**
|
||||
- 安卓 `e.alpha` —— 逆时针,**要 `(360 - alpha) % 360`**
|
||||
- iOS 13+ 必须在用户手势里 `DeviceOrientationEvent.requestPermission()`
|
||||
|
||||
**踩过的坑**:箭头别用绝对罗盘角。地图已经按行进方向转过一次了,
|
||||
再按绝对角转箭头 = 转两次,方向是反的。要减掉地图朝向。
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
# 前端重构方案(从单文件走向模块化)
|
||||
|
||||
> 现状数据(2026-11):`static/js/map.js` **213 KB / 4776 行**,模板 `map.html` 里 **136 处内联
|
||||
> `onclick/oninput/onchange`**,全部脚本是 classic script + 全局变量,无构建、无类型、无单测(只有 4 个 node 契约测试)。
|
||||
|
||||
## 1. 为什么现在必须动
|
||||
|
||||
| 现象 | 代价 |
|
||||
|---|---|
|
||||
| 一个文件里塞了地图、标记、卡片、订单、导航、登录、共享、订阅、设置 | 改一处要读 4000 行上下文;合并冲突几乎必冲突 |
|
||||
| 全是全局变量(`map` / `selectedBike` / `_nav` / `authToken`…) | 任何模块都能改任何状态,出现「关掉卡片导航还在跑」这类竞态 |
|
||||
| 内联 `onclick="fn()"` 136 处 | 函数名是隐式 ABI,重命名即线上崩,且 IDE 无法跳转/查引用 |
|
||||
| 无类型、无 lint | `st.electric` vs `st.electric_quantity` 这种字段名错误只能靠人眼(本期已踩过一次) |
|
||||
| 无组件化 | 弹窗/卡片/设置页都是字符串拼接 HTML,XSS 与转义靠自觉 |
|
||||
|
||||
## 2. 约束(决定方案选型)
|
||||
|
||||
1. **部署是 Flask + 静态文件**,没有 Node 运行时;构建产物必须能直接放进 `static/`。
|
||||
2. **136 处内联事件**:短期内不能全部改成 `addEventListener`,否则一次性改动面太大。
|
||||
3. 有 4 个 node 契约测试(`tests/*.cjs`)直接从 `static/js/*.js` 读源码 + `vm` 执行,重构要保证它们仍能跑。
|
||||
4. 地图是 **BMapGL 全局 SDK**(`window.BMapGL`),且用 `callback=onBaiduMapReady` 异步就绪,不能被 tree-shaking / 严格模块作用域搞坏。
|
||||
5. 生产只有单页 + admin 两页,不需要 SSR。
|
||||
|
||||
## 3. 三个候选方案
|
||||
|
||||
### 方案 A:无构建 ES Modules(**第一步就做**)
|
||||
|
||||
```html
|
||||
<script type="module" src="/static/js/main.js?v=..."></script>
|
||||
```
|
||||
|
||||
```js
|
||||
// main.js
|
||||
import { initMap } from "./map/core.js";
|
||||
import { installGlobals } from "./compat/globals.js"; // 兼容 136 处内联事件
|
||||
installGlobals(); // 把 window.openShareModal = ... 挂回去(一次性、集中)
|
||||
initMap();
|
||||
```
|
||||
|
||||
- 优点:零依赖、零构建、部署方式不变、可以**逐文件替换**,随时能停。
|
||||
- 缺点:没有类型检查、没有打包(模块多会有几十个请求,但都是 `defer` 缓存命中,实际影响小)。
|
||||
- 内联事件兼容:集中一个 `compat/globals.js` 显式导出需要的函数。
|
||||
**实测 `map.html` 里内联事件引用了 95 个标识符**,去掉 `document/event/if/return/this`
|
||||
这类误匹配、以及 `SettingsPages`/`uiNavigate`(本来就在 `window` 上)之后,
|
||||
**真正要挂的约 88 个函数**——分布:`map.js` 约 70、`share.js` 9、`navigation.js` 4、
|
||||
`subscribe.js` 3。这个清单是 Phase 0 的验收依据(`grep` 对照,缺一个线上就有一处按钮失灵)。
|
||||
|
||||
### 方案 B:Vite + TypeScript(**第二步**)
|
||||
|
||||
- Vite build 产出 `static/dist/`,Flask 模板只引 `dist/main.[hash].js`。
|
||||
- 好处:类型(`Bike`/`Order`/`Rental` 接口能直接照 `routes/*.py` 的 JSON 写)、按需打包、真 HMR。
|
||||
- 迁移成本:需要引入 Node(本机/CI 构建),部署多一步 `pnpm build`。
|
||||
|
||||
### 方案 C:Vite + Vue 3(**只在 UI 继续膨胀时才做**)
|
||||
|
||||
- 卡片、订单面板、设置页、订阅弹窗可以做成组件,状态用 `ref/reactive`。
|
||||
- 代价最大:地图容器与 BMapGL 命令式 API 结合需要封装层,团队要熟悉 Vue。
|
||||
- 不建议现在直接跳,除非前端交互还要翻倍。
|
||||
|
||||
## 4. 推荐路径
|
||||
|
||||
```
|
||||
Phase 0(1-2 天,无风险) 方案 A:拆文件 + ESM,收敛全局
|
||||
Phase 1(2-3 天) 方案 B:引入 Vite + TS,只对「数据层 + 新模块」上类型
|
||||
Phase 2(按需) 方案 C:把 3 个最复杂的面板改成 Vue 组件
|
||||
```
|
||||
|
||||
**原则:每一阶段结束都能上线,都不改后端接口。**
|
||||
|
||||
## 5. Phase 0 模块边界(把 4776 行拆成这些)
|
||||
|
||||
| 模块 | 职责 | 现来源 |
|
||||
|---|---|---|
|
||||
| `src/core/http.js` | 统一 `fetch` + `Authorization` + 错误归一 | map.js 里散落的 fetch |
|
||||
| `src/core/state.js` | 只读导出 + setter(`getActiveRental()` 等),替代裸全局 | 全局变量区 |
|
||||
| `src/core/geo.js` | WGS84/GCJ02/BD09 转换、`calcDistance`、`offsetCoord` | map.js 顶部 + coordtransform |
|
||||
| `src/map/map-core.js` | 地图初始化、缩放、视图、地图上的公共图层 | `initMap` 段 |
|
||||
| `src/map/markers.js` | 车辆图标、增量渲染、气泡聚合、高亮 | 图标缓存 + `renderMap` |
|
||||
| `src/card/bike-card.js` | 车辆卡片渲染、距离/电量/状态、按钮可用性 | `showBikeDetail` |
|
||||
| `src/order/order-status.js` | 订单横幅、倒计时、`/api/order/status` 轮询、到期震动 | 订单状态段 |
|
||||
| `src/order/order-actions.js` | 开锁/还车/加轮/月卡/寻车 | 订单动作段 |
|
||||
| `src/nav/navigation.js` | 跟随式导航(已是独立文件,改成 ESM 即可) | navigation.js |
|
||||
| `src/nav/walk-route.js` | 步行/骑行路线请求与缓存 | `refineWalkRoute` |
|
||||
| `src/share/share.js` | 共享关系 | share.js |
|
||||
| `src/subscribe/subscribe.js` | 订阅规则 | subscribe.js |
|
||||
| `src/ui/modals.js` | 通用弹窗、确认框、Toast | `appConfirm` 等 |
|
||||
| `src/ui/settings.js` | 我的/设置页 | settings-pages.js + 相关段 |
|
||||
| `src/compat/globals.js` | **唯一**把函数挂 `window` 的地方(服务内联事件) | 新增 |
|
||||
|
||||
拆完 `map.js` 应降到 **< 300 行**(只剩编排:初始化顺序、事件绑定、模块装配)。
|
||||
|
||||
## 6. 迁移步骤(每步可单独提交、可回滚)
|
||||
|
||||
1. **建 `src/` 骨架 + `main.js`**:先只搬 `geo.js`、`http.js`(纯函数,零依赖),`map.js` 里改成 `import`。
|
||||
2. **搬 `navigation.js`**:它是最近写的、自包含,改 ESM 最安全;用 headless 回归「导航/偏航重算/拖动回正」。
|
||||
3. **搬 markers / card**:这两块与地图耦合最紧,先搬渲染函数,状态仍留在 `state.js`。
|
||||
4. **搬 order / share / subscribe**:这三块有 node 契约测试,改完先跑 `node tests/*.cjs`。
|
||||
5. **收口全局**:`grep -o 'on[a-z]*="[^"]*"' templates/map.html` 逐个对照 `globals.js`,确保 136 处全覆盖。
|
||||
6. **删除旧文件**,`map.html` 只留一个 `<script type="module">`。
|
||||
|
||||
## 7. 风险与对策
|
||||
|
||||
| 风险 | 对策 |
|
||||
|---|---|
|
||||
| ESM 是严格作用域,内联事件全崩 | `globals.js` 集中挂载;上线前用 headless 点一遍 136 个入口里的高频项 |
|
||||
| 模块图循环依赖(map ↔ card ↔ order) | 依赖方向单向:`core → map → card → order`;跨层用事件(`document.dispatchEvent`)而不是互调 |
|
||||
| BMapGL 的 `callback=onBaiduMapReady` 与模块加载顺序冲突 | `map-core.js` 导出 `whenMapReady(): Promise`,其它模块 await 它,去掉隐式顺序依赖 |
|
||||
| 静态资源哈希(`map_asset_version`) | 继续用 `routes/map_api.py` 的 MAP_ASSETS 列表,新增文件加进去即可 |
|
||||
| node 契约测试读源码字符串 | Phase 0 期间保持函数名单不变;测试改为 `import` 后仍能断言 |
|
||||
| 一次搬太多 | 每步一提交,`pytest + node + headless 冒烟` 全绿才继续 |
|
||||
|
||||
## 8. 验收标准
|
||||
|
||||
- `static/js/map.js` < 300 行;单文件最大 < 600 行。
|
||||
- `window.` 上的符号只出现在 `globals.js`(`grep -c "window\." static/js/src | sort`)。
|
||||
- 4 个 node 契约测试 + 161 个 pytest 全绿。
|
||||
- headless 冒烟脚本覆盖:打开卡片 → 导航 → 拖动回正 → 结束导航 → 还车 → 订阅弹窗 → 共享弹窗。
|
||||
- 首屏脚本请求数 ≤ 15,总体积不高于现在(213 KB + 76 KB)。
|
||||
@@ -106,17 +106,10 @@ def _load_smtp_config() -> dict:
|
||||
cfg[k] = v.strip()
|
||||
except Exception as e:
|
||||
print(f"[SMTP配置] 读取失败: {e}")
|
||||
import os
|
||||
for key in cfg:
|
||||
if os.environ.get(key.upper()) is not None:
|
||||
cfg[key] = os.environ[key.upper()]
|
||||
return cfg
|
||||
|
||||
|
||||
def send_email(to_email: str, subject: str, body: str, html_body: str = None) -> bool:
|
||||
from runtime_mode import PREVIEW_MODE
|
||||
if PREVIEW_MODE and str(to_email).lower() in ("demo@preview.local", "friend@preview.local"):
|
||||
return True # Demonstration recipients are synthetic; real alert emails use SMTP.
|
||||
"""发送邮件,可同时提供纯文本和 HTML 版本,返回是否成功。"""
|
||||
cfg = _load_smtp_config()
|
||||
if not cfg["smtp_user"] or not cfg["smtp_pass"]:
|
||||
|
||||
+134
-134
@@ -1,134 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""注册/重置密码邮箱验证码:服务端 60 秒冷却、10 分钟有效期、5 次错误作废。
|
||||
内存存储(单进程部署足够);重启后验证码失效,用户重新发送即可。
|
||||
purpose 区分用途(register / reset),不同用途互不通用。"""
|
||||
import hashlib
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
import rate_limit
|
||||
from email_utils import render_email_safe, send_email
|
||||
|
||||
CODE_TTL_SECONDS = 10 * 60
|
||||
CODE_SEND_COOLDOWN = 60 # 同一邮箱两次发送的最小间隔(服务端强制)
|
||||
CODE_MAX_ATTEMPTS = 5
|
||||
SEND_IP_MAX_PER_HOUR = 10 # 同一 IP 每小时最多请求验证码次数
|
||||
|
||||
PURPOSES = ("register", "reset")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_codes: dict = {} # email -> {"hash": sha256hex, "expires": ts, "attempts": n, "sent_at": ts, "purpose": str}
|
||||
|
||||
# purpose -> (邮件主题, 页面标题, 首段说明, 顶部 kicker, 主题色)
|
||||
_PURPOSE_TITLES = {
|
||||
"register": (
|
||||
"【小白超人】注册验证码",
|
||||
"注册验证码",
|
||||
"你正在注册小白超人电动车地图账号,请在页面中输入下面的验证码完成注册。",
|
||||
"小白超人 · 账号注册",
|
||||
"#2563eb",
|
||||
),
|
||||
"reset": (
|
||||
"【小白超人】重置密码验证码",
|
||||
"重置密码验证码",
|
||||
"你正在重置小白超人电动车地图的登录密码,请在页面中输入下面的验证码。",
|
||||
"小白超人 · 重置密码",
|
||||
"#dc2626",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _now() -> float:
|
||||
return time.time()
|
||||
|
||||
|
||||
def _code_hash(code: str, email: str) -> str:
|
||||
return hashlib.sha256(f"{email.lower()}:{code}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _cleanup_locked(now: float):
|
||||
for email in [e for e, v in _codes.items() if v["expires"] <= now]:
|
||||
_codes.pop(email, None)
|
||||
|
||||
|
||||
def send_code(email: str, purpose: str = "register") -> tuple:
|
||||
"""发送验证码到邮箱。返回 (ok, message)。受 60s 邮箱冷却与每小时 IP 上限约束。"""
|
||||
email = (email or "").strip().lower()
|
||||
if purpose not in PURPOSES:
|
||||
purpose = "register"
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||
wait = int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||
return False, f"发送过于频繁,请 {wait} 秒后再试"
|
||||
code = f"{secrets.randbelow(1000000):06d}"
|
||||
subject, title, lead, kicker, accent = _PURPOSE_TITLES.get(
|
||||
purpose, _PURPOSE_TITLES["register"])
|
||||
ttl_minutes = CODE_TTL_SECONDS // 60
|
||||
# 纯文本版本保留(无 HTML 能力的客户端);HTML 版本走统一模板。
|
||||
plain = (f"{title}\n\n{lead}\n\n验证码:{code}\n\n"
|
||||
f"{ttl_minutes} 分钟内有效。若不是你本人操作,请忽略本邮件。")
|
||||
html_body = render_email_safe(
|
||||
kicker=kicker, title=title,
|
||||
lead=f"请在页面中输入下面的验证码,{ttl_minutes} 分钟内有效。",
|
||||
code=code, accent=accent,
|
||||
details=[("有效期", f"{ttl_minutes} 分钟"),
|
||||
("用途", "账号注册" if purpose == "register" else "重置登录密码")],
|
||||
footnote="若不是你本人操作,请忽略本邮件,你的账号不会受到任何影响。",
|
||||
)
|
||||
ok = send_email(email, subject, plain, html_body)
|
||||
if not ok:
|
||||
return False, "验证码邮件发送失败,请稍后重试"
|
||||
with _lock:
|
||||
_codes[email] = {
|
||||
"hash": _code_hash(code, email),
|
||||
"expires": now + CODE_TTL_SECONDS,
|
||||
"attempts": 0,
|
||||
"sent_at": now,
|
||||
"purpose": purpose,
|
||||
}
|
||||
return True, "验证码已发送"
|
||||
|
||||
|
||||
def check_send_cooldown(email: str) -> int:
|
||||
"""返回还需等待的秒数(0 = 可发送)。供接口在未真正发送前返回通用响应。"""
|
||||
email = (email or "").strip().lower()
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||
return int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||
return 0
|
||||
|
||||
|
||||
def verify_code(email: str, code: str, purpose: str = "register") -> bool:
|
||||
"""校验验证码;成功即作废,连续错误 5 次作废。purpose 必须与发送时一致。"""
|
||||
email = (email or "").strip().lower()
|
||||
code = (code or "").strip()
|
||||
if purpose not in PURPOSES:
|
||||
purpose = "register"
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if not entry or entry["expires"] <= now or entry["attempts"] >= CODE_MAX_ATTEMPTS:
|
||||
return False
|
||||
if entry.get("purpose", "register") != purpose:
|
||||
# 用途不匹配(例如拿注册验证码去重置密码):按错误处理并计数
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
if not (len(code) == 6 and code.isdigit()):
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
if secrets.compare_digest(entry["hash"], _code_hash(code, email)):
|
||||
_codes.pop(email, None)
|
||||
return True
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
|
||||
|
||||
def ip_send_allowed(ip: str) -> bool:
|
||||
"""同一 IP 每小时验证码发送次数上限。"""
|
||||
return rate_limit.hit(("send_code", ip), SEND_IP_MAX_PER_HOUR, 3600)
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""注册/重置密码邮箱验证码:服务端 60 秒冷却、10 分钟有效期、5 次错误作废。
|
||||
内存存储(单进程部署足够);重启后验证码失效,用户重新发送即可。
|
||||
purpose 区分用途(register / reset),不同用途互不通用。"""
|
||||
import hashlib
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
import rate_limit
|
||||
from email_utils import render_email_safe, send_email
|
||||
|
||||
CODE_TTL_SECONDS = 10 * 60
|
||||
CODE_SEND_COOLDOWN = 60 # 同一邮箱两次发送的最小间隔(服务端强制)
|
||||
CODE_MAX_ATTEMPTS = 5
|
||||
SEND_IP_MAX_PER_HOUR = 10 # 同一 IP 每小时最多请求验证码次数
|
||||
|
||||
PURPOSES = ("register", "reset")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_codes: dict = {} # email -> {"hash": sha256hex, "expires": ts, "attempts": n, "sent_at": ts, "purpose": str}
|
||||
|
||||
# purpose -> (邮件主题, 页面标题, 首段说明, 顶部 kicker, 主题色)
|
||||
_PURPOSE_TITLES = {
|
||||
"register": (
|
||||
"【小白超人】注册验证码",
|
||||
"注册验证码",
|
||||
"你正在注册小白超人电动车地图账号,请在页面中输入下面的验证码完成注册。",
|
||||
"小白超人 · 账号注册",
|
||||
"#2563eb",
|
||||
),
|
||||
"reset": (
|
||||
"【小白超人】重置密码验证码",
|
||||
"重置密码验证码",
|
||||
"你正在重置小白超人电动车地图的登录密码,请在页面中输入下面的验证码。",
|
||||
"小白超人 · 重置密码",
|
||||
"#dc2626",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _now() -> float:
|
||||
return time.time()
|
||||
|
||||
|
||||
def _code_hash(code: str, email: str) -> str:
|
||||
return hashlib.sha256(f"{email.lower()}:{code}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _cleanup_locked(now: float):
|
||||
for email in [e for e, v in _codes.items() if v["expires"] <= now]:
|
||||
_codes.pop(email, None)
|
||||
|
||||
|
||||
def send_code(email: str, purpose: str = "register") -> tuple:
|
||||
"""发送验证码到邮箱。返回 (ok, message)。受 60s 邮箱冷却与每小时 IP 上限约束。"""
|
||||
email = (email or "").strip().lower()
|
||||
if purpose not in PURPOSES:
|
||||
purpose = "register"
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||
wait = int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||
return False, f"发送过于频繁,请 {wait} 秒后再试"
|
||||
code = f"{secrets.randbelow(1000000):06d}"
|
||||
subject, title, lead, kicker, accent = _PURPOSE_TITLES.get(
|
||||
purpose, _PURPOSE_TITLES["register"])
|
||||
ttl_minutes = CODE_TTL_SECONDS // 60
|
||||
# 纯文本版本保留(无 HTML 能力的客户端);HTML 版本走统一模板。
|
||||
plain = (f"{title}\n\n{lead}\n\n验证码:{code}\n\n"
|
||||
f"{ttl_minutes} 分钟内有效。若不是你本人操作,请忽略本邮件。")
|
||||
html_body = render_email_safe(
|
||||
kicker=kicker, title=title,
|
||||
lead=f"请在页面中输入下面的验证码,{ttl_minutes} 分钟内有效。",
|
||||
code=code, accent=accent,
|
||||
details=[("有效期", f"{ttl_minutes} 分钟"),
|
||||
("用途", "账号注册" if purpose == "register" else "重置登录密码")],
|
||||
footnote="若不是你本人操作,请忽略本邮件,你的账号不会受到任何影响。",
|
||||
)
|
||||
ok = send_email(email, subject, plain, html_body)
|
||||
if not ok:
|
||||
return False, "验证码邮件发送失败,请稍后重试"
|
||||
with _lock:
|
||||
_codes[email] = {
|
||||
"hash": _code_hash(code, email),
|
||||
"expires": now + CODE_TTL_SECONDS,
|
||||
"attempts": 0,
|
||||
"sent_at": now,
|
||||
"purpose": purpose,
|
||||
}
|
||||
return True, "验证码已发送"
|
||||
|
||||
|
||||
def check_send_cooldown(email: str) -> int:
|
||||
"""返回还需等待的秒数(0 = 可发送)。供接口在未真正发送前返回通用响应。"""
|
||||
email = (email or "").strip().lower()
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if entry and now - entry["sent_at"] < CODE_SEND_COOLDOWN:
|
||||
return int(CODE_SEND_COOLDOWN - (now - entry["sent_at"])) + 1
|
||||
return 0
|
||||
|
||||
|
||||
def verify_code(email: str, code: str, purpose: str = "register") -> bool:
|
||||
"""校验验证码;成功即作废,连续错误 5 次作废。purpose 必须与发送时一致。"""
|
||||
email = (email or "").strip().lower()
|
||||
code = (code or "").strip()
|
||||
if purpose not in PURPOSES:
|
||||
purpose = "register"
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email)
|
||||
if not entry or entry["expires"] <= now or entry["attempts"] >= CODE_MAX_ATTEMPTS:
|
||||
return False
|
||||
if entry.get("purpose", "register") != purpose:
|
||||
# 用途不匹配(例如拿注册验证码去重置密码):按错误处理并计数
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
if not (len(code) == 6 and code.isdigit()):
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
if secrets.compare_digest(entry["hash"], _code_hash(code, email)):
|
||||
_codes.pop(email, None)
|
||||
return True
|
||||
entry["attempts"] += 1
|
||||
return False
|
||||
|
||||
|
||||
def ip_send_allowed(ip: str) -> bool:
|
||||
"""同一 IP 每小时验证码发送次数上限。"""
|
||||
return rate_limit.hit(("send_code", ip), SEND_IP_MAX_PER_HOUR, 3600)
|
||||
|
||||
+55
-55
@@ -1,55 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
"""生成车辆标记图标"""
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import os
|
||||
|
||||
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
||||
os.makedirs(STATIC_DIR, exist_ok=True)
|
||||
|
||||
# 状态颜色 (R, G, B)
|
||||
COLORS = {
|
||||
"green": "#4CAF50",
|
||||
"pink": "#E91E8C",
|
||||
"orange": "#FF9800",
|
||||
"gray": "#9E9E9E",
|
||||
"red": "#F44336",
|
||||
}
|
||||
|
||||
def make_icon(color_hex, label="", size=36):
|
||||
"""生成圆形标记图标,label=文字(如百分比或状态符)"""
|
||||
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
r = size // 2
|
||||
cx, cy = r, r
|
||||
# 填充圆
|
||||
draw.ellipse([2, 2, size-3, size-3], fill=color_hex + "E0") # 带透明度
|
||||
# 边框
|
||||
draw.ellipse([2, 2, size-3, size-3], outline=color_hex, width=2)
|
||||
|
||||
if label:
|
||||
# 文字居中
|
||||
try:
|
||||
font_size = 11 if len(label) <= 2 else 9
|
||||
font = ImageFont.truetype("arial.ttf", font_size)
|
||||
except Exception:
|
||||
font = ImageFont.load_default()
|
||||
bbox = draw.textbbox((0, 0), label, font=font)
|
||||
tw = bbox[2] - bbox[0]
|
||||
th = bbox[3] - bbox[1]
|
||||
tx = cx - tw // 2 - bbox[0]
|
||||
ty = cy - th // 2 - bbox[1]
|
||||
# 白色文字
|
||||
draw.text((tx, ty), label, fill="#FFFFFF", font=font)
|
||||
|
||||
path = os.path.join(STATIC_DIR, f"marker_{color_hex[1:]}.png")
|
||||
img.save(path, "PNG")
|
||||
print(f" {path}")
|
||||
return path
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("生成标记图标...")
|
||||
for name, color in COLORS.items():
|
||||
make_icon(color)
|
||||
print("完成!")
|
||||
#!/usr/bin/env python3
|
||||
"""生成车辆标记图标"""
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import os
|
||||
|
||||
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
||||
os.makedirs(STATIC_DIR, exist_ok=True)
|
||||
|
||||
# 状态颜色 (R, G, B)
|
||||
COLORS = {
|
||||
"green": "#4CAF50",
|
||||
"pink": "#E91E8C",
|
||||
"orange": "#FF9800",
|
||||
"gray": "#9E9E9E",
|
||||
"red": "#F44336",
|
||||
}
|
||||
|
||||
def make_icon(color_hex, label="", size=36):
|
||||
"""生成圆形标记图标,label=文字(如百分比或状态符)"""
|
||||
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
r = size // 2
|
||||
cx, cy = r, r
|
||||
# 填充圆
|
||||
draw.ellipse([2, 2, size-3, size-3], fill=color_hex + "E0") # 带透明度
|
||||
# 边框
|
||||
draw.ellipse([2, 2, size-3, size-3], outline=color_hex, width=2)
|
||||
|
||||
if label:
|
||||
# 文字居中
|
||||
try:
|
||||
font_size = 11 if len(label) <= 2 else 9
|
||||
font = ImageFont.truetype("arial.ttf", font_size)
|
||||
except Exception:
|
||||
font = ImageFont.load_default()
|
||||
bbox = draw.textbbox((0, 0), label, font=font)
|
||||
tw = bbox[2] - bbox[0]
|
||||
th = bbox[3] - bbox[1]
|
||||
tx = cx - tw // 2 - bbox[0]
|
||||
ty = cy - th // 2 - bbox[1]
|
||||
# 白色文字
|
||||
draw.text((tx, ty), label, fill="#FFFFFF", font=font)
|
||||
|
||||
path = os.path.join(STATIC_DIR, f"marker_{color_hex[1:]}.png")
|
||||
img.save(path, "PNG")
|
||||
print(f" {path}")
|
||||
return path
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("生成标记图标...")
|
||||
for name, color in COLORS.items():
|
||||
make_icon(color)
|
||||
print("完成!")
|
||||
|
||||
@@ -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"]}
|
||||
-223
@@ -1,223 +0,0 @@
|
||||
"""Preview fixtures for the demo account; independent test accounts use real APIs."""
|
||||
import copy
|
||||
import datetime as dt
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from flask import jsonify, request
|
||||
|
||||
DEMO_EMAIL = "demo@preview.local"
|
||||
DEMO_PASSWORD = "preview123"
|
||||
_lock = threading.RLock()
|
||||
_rides = {}
|
||||
_live_maps = {}
|
||||
|
||||
|
||||
def sample_bikes():
|
||||
bikes = []
|
||||
for n in range(28):
|
||||
code = str(30000193 + n) if n % 5 == 0 else str((50300 if n % 3 == 0 else 51200) + n)
|
||||
state, status = ((4, 0) if n % 11 == 0 else (2, 0) if n % 13 == 0 else (1, 1) if n % 7 == 0 else (1, 0))
|
||||
bikes.append({"code": code, "id": code, "state": state, "status": status,
|
||||
"latitude": 36.53182 + (n // 7 - 1) * .00105,
|
||||
"longitude": 116.7817 + (n % 7 - 3) * .0008,
|
||||
"electric_quantity": None if n == 3 else 10 if n == 4 else 25 + (n * 13) % 75})
|
||||
return bikes
|
||||
|
||||
|
||||
def seed_preview():
|
||||
from db import get_db
|
||||
from routes.auth import hash_password
|
||||
conn = get_db()
|
||||
if conn.execute("SELECT id FROM users WHERE email=?", (DEMO_EMAIL,)).fetchone():
|
||||
conn.close()
|
||||
return
|
||||
user_id = conn.execute("INSERT INTO users (email, password_hash) VALUES (?, ?)",
|
||||
(DEMO_EMAIL, hash_password(DEMO_PASSWORD))).lastrowid
|
||||
peer_id = conn.execute("INSERT INTO users (email, password_hash) VALUES (?, ?)",
|
||||
("friend@preview.local", hash_password(secrets.token_urlsafe(24)))).lastrowid
|
||||
places = [("图书馆", "poi", 36.5325, 116.7812), ("第一教学楼", "poi", 36.5319, 116.7824),
|
||||
("学生食堂", "poi", 36.5308, 116.7801), ("宿舍区停车点", "parking", 36.5330, 116.7820),
|
||||
("图书馆停车点", "parking", 36.5321, 116.7808)]
|
||||
for name, kind, lat, lng in places:
|
||||
conn.execute("INSERT INTO campus_locations (name,kind,latitude,longitude,radius) VALUES (?,?,?,?,150)",
|
||||
(name, kind, lat, lng))
|
||||
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).replace(tzinfo=None)
|
||||
for n in range(68):
|
||||
start = now - dt.timedelta(hours=n * 3 + 1)
|
||||
end = start + dt.timedelta(minutes=12 + n % 6)
|
||||
conn.execute("""INSERT INTO rentals (order_id,bike_code,email,user_id,rider_user_id,start_time,
|
||||
end_time,returned_at,expired,source,start_label,end_label)
|
||||
VALUES (?,?,?,?,?,?,?,?,1,'wechat',?,?)""",
|
||||
(f"DEMO-{n:04}", str(51200 + n % 20), DEMO_EMAIL, user_id,
|
||||
peer_id if n % 3 == 0 else None, start.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
end.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"宿舍区附近", "图书馆附近"))
|
||||
for n in range(72):
|
||||
when = (now - dt.timedelta(minutes=n * 10)).strftime("%Y-%m-%d %H:%M:%S")
|
||||
for bike in sample_bikes():
|
||||
conn.execute("""INSERT INTO bike_history (bike_code,latitude,longitude,state,status,electric,recorded_at)
|
||||
VALUES (?,?,?,?,?,?,?)""", (bike["code"], bike["latitude"], bike["longitude"],
|
||||
bike["state"], bike["status"], bike["electric_quantity"], when))
|
||||
parking = conn.execute("SELECT id FROM campus_locations WHERE kind='parking' ORDER BY id LIMIT 1").fetchone()[0]
|
||||
conn.execute("""INSERT INTO subscribe_rules (user_id,location_id,weekday,minute_of_day,notify_enabled,
|
||||
auto_unlock,enabled,kinds,min_electric,max_electric,sort_by,retry_times,last_run_at,last_run_status,last_run_message)
|
||||
VALUES (?,?,0,715,1,0,0,'small,big,red',20,100,'distance_asc',3,?,'success',?)""",
|
||||
(user_id, parking, now.strftime("%Y-%m-%d %H:%M:%S"), "演示:停车点附近有 6 辆符合条件的车辆"))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def install_preview(app):
|
||||
app.config["PREVIEW_MODE"] = True
|
||||
|
||||
@app.post("/api/preview/session")
|
||||
def create_test_session():
|
||||
from db import get_db
|
||||
from rate_limit import hit
|
||||
from routes.auth import _client_ip, hash_password
|
||||
if not hit(("preview_session", _client_ip()), 10, 3600):
|
||||
return jsonify(rtn_code=429, message="创建测试账号过于频繁,请稍后再试"), 429
|
||||
conn = get_db()
|
||||
email = "tester-" + secrets.token_hex(6) + "@preview.local"
|
||||
uid = conn.execute("INSERT INTO users (email,password_hash) VALUES (?,?)",
|
||||
(email, hash_password(secrets.token_urlsafe(32)))).lastrowid
|
||||
token = secrets.token_urlsafe(32)
|
||||
conn.execute("""INSERT INTO sessions (user_id,token,expires_at,device_name,last_active)
|
||||
VALUES (?,?,datetime('now','+8 hours','+30 days'),'预览测试浏览器',datetime('now','+8 hours'))""", (uid, token))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify(rtn_code=0, data={"token": token, "email": email})
|
||||
|
||||
@app.before_request
|
||||
def preview_requests():
|
||||
from routes.auth import get_current_user
|
||||
from db import get_db, get_user_rental_settings
|
||||
path = request.path
|
||||
if path == "/api/config":
|
||||
return jsonify(center_lat=36.531820, center_lng=116.780180, scale=17,
|
||||
school_name="山东管理学院", type_names={"1": "单车", "3": "电动车", "6": "助力车"}, preview=True)
|
||||
if not path.startswith("/api/") or path == "/api/preview/session":
|
||||
return None
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return None
|
||||
if user["email"] != DEMO_EMAIL:
|
||||
# The preview container has no production global token. Use this private
|
||||
# test account's explicitly supplied WeChat credentials for map queries.
|
||||
from wechat import request_with_user_auth
|
||||
if path == "/api/auth/save_token":
|
||||
with _lock:
|
||||
for key in [key for key in _live_maps if key[0] == user["id"]]:
|
||||
_live_maps.pop(key, None)
|
||||
if path == "/api/map":
|
||||
bike_type = request.args.get("type", "3")
|
||||
if bike_type not in ("1", "3", "6"):
|
||||
return jsonify(rtn_code=400, message="不支持的车辆类型"), 400
|
||||
key = (user["id"], bike_type)
|
||||
with _lock:
|
||||
cached = _live_maps.get(key)
|
||||
if not cached or cached[0] <= time.time():
|
||||
now = time.time()
|
||||
result = request_with_user_auth(user["id"], "GET", "/project/map", params={"type": bike_type})
|
||||
if result.get("rtn_code") == 401:
|
||||
result = {**result, "rtn_code": 400, "message": "请先在设置中填写微信凭证,再刷新车辆数据"}
|
||||
ttl = 60 if result.get("rtn_code") == 0 else 5
|
||||
result["map_snapshot"] = {"fetched_at": now if result.get("rtn_code") == 0 else None,
|
||||
"expires_at": now + ttl, "status": "fresh" if result.get("rtn_code") == 0 else "error"}
|
||||
_live_maps[key] = (now + ttl, result)
|
||||
if len(_live_maps) > 200:
|
||||
for expired in [k for k, v in _live_maps.items() if v[0] < now]:
|
||||
_live_maps.pop(expired, None)
|
||||
cached = _live_maps[key]
|
||||
response = jsonify(copy.deepcopy(cached[1]))
|
||||
response.headers["X-Map-Server-Time"] = str(time.time())
|
||||
response.headers["Cache-Control"] = "private, no-store"
|
||||
return response
|
||||
if path == "/api/bicycle":
|
||||
return jsonify(request_with_user_auth(user["id"], "POST", "/project/bicycle", data=request.get_json(silent=True) or {}))
|
||||
if path == "/api/find_bike":
|
||||
from urllib.parse import urlsplit
|
||||
from wechat import SEARCH_BIKE_URL
|
||||
return jsonify(request_with_user_auth(user["id"], "POST", urlsplit(SEARCH_BIKE_URL).path, data=request.get_json(silent=True) or {}))
|
||||
return None
|
||||
# Demo operations stay synthetic, even after live testing is enabled.
|
||||
if path.startswith("/api/subscribe/") or path in ("/api/campus/locations", "/api/auth/status", "/api/auth/logout", "/api/user/orders") or path.startswith("/api/auth/sessions"):
|
||||
return None
|
||||
if path == "/api/auth/rental_settings":
|
||||
if request.method == "POST":
|
||||
from db import normalize_rental_settings, save_user_rental_settings
|
||||
try:
|
||||
settings = normalize_rental_settings(request.get_json(silent=True) or {})
|
||||
except ValueError as exc:
|
||||
return jsonify(rtn_code=400, message=str(exc)), 400
|
||||
save_user_rental_settings(user["id"], settings)
|
||||
return jsonify(rtn_code=0, data=get_user_rental_settings(user["id"]))
|
||||
if path == "/api/auth/profile":
|
||||
return jsonify(rtn_code=0, data={"email": DEMO_EMAIL, "has_auth": True, "token_id": "", "access_token": "", "strict_mode": False,
|
||||
"rental_settings": get_user_rental_settings(user["id"]), "alert_email": DEMO_EMAIL})
|
||||
if path in ("/api/auth/user_info", "/api/user/info"):
|
||||
return jsonify(rtn_code=0, data={"has_auth": True, "true_name": "演示同学", "out_money": 12.5, "save_money": 86.0})
|
||||
if path == "/api/auth/packages":
|
||||
return jsonify(rtn_code=0, data={"has_auth": True, "packages": [{"name": "演示骑行月卡", "remain": 12, "remaining": 12, "expire_time": "2026-12-31"}]})
|
||||
if path.startswith("/api/auth/"):
|
||||
return jsonify(rtn_code=403, message="演示账号使用模拟数据;请创建独立测试账号后填写真实凭证"), 403
|
||||
if path == "/api/map":
|
||||
now = time.time()
|
||||
response = jsonify(rtn_code=0, data={"bicycleStation": sample_bikes(), "driverArea": [], "parkeArea": []},
|
||||
map_snapshot={"fetched_at": now, "expires_at": now + 60, "status": "fresh"})
|
||||
response.headers["X-Map-Server-Time"] = str(now)
|
||||
response.headers["Cache-Control"] = "private, no-store"
|
||||
return response
|
||||
if path == "/api/bicycle":
|
||||
code = str((request.get_json(silent=True) or {}).get("code", ""))
|
||||
bike = next((b for b in sample_bikes() if b["code"] == code), None)
|
||||
return jsonify(rtn_code=0, data=bike) if bike else jsonify(rtn_code=404, message="演示数据中没有这辆车,请从附近列表选择")
|
||||
if path == "/api/find_bike":
|
||||
return jsonify(rtn_code=0, message="模拟寻车成功", data={})
|
||||
token = request.headers.get("Authorization", "")
|
||||
with _lock:
|
||||
ride = _rides.get(token)
|
||||
if path == "/api/order/status":
|
||||
return jsonify(rtn_code=0, has_credentials=True, has_order=bool(ride), order=ride)
|
||||
if path == "/api/rental/status":
|
||||
settings = get_user_rental_settings(user["id"])
|
||||
end = ride.get("deadline") if ride else time.time()
|
||||
return jsonify(rtn_code=0, data={"active": bool(ride), "remaining_seconds": max(0, int(end - time.time())),
|
||||
"current_round": 1, "total_rounds": ride.get("rounds", 1) if ride else 1,
|
||||
"auto_return": settings["auto_return_enabled"],
|
||||
"final_end_time": dt.datetime.fromtimestamp(end, dt.timezone(dt.timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S")})
|
||||
if path == "/api/order/unlock":
|
||||
if ride:
|
||||
return jsonify(rtn_code=400, message="请先结束当前演示订单")
|
||||
data = request.get_json(silent=True) or {}
|
||||
code = str(data.get("code") or data.get("bike_code") or "51201")
|
||||
ride = {"order_id": "DEMO-LIVE-" + secrets.token_hex(4), "code": code, "status": 2, "deadline": time.time() + 19 * 60, "rounds": 1}
|
||||
_rides[token] = ride
|
||||
return jsonify(rtn_code=0, message="模拟开锁成功", data={**ride, "rental_id": 0, "duration_minutes": 19})
|
||||
if path == "/api/order/add_round":
|
||||
if ride:
|
||||
ride["deadline"] += 19 * 60
|
||||
ride["rounds"] += 1
|
||||
return jsonify(rtn_code=0, message="演示订单已追加一轮")
|
||||
if path in ("/api/order/return", "/api/rental/return", "/api/share/return"):
|
||||
_rides.pop(token, None)
|
||||
return jsonify(rtn_code=0, message="模拟还车成功", data={"returned": True, "paid": True})
|
||||
if path == "/api/order/preview":
|
||||
return jsonify(rtn_code=0, data={"has_card": True, "cards": [{"name": "演示骑行月卡", "remain": 12}],
|
||||
"auto_return": True, "rounds_planned": 1, "duration_minutes": 19, "est_end_time": "19 分钟后"})
|
||||
if path == "/api/share/sources":
|
||||
return jsonify(rtn_code=0, data={"sources": [], "hidden_count": 0})
|
||||
if path == "/api/share/active":
|
||||
return jsonify(rtn_code=0, data=[])
|
||||
if path.startswith("/api/share/"):
|
||||
return jsonify(rtn_code=0, data=[], pending=[], usable=[], mine=[])
|
||||
if path == "/api/rental/sync":
|
||||
return jsonify(rtn_code=0, data={"active": False})
|
||||
if path.startswith("/api/order/"):
|
||||
return jsonify(rtn_code=0, message="模拟操作成功", data={"paid": True})
|
||||
if path.startswith("/api/history/") or path.startswith("/api/analysis/") or path == "/api/bike_history":
|
||||
return None # Read-only seeded history through the real analysis code.
|
||||
if path == "/api/user/orders/trajectory":
|
||||
return jsonify(rtn_code=0, data={"points": [], "bike_code": "51201", "hint": "演示订单无完整轨迹"})
|
||||
return jsonify(rtn_code=403, message="演示模式暂不提供此操作"), 403
|
||||
@@ -1,21 +0,0 @@
|
||||
"""Dedicated preview entry point. Starts no collectors, schedulers or real timers."""
|
||||
from runtime_mode import PREVIEW_MODE
|
||||
|
||||
if not PREVIEW_MODE:
|
||||
raise RuntimeError("preview_server requires XBNIU_PREVIEW=1")
|
||||
|
||||
from app import app
|
||||
from db import init_db
|
||||
from preview_data import seed_preview
|
||||
|
||||
init_db()
|
||||
seed_preview()
|
||||
|
||||
# Real test accounts use the normal timers and notifications in this isolated database.
|
||||
from timer import restore_active_timers, start_all_order_checkers
|
||||
from subscribe import start_subscribe_scheduler
|
||||
from alerts import start_alert_scheduler
|
||||
restore_active_timers()
|
||||
start_all_order_checkers()
|
||||
start_subscribe_scheduler()
|
||||
start_alert_scheduler()
|
||||
-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-----
|
||||
+1322
-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 -*-
|
||||
"""抓包工具安装包下载
|
||||
|
||||
安装包体积较大(约 160MB),放在项目根的 downloads/ 目录而不是 static/,
|
||||
安装包体积较大(约 25MB),放在项目根的 downloads/ 目录而不是 static/,
|
||||
避免被 Flask 静态路由以外的缓存策略干扰,也便于单独替换升级。
|
||||
|
||||
公开访问:用户注册前就需要拿到工具,若加登录校验会形成「没工具拿不到凭据、
|
||||
@@ -18,7 +18,7 @@ bp = Blueprint("download", __name__)
|
||||
# 容易出编码问题。对外的下载文件名由 download_name 还原。
|
||||
DOWNLOADS_DIR = Path(__file__).parent.parent / "downloads"
|
||||
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"])
|
||||
|
||||
+22
-3
@@ -26,13 +26,32 @@ HISTORY_DAYS = 30
|
||||
|
||||
_STATE_LABELS = {
|
||||
"available": "可用", "used": "使用中", "locked": "欠压",
|
||||
"reserved": "损坏", "low": "低电量", "unknown": "未知",
|
||||
"reserved": "损坏", "low": "低电量",
|
||||
}
|
||||
|
||||
|
||||
def _classify(state, status, electric):
|
||||
from bike_data import classify
|
||||
return classify(state, status, electric)
|
||||
try:
|
||||
state = int(state)
|
||||
except (TypeError, ValueError):
|
||||
state = 1
|
||||
try:
|
||||
status = int(status)
|
||||
except (TypeError, ValueError):
|
||||
status = 1
|
||||
try:
|
||||
electric = float(electric)
|
||||
except (TypeError, ValueError):
|
||||
electric = 100.0
|
||||
if state == 10 or electric < 20:
|
||||
return "low"
|
||||
if state == 4:
|
||||
return "locked"
|
||||
if state == 2:
|
||||
return "reserved"
|
||||
if state == 1 and status == 1:
|
||||
return "used"
|
||||
return "available"
|
||||
|
||||
|
||||
def _clean_expired_tokens(conn):
|
||||
|
||||
+484
-434
@@ -1,434 +1,484 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""地图数据、寻车、分析等路由"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
import hashlib
|
||||
import threading
|
||||
import asyncio
|
||||
import aiohttp
|
||||
from pathlib import Path
|
||||
from flask import Blueprint, current_app, jsonify, request, render_template
|
||||
|
||||
from db import get_db, get_user_display_name, get_user_auth
|
||||
from routes.auth import get_current_user
|
||||
from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS
|
||||
|
||||
bp = Blueprint("map_api", __name__)
|
||||
|
||||
# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放
|
||||
BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
|
||||
|
||||
# 并行寻车任务
|
||||
ring_tasks: dict = {}
|
||||
_ring_lock = threading.Lock()
|
||||
|
||||
|
||||
async def ring_single_bike_async(session, bike_code, school_id=10):
|
||||
try:
|
||||
headers = {**SEARCH_HEADERS, **get_signature_headers()}
|
||||
async with session.post(
|
||||
SEARCH_BIKE_URL,
|
||||
json={"code": bike_code, "school_id": school_id},
|
||||
headers=headers,
|
||||
timeout=aiohttp.ClientTimeout(total=5)
|
||||
) as resp:
|
||||
data = await resp.json()
|
||||
return data.get("rtn_code") == 0 or data.get("success") is True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def run_ring_task(task_id: str):
|
||||
global ring_tasks
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return
|
||||
bikes = task["bikes"]
|
||||
total = len(bikes)
|
||||
task["total"] = total
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop)
|
||||
try:
|
||||
async def run_session():
|
||||
semaphore = asyncio.Semaphore(20)
|
||||
async with aiohttp.ClientSession(connector=connector) as session:
|
||||
async def ring_one(idx, code):
|
||||
async with semaphore:
|
||||
if task["cancelled"]:
|
||||
return False
|
||||
result = await ring_single_bike_async(session, code, 10)
|
||||
with _ring_lock:
|
||||
task["done"] += 1
|
||||
if result:
|
||||
task["success"] += 1
|
||||
else:
|
||||
task["failed"] += 1
|
||||
task["last_update"] = time.time()
|
||||
return result
|
||||
batch_size = 20
|
||||
for i in range(0, len(bikes), batch_size):
|
||||
if task["cancelled"]:
|
||||
break
|
||||
batch = bikes[i:i + batch_size]
|
||||
await asyncio.gather(
|
||||
*[ring_one(i + j, b["code"]) for j, b in enumerate(batch)],
|
||||
return_exceptions=True
|
||||
)
|
||||
await asyncio.sleep(0.1)
|
||||
loop.run_until_complete(run_session())
|
||||
finally:
|
||||
with _ring_lock:
|
||||
task["status"] = "completed" if not task["cancelled"] else "cancelled"
|
||||
task["done"] = total
|
||||
loop.close()
|
||||
|
||||
|
||||
@bp.route("/api/ring_all", methods=["POST"])
|
||||
def api_ring_all():
|
||||
global ring_tasks
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
if user["email"] not in BATCH_RING_ALLOWED_EMAILS:
|
||||
return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"})
|
||||
data = request.get_json() or {}
|
||||
codes = data.get("codes", [])
|
||||
if isinstance(codes, str):
|
||||
codes = [codes]
|
||||
if not codes:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}")
|
||||
task_id = str(uuid.uuid4())[:8]
|
||||
task = {
|
||||
"status": "running", "total": len(codes), "done": 0,
|
||||
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
|
||||
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
|
||||
}
|
||||
with _ring_lock:
|
||||
ring_tasks[task_id] = task
|
||||
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
|
||||
t.start()
|
||||
return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes),
|
||||
"message": f"任务已启动,共 {len(codes)} 辆车"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_status/<task_id>")
|
||||
def api_ring_status(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
|
||||
"done": task["done"], "success": task["success"], "failed": task["failed"]})
|
||||
|
||||
|
||||
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
|
||||
def api_ring_cancel(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
if task["status"] != "running":
|
||||
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
|
||||
task["cancelled"] = True
|
||||
task["status"] = "cancelling"
|
||||
return jsonify({"rtn_code": 0, "message": "取消请求已发送"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_progress/<task_id>")
|
||||
def api_ring_progress(task_id):
|
||||
from flask import Response as FlaskResponse
|
||||
global ring_tasks
|
||||
def _sse(obj):
|
||||
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
||||
def generate():
|
||||
last_done = -1
|
||||
last_status = None
|
||||
tick = 0
|
||||
while True:
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
|
||||
yield _sse({"type": "error", "message": "任务不存在或已结束"})
|
||||
return
|
||||
done = task["done"]
|
||||
status = task["status"]
|
||||
if done != last_done or status != last_status:
|
||||
last_done = done
|
||||
last_status = status
|
||||
yield _sse({
|
||||
"type": "progress",
|
||||
"status": status,
|
||||
"done": done,
|
||||
"total": task["total"],
|
||||
"success": task["success"],
|
||||
"failed": task["failed"],
|
||||
})
|
||||
if status in ("completed", "cancelled"):
|
||||
# 已结束,补发一条 done 事件后关闭
|
||||
yield _sse({"type": "done", "status": status})
|
||||
return
|
||||
tick += 1
|
||||
if tick >= 20: # 约 10s 一次心跳,避免代理/连接超时被判定为断开
|
||||
tick = 0
|
||||
yield ": ping\n\n"
|
||||
time.sleep(0.5)
|
||||
return FlaskResponse(
|
||||
generate(),
|
||||
mimetype="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
|
||||
def api_ring_status_clear(task_id):
|
||||
with _ring_lock:
|
||||
ring_tasks.pop(task_id, None)
|
||||
return jsonify({"rtn_code": 0, "message": "已清除"})
|
||||
|
||||
|
||||
@bp.route("/api/map")
|
||||
def api_map():
|
||||
# 非登录人员不能使用:地图数据需登录后查看
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
bike_type = request.args.get("type", "1").strip()
|
||||
from map_cache import MAP_TYPES
|
||||
if bike_type not in MAP_TYPES:
|
||||
return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400
|
||||
result = request_api("GET", "/project/map", params={"type": bike_type})
|
||||
# 上游错误文案统一翻译(成功响应原样透传)
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
response = jsonify(result)
|
||||
# Only the server snapshot is cached; browsers must ask the server on refresh.
|
||||
response.headers["Cache-Control"] = "private, no-store"
|
||||
response.headers["Vary"] = "Authorization"
|
||||
response.headers["X-Map-Server-Time"] = str(time.time())
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/api/bicycle", methods=["GET", "POST"])
|
||||
def api_bicycle():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
code = data.get("code", "")
|
||||
if not code:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}")
|
||||
result = request_api("POST", "/project/bicycle", data={"code": code})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/find_bike", methods=["POST"])
|
||||
def api_find_bike():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
keyword = (data.get("keyword") or data.get("code") or "").strip()
|
||||
if not keyword:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少关键字"})
|
||||
school_id = data.get("school_id", 10)
|
||||
result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/config")
|
||||
def api_config():
|
||||
return jsonify({
|
||||
"center_lat": 36.531820, "center_lng": 116.780180,
|
||||
"scale": 17, "school_name": "山东管理学院",
|
||||
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
|
||||
})
|
||||
|
||||
|
||||
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
|
||||
@bp.route("/api/map/freshness")
|
||||
def api_map_freshness():
|
||||
"""优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。
|
||||
|
||||
只读取缓存元数据,不会为了查询时间额外请求上游。
|
||||
"""
|
||||
from map_cache import shared_map_cache
|
||||
snapshot = shared_map_cache.freshness(request.args.get("type", "3"))
|
||||
if snapshot is not None:
|
||||
response = jsonify({"rtn_code": 0, "data": snapshot})
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone()
|
||||
conn.close()
|
||||
latest = row["latest"] if row else None
|
||||
if not latest:
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}})
|
||||
|
||||
import datetime as dt
|
||||
import sqlite3
|
||||
# recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源
|
||||
try:
|
||||
naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S")
|
||||
latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
|
||||
now = dt.datetime.now(latest_dt.tzinfo)
|
||||
stale = max(0, int((now - latest_dt).total_seconds()))
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": None,
|
||||
"interval_hint": "时间格式异常"}})
|
||||
|
||||
hint = "白天 5-10 分钟 / 夜间 30-60 分钟"
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": stale, "interval_hint": hint}})
|
||||
|
||||
|
||||
@bp.route("/api/campus/locations")
|
||||
def campus_locations():
|
||||
"""校园地点(单点模型)。
|
||||
|
||||
- kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」;
|
||||
- kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。
|
||||
|
||||
返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。
|
||||
"""
|
||||
from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations
|
||||
result = []
|
||||
for loc in load_locations():
|
||||
item = {
|
||||
"id": loc["id"],
|
||||
"name": loc["name"],
|
||||
"kind": loc.get("kind") or "poi",
|
||||
"latitude": loc.get("latitude"),
|
||||
"longitude": loc.get("longitude"),
|
||||
"radius": loc.get("radius") or (
|
||||
DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None),
|
||||
"bd09": None,
|
||||
}
|
||||
if loc.get("latitude") is not None and loc.get("longitude") is not None:
|
||||
bd = gcj02_to_bd09(loc["longitude"], loc["latitude"])
|
||||
item["bd09"] = {"lat": bd[1], "lng": bd[0]}
|
||||
result.append(item)
|
||||
return jsonify({"rtn_code": 0, "data": result})
|
||||
|
||||
|
||||
# ========== 用户信息 API ==========
|
||||
@bp.route("/api/user/info")
|
||||
def api_user_info():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
from wechat import request_with_user_auth
|
||||
token_id, access_token = get_user_auth(user["id"])
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"})
|
||||
|
||||
result = request_with_user_auth(user["id"], "GET", "/user/info")
|
||||
if result.get("rtn_code") != 0:
|
||||
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")})
|
||||
|
||||
data = result.get("data", {})
|
||||
non_deal = data.get("nonDealOrder")
|
||||
true_name = ""
|
||||
account = data.get("account", {})
|
||||
if isinstance(account, str):
|
||||
try:
|
||||
account = json.loads(account)
|
||||
except Exception:
|
||||
account = {}
|
||||
true_name = account.get("trueName", "") if isinstance(account, dict) else ""
|
||||
|
||||
out_money = data.get("bus_account", {}).get("outMoneyBus", 0)
|
||||
save_money = data.get("bus_account", {}).get("saveMoneyBus", 0)
|
||||
|
||||
return jsonify({
|
||||
"rtn_code": 0, "has_auth": True,
|
||||
"data": {
|
||||
"true_name": true_name, "out_money": out_money,
|
||||
"save_money": save_money, "has_auth": True,
|
||||
"nonDealOrder": non_deal,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
# ========== 首页路由 ==========
|
||||
MAP_ASSETS = (
|
||||
"js/ui-preferences.js",
|
||||
"css/map.css",
|
||||
"css/bike-clusters.css",
|
||||
"css/map-settings.css",
|
||||
"css/ui-system.css",
|
||||
"css/theme-modes.css",
|
||||
"css/map-discovery.css",
|
||||
"js/ui-motion.js",
|
||||
"js/qrcode.min.js",
|
||||
"js/coordtransform.js",
|
||||
"js/bike-clusters.js",
|
||||
"js/settings-pages.js",
|
||||
"js/bike-data.js",
|
||||
"js/api-client.js",
|
||||
"js/ui-dialogs.js",
|
||||
"js/map.js",
|
||||
"js/map-account.js",
|
||||
"js/map-orders.js",
|
||||
"js/map-history.js",
|
||||
"js/map-subscriptions.js",
|
||||
"js/map-rental.js",
|
||||
"js/map-utils.js",
|
||||
"js/map-sharing.js",
|
||||
"js/map-discovery.js",
|
||||
"js/map-boot.js",
|
||||
)
|
||||
|
||||
|
||||
def _map_asset_version():
|
||||
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
|
||||
digest = hashlib.sha256()
|
||||
for filename in MAP_ASSETS:
|
||||
digest.update(filename.encode())
|
||||
try:
|
||||
digest.update((Path(current_app.static_folder) / filename).read_bytes())
|
||||
except FileNotFoundError:
|
||||
digest.update(b"missing")
|
||||
return digest.hexdigest()[:16]
|
||||
|
||||
|
||||
@bp.route("/")
|
||||
def index():
|
||||
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version(), preview_mode=current_app.config.get("PREVIEW_MODE", False)))
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/analysis.html")
|
||||
def analysis_page():
|
||||
return render_template("analysis.html")
|
||||
|
||||
|
||||
@bp.route("/ring_progress.html")
|
||||
def ring_progress():
|
||||
return render_template("ring_progress.html")
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""地图数据、寻车、分析等路由"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
import hashlib
|
||||
import threading
|
||||
import asyncio
|
||||
import aiohttp
|
||||
from pathlib import Path
|
||||
from flask import Blueprint, current_app, jsonify, request, render_template
|
||||
|
||||
from db import get_db, get_user_display_name, get_user_auth
|
||||
from routes.auth import get_current_user
|
||||
from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS
|
||||
|
||||
bp = Blueprint("map_api", __name__)
|
||||
|
||||
# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放
|
||||
BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
|
||||
|
||||
# 并行寻车任务
|
||||
ring_tasks: dict = {}
|
||||
_ring_lock = threading.Lock()
|
||||
|
||||
|
||||
async def ring_single_bike_async(session, bike_code, school_id=10):
|
||||
try:
|
||||
headers = {**SEARCH_HEADERS, **get_signature_headers()}
|
||||
async with session.post(
|
||||
SEARCH_BIKE_URL,
|
||||
json={"code": bike_code, "school_id": school_id},
|
||||
headers=headers,
|
||||
timeout=aiohttp.ClientTimeout(total=5)
|
||||
) as resp:
|
||||
data = await resp.json()
|
||||
return data.get("rtn_code") == 0 or data.get("success") is True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def run_ring_task(task_id: str):
|
||||
global ring_tasks
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return
|
||||
bikes = task["bikes"]
|
||||
total = len(bikes)
|
||||
task["total"] = total
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop)
|
||||
try:
|
||||
async def run_session():
|
||||
semaphore = asyncio.Semaphore(20)
|
||||
async with aiohttp.ClientSession(connector=connector) as session:
|
||||
async def ring_one(idx, code):
|
||||
async with semaphore:
|
||||
if task["cancelled"]:
|
||||
return False
|
||||
result = await ring_single_bike_async(session, code, 10)
|
||||
with _ring_lock:
|
||||
task["done"] += 1
|
||||
if result:
|
||||
task["success"] += 1
|
||||
else:
|
||||
task["failed"] += 1
|
||||
task["last_update"] = time.time()
|
||||
return result
|
||||
batch_size = 20
|
||||
for i in range(0, len(bikes), batch_size):
|
||||
if task["cancelled"]:
|
||||
break
|
||||
batch = bikes[i:i + batch_size]
|
||||
await asyncio.gather(
|
||||
*[ring_one(i + j, b["code"]) for j, b in enumerate(batch)],
|
||||
return_exceptions=True
|
||||
)
|
||||
await asyncio.sleep(0.1)
|
||||
loop.run_until_complete(run_session())
|
||||
finally:
|
||||
with _ring_lock:
|
||||
task["status"] = "completed" if not task["cancelled"] else "cancelled"
|
||||
task["done"] = total
|
||||
loop.close()
|
||||
|
||||
|
||||
@bp.route("/api/ring_all", methods=["POST"])
|
||||
def api_ring_all():
|
||||
global ring_tasks
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
if user["email"] not in BATCH_RING_ALLOWED_EMAILS:
|
||||
return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"})
|
||||
data = request.get_json() or {}
|
||||
codes = data.get("codes", [])
|
||||
if isinstance(codes, str):
|
||||
codes = [codes]
|
||||
if not codes:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}")
|
||||
task_id = str(uuid.uuid4())[:8]
|
||||
task = {
|
||||
"status": "running", "total": len(codes), "done": 0,
|
||||
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
|
||||
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
|
||||
}
|
||||
with _ring_lock:
|
||||
ring_tasks[task_id] = task
|
||||
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
|
||||
t.start()
|
||||
return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes),
|
||||
"message": f"任务已启动,共 {len(codes)} 辆车"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_status/<task_id>")
|
||||
def api_ring_status(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
|
||||
"done": task["done"], "success": task["success"], "failed": task["failed"]})
|
||||
|
||||
|
||||
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
|
||||
def api_ring_cancel(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
if task["status"] != "running":
|
||||
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
|
||||
task["cancelled"] = True
|
||||
task["status"] = "cancelling"
|
||||
return jsonify({"rtn_code": 0, "message": "取消请求已发送"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_progress/<task_id>")
|
||||
def api_ring_progress(task_id):
|
||||
from flask import Response as FlaskResponse
|
||||
global ring_tasks
|
||||
def _sse(obj):
|
||||
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
||||
def generate():
|
||||
last_done = -1
|
||||
last_status = None
|
||||
tick = 0
|
||||
while True:
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
|
||||
yield _sse({"type": "error", "message": "任务不存在或已结束"})
|
||||
return
|
||||
done = task["done"]
|
||||
status = task["status"]
|
||||
if done != last_done or status != last_status:
|
||||
last_done = done
|
||||
last_status = status
|
||||
yield _sse({
|
||||
"type": "progress",
|
||||
"status": status,
|
||||
"done": done,
|
||||
"total": task["total"],
|
||||
"success": task["success"],
|
||||
"failed": task["failed"],
|
||||
})
|
||||
if status in ("completed", "cancelled"):
|
||||
# 已结束,补发一条 done 事件后关闭
|
||||
yield _sse({"type": "done", "status": status})
|
||||
return
|
||||
tick += 1
|
||||
if tick >= 20: # 约 10s 一次心跳,避免代理/连接超时被判定为断开
|
||||
tick = 0
|
||||
yield ": ping\n\n"
|
||||
time.sleep(0.5)
|
||||
return FlaskResponse(
|
||||
generate(),
|
||||
mimetype="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
|
||||
def api_ring_status_clear(task_id):
|
||||
with _ring_lock:
|
||||
ring_tasks.pop(task_id, None)
|
||||
return jsonify({"rtn_code": 0, "message": "已清除"})
|
||||
|
||||
|
||||
@bp.route("/api/map")
|
||||
def api_map():
|
||||
# 非登录人员不能使用:地图数据需登录后查看
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
bike_type = request.args.get("type", "1").strip()
|
||||
from map_cache import MAP_TYPES
|
||||
if bike_type not in MAP_TYPES:
|
||||
return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400
|
||||
result = request_api("GET", "/project/map", params={"type": bike_type})
|
||||
# 上游错误文案统一翻译(成功响应原样透传)
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
response = jsonify(result)
|
||||
# Only the server snapshot is cached; browsers must ask the server on refresh.
|
||||
response.headers["Cache-Control"] = "private, no-store"
|
||||
response.headers["Vary"] = "Authorization"
|
||||
response.headers["X-Map-Server-Time"] = str(time.time())
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/api/bicycle", methods=["GET", "POST"])
|
||||
def api_bicycle():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
code = data.get("code", "")
|
||||
if not code:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}")
|
||||
result = request_api("POST", "/project/bicycle", data={"code": code})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/find_bike", methods=["POST"])
|
||||
def api_find_bike():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
keyword = (data.get("keyword") or data.get("code") or "").strip()
|
||||
if not keyword:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少关键字"})
|
||||
school_id = data.get("school_id", 10)
|
||||
result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/config")
|
||||
def api_config():
|
||||
return jsonify({
|
||||
"center_lat": 36.531820, "center_lng": 116.780180,
|
||||
"scale": 17, "school_name": "山东管理学院",
|
||||
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
|
||||
})
|
||||
|
||||
|
||||
@bp.route("/api/nav_route")
|
||||
def api_nav_route():
|
||||
"""导航路线:距离/耗时/分段指引/整条折线(前端直接画到地图上)。
|
||||
|
||||
参数:origin_lat/origin_lng/dest_lat/dest_lng(GCJ02),mode=walking|riding
|
||||
返回:{rtn_code:0, data:{distance, duration, points:[[lng,lat],...], steps:[...]}}
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
|
||||
from routes.auth import _client_ip
|
||||
from rate_limit import hit as rl_hit
|
||||
# 导航比查卡片更重,按 IP 每分钟 20 次
|
||||
if not rl_hit(("nav_route", _client_ip()), 20, 60):
|
||||
return jsonify({"rtn_code": 429, "message": "导航请求过于频繁,请稍后再试"}), 429
|
||||
|
||||
try:
|
||||
o_lat = float(request.args.get("origin_lat"))
|
||||
o_lng = float(request.args.get("origin_lng"))
|
||||
d_lat = float(request.args.get("dest_lat"))
|
||||
d_lng = float(request.args.get("dest_lng"))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"})
|
||||
|
||||
mode = (request.args.get("mode") or "walking").strip().lower()
|
||||
if mode not in ("walking", "riding"):
|
||||
mode = "walking"
|
||||
|
||||
import walk_route
|
||||
data = walk_route.get_nav_route(o_lat, o_lng, d_lat, d_lng, api=mode)
|
||||
if data.get("error"):
|
||||
return jsonify({"rtn_code": 500, "message": data["error"]}), 200
|
||||
response = jsonify({"rtn_code": 0, "data": data})
|
||||
response.headers["Cache-Control"] = "private, max-age=30"
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/api/walk_route")
|
||||
def api_walk_route():
|
||||
"""步行路线:真实道路距离 + 步行耗时(百度轻量级路线规划)。
|
||||
|
||||
参数:origin_lat/origin_lng/dest_lat/dest_lng,**全部 GCJ02**
|
||||
(前端要把 BD09 的我方位置先转 GCJ02 再传)。
|
||||
返回:{rtn_code:0, data:{distance, duration, source}}
|
||||
source = baidu(实时)/ cache(命中缓存)/ estimate(百度不可用时的本地估算)
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
|
||||
from routes.auth import _client_ip
|
||||
from rate_limit import hit as rl_hit
|
||||
# 保护百度配额:同一 IP 每分钟 60 次(正常点卡片远低于此)
|
||||
if not rl_hit(("walk_route", _client_ip()), 60, 60):
|
||||
return jsonify({"rtn_code": 429, "message": "请求过于频繁,请稍后再试"}), 429
|
||||
|
||||
try:
|
||||
o_lat = float(request.args.get("origin_lat"))
|
||||
o_lng = float(request.args.get("origin_lng"))
|
||||
d_lat = float(request.args.get("dest_lat"))
|
||||
d_lng = float(request.args.get("dest_lng"))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"})
|
||||
|
||||
import walk_route
|
||||
data = walk_route.get_walk_route(o_lat, o_lng, d_lat, d_lng)
|
||||
response = jsonify({"rtn_code": 0, "data": data})
|
||||
response.headers["Cache-Control"] = "private, max-age=60"
|
||||
return response
|
||||
|
||||
|
||||
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
|
||||
@bp.route("/api/map/freshness")
|
||||
def api_map_freshness():
|
||||
"""优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。
|
||||
|
||||
只读取缓存元数据,不会为了查询时间额外请求上游。
|
||||
"""
|
||||
from map_cache import shared_map_cache
|
||||
snapshot = shared_map_cache.freshness(request.args.get("type", "3"))
|
||||
if snapshot is not None:
|
||||
response = jsonify({"rtn_code": 0, "data": snapshot})
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone()
|
||||
conn.close()
|
||||
latest = row["latest"] if row else None
|
||||
if not latest:
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}})
|
||||
|
||||
import datetime as dt
|
||||
import sqlite3
|
||||
# recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源
|
||||
try:
|
||||
naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S")
|
||||
latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
|
||||
now = dt.datetime.now(latest_dt.tzinfo)
|
||||
stale = max(0, int((now - latest_dt).total_seconds()))
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": None,
|
||||
"interval_hint": "时间格式异常"}})
|
||||
|
||||
hint = "白天 5-10 分钟 / 夜间 30-60 分钟"
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": stale, "interval_hint": hint}})
|
||||
|
||||
|
||||
@bp.route("/api/campus/locations")
|
||||
def campus_locations():
|
||||
"""校园地点(单点模型)。
|
||||
|
||||
- kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」;
|
||||
- kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。
|
||||
|
||||
返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。
|
||||
"""
|
||||
from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations
|
||||
result = []
|
||||
for loc in load_locations():
|
||||
item = {
|
||||
"id": loc["id"],
|
||||
"name": loc["name"],
|
||||
"kind": loc.get("kind") or "poi",
|
||||
"latitude": loc.get("latitude"),
|
||||
"longitude": loc.get("longitude"),
|
||||
"radius": loc.get("radius") or (
|
||||
DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None),
|
||||
"bd09": None,
|
||||
}
|
||||
if loc.get("latitude") is not None and loc.get("longitude") is not None:
|
||||
bd = gcj02_to_bd09(loc["longitude"], loc["latitude"])
|
||||
item["bd09"] = {"lat": bd[1], "lng": bd[0]}
|
||||
result.append(item)
|
||||
return jsonify({"rtn_code": 0, "data": result})
|
||||
|
||||
|
||||
# ========== 用户信息 API ==========
|
||||
@bp.route("/api/user/info")
|
||||
def api_user_info():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
from wechat import request_with_user_auth
|
||||
token_id, access_token = get_user_auth(user["id"])
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"})
|
||||
|
||||
result = request_with_user_auth(user["id"], "GET", "/user/info")
|
||||
if result.get("rtn_code") != 0:
|
||||
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")})
|
||||
|
||||
data = result.get("data", {})
|
||||
non_deal = data.get("nonDealOrder")
|
||||
true_name = ""
|
||||
account = data.get("account", {})
|
||||
if isinstance(account, str):
|
||||
try:
|
||||
account = json.loads(account)
|
||||
except Exception:
|
||||
account = {}
|
||||
true_name = account.get("trueName", "") if isinstance(account, dict) else ""
|
||||
|
||||
out_money = data.get("bus_account", {}).get("outMoneyBus", 0)
|
||||
save_money = data.get("bus_account", {}).get("saveMoneyBus", 0)
|
||||
|
||||
return jsonify({
|
||||
"rtn_code": 0, "has_auth": True,
|
||||
"data": {
|
||||
"true_name": true_name, "out_money": out_money,
|
||||
"save_money": save_money, "has_auth": True,
|
||||
"nonDealOrder": non_deal,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
# ========== 首页路由 ==========
|
||||
MAP_ASSETS = (
|
||||
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
|
||||
"js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
|
||||
"js/settings-pages.js", "js/navigation.js", "js/share.js", "js/subscribe.js", "js/map.js",
|
||||
)
|
||||
|
||||
|
||||
def _map_asset_version():
|
||||
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
|
||||
digest = hashlib.sha256()
|
||||
for filename in MAP_ASSETS:
|
||||
digest.update(filename.encode())
|
||||
try:
|
||||
digest.update((Path(current_app.static_folder) / filename).read_bytes())
|
||||
except FileNotFoundError:
|
||||
digest.update(b"missing")
|
||||
return digest.hexdigest()[:16]
|
||||
|
||||
|
||||
@bp.route("/")
|
||||
def index():
|
||||
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/analysis.html")
|
||||
def analysis_page():
|
||||
return render_template("analysis.html")
|
||||
|
||||
|
||||
@bp.route("/ring_progress.html")
|
||||
def ring_progress():
|
||||
return render_template("ring_progress.html")
|
||||
|
||||
+1795
-1514
File diff suppressed because it is too large
Load Diff
+936
-932
File diff suppressed because it is too large
Load Diff
+66
-32
@@ -30,9 +30,6 @@ def _rule_row(row: dict, locations_by_id: dict) -> dict:
|
||||
"auto_unlock": bool(row["auto_unlock"]),
|
||||
"enabled": bool(row["enabled"]),
|
||||
"last_fired_on": row.get("last_fired_on") or "",
|
||||
"last_run_at": row.get("last_run_at"),
|
||||
"last_run_status": row.get("last_run_status"),
|
||||
"last_run_message": row.get("last_run_message"),
|
||||
# 自动开锁筛选配置
|
||||
"kinds": flt["kinds"],
|
||||
"min_electric": flt["min_electric"],
|
||||
@@ -108,37 +105,74 @@ def rules_update(rule_id: int):
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 404, "message": "规则不存在"})
|
||||
current = dict(row)
|
||||
allowed = {"enabled", "notify_enabled", "auto_unlock", "location_id", "weekday", "time",
|
||||
"kinds", "min_electric", "max_electric", "sort_by", "retry_times"}
|
||||
if not data or not set(data).intersection(allowed):
|
||||
updates = []
|
||||
params = []
|
||||
|
||||
def _truthy(v):
|
||||
return 1 if v in (True, 1, "1", "true") else 0
|
||||
|
||||
if "enabled" in data:
|
||||
updates.append("enabled = ?")
|
||||
params.append(_truthy(data.get("enabled")))
|
||||
if "notify_enabled" in data:
|
||||
updates.append("notify_enabled = ?")
|
||||
params.append(_truthy(data.get("notify_enabled")))
|
||||
if "auto_unlock" in data:
|
||||
updates.append("auto_unlock = ?")
|
||||
params.append(_truthy(data.get("auto_unlock")))
|
||||
|
||||
# 组合校验:任何一个筛选字段变化时,用「现值 + 新值」整体校验一次
|
||||
filter_keys = ("kinds", "min_electric", "max_electric", "sort_by", "retry_times")
|
||||
if any(k in data for k in filter_keys):
|
||||
flt = sub.rule_filters(current)
|
||||
merged = {
|
||||
"location_id": current.get("location_id"),
|
||||
"weekday": current.get("weekday"),
|
||||
"time": "%02d:%02d" % (int(current.get("minute_of_day") or 0) // 60,
|
||||
int(current.get("minute_of_day") or 0) % 60),
|
||||
"kinds": data.get("kinds", flt["kinds"]),
|
||||
"min_electric": data.get("min_electric", flt["min_electric"]),
|
||||
"max_electric": data.get("max_electric", flt["max_electric"]),
|
||||
"sort_by": data.get("sort_by", flt["sort_by"]),
|
||||
"retry_times": data.get("retry_times", flt["retry_times"]),
|
||||
"notify_enabled": True,
|
||||
"auto_unlock": bool(current.get("auto_unlock")),
|
||||
}
|
||||
try:
|
||||
fields = sub.normalize_rule(merged)
|
||||
except ValueError as exc:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
updates.extend(["kinds = ?", "min_electric = ?", "max_electric = ?",
|
||||
"sort_by = ?", "retry_times = ?"])
|
||||
params.extend([fields["kinds"], fields["min_electric"], fields["max_electric"],
|
||||
fields["sort_by"], fields["retry_times"]])
|
||||
|
||||
if ("time" in data and "weekday" in data) or ("time" in data or "weekday" in data):
|
||||
merged_time = {
|
||||
"location_id": current.get("location_id"),
|
||||
"weekday": data.get("weekday", current.get("weekday")),
|
||||
"time": data.get("time") or "%02d:%02d" % (
|
||||
int(current.get("minute_of_day") or 0) // 60,
|
||||
int(current.get("minute_of_day") or 0) % 60),
|
||||
}
|
||||
try:
|
||||
fields = sub.normalize_rule(merged_time)
|
||||
except ValueError as exc:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
updates.extend(["weekday = ?", "minute_of_day = ?"])
|
||||
params.extend([fields["weekday"], fields["minute_of_day"]])
|
||||
|
||||
if not updates:
|
||||
conn.close()
|
||||
return jsonify(rtn_code=400, message="没有需要更新的字段"), 400
|
||||
filters = sub.rule_filters(current)
|
||||
merged = {**filters, "location_id": current["location_id"], "weekday": current["weekday"],
|
||||
"time": "%02d:%02d" % divmod(current["minute_of_day"], 60),
|
||||
"notify_enabled": bool(current["notify_enabled"]), "auto_unlock": bool(current["auto_unlock"])}
|
||||
merged.update({k: v for k, v in data.items() if k in allowed})
|
||||
try:
|
||||
fields = sub.normalize_rule(merged)
|
||||
from campus import get_location
|
||||
location = get_location(fields["location_id"])
|
||||
if not location or location.get("kind") != "parking":
|
||||
raise ValueError("订阅只能选择有效停车点")
|
||||
enabled = data.get("enabled", bool(current["enabled"]))
|
||||
if enabled not in (True, False, 0, 1, "0", "1", "true", "false"):
|
||||
raise ValueError("启用状态无效")
|
||||
enabled = int(enabled in (True, 1, "1", "true"))
|
||||
except (TypeError, ValueError) as exc:
|
||||
conn.close()
|
||||
return jsonify(rtn_code=400, message=str(exc)), 400
|
||||
columns = ("location_id", "weekday", "minute_of_day", "notify_enabled", "auto_unlock",
|
||||
"kinds", "min_electric", "max_electric", "sort_by", "retry_times")
|
||||
values = [int(fields[k]) if k in ("notify_enabled", "auto_unlock") else fields[k] for k in columns]
|
||||
conn.execute("UPDATE subscribe_rules SET " + ", ".join(k + " = ?" for k in columns) +
|
||||
", enabled = ? WHERE id = ? AND user_id = ?", (*values, enabled, rule_id, user["id"]))
|
||||
return jsonify({"rtn_code": 400, "message": "没有需要更新的字段"})
|
||||
params.extend([rule_id, user["id"]])
|
||||
conn.execute(f"UPDATE subscribe_rules SET {', '.join(updates)} "
|
||||
f"WHERE id = ? AND user_id = ?", params)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify(rtn_code=0, message="规则已更新")
|
||||
return jsonify({"rtn_code": 0, "message": "规则已更新"})
|
||||
|
||||
|
||||
@bp.route("/api/subscribe/rules/<int:rule_id>", methods=["DELETE"])
|
||||
@@ -163,4 +197,4 @@ def subscribe_options():
|
||||
{"key": "red", "label": "红车"}],
|
||||
"sort_by": [{"key": k, "label": v} for k, v in sub.SORT_OPTIONS.items()],
|
||||
"auto_unlock_enabled": sub.AUTO_UNLOCK_ENABLED,
|
||||
}})
|
||||
}})
|
||||
@@ -1,4 +0,0 @@
|
||||
"""An explicit process-level switch, never controlled by an HTTP request."""
|
||||
import os
|
||||
|
||||
PREVIEW_MODE = os.environ.get("XBNIU_PREVIEW", "").strip().lower() in ("1", "true", "yes")
|
||||
@@ -6,8 +6,7 @@ $zip = Join-Path $src '1.zip'
|
||||
$pendingZip = Join-Path $src '1.zip.tmp'
|
||||
|
||||
$include = @(
|
||||
'.gitignore','.dockerignore','Dockerfile','Dockerfile.preview','LICENSE','README.md','app.py','db.py','campus.py','alerts.py','subscribe.py',
|
||||
'bike_data.py','runtime_mode.py','preview_data.py','preview_server.py',
|
||||
'.gitignore','LICENSE','README.md','app.py','db.py','campus.py','alerts.py','subscribe.py',
|
||||
'email_utils.py','email_verify.py','generate_icons.py','map_cache.py','pytest.ini','rate_limit.py',
|
||||
'rental_mail.py','requirements.txt','server_config.json','timer.py',
|
||||
'update_creds_from_capture.py','wechat.py'
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""百度「步行路线规划(轻量)」连通性探针。
|
||||
|
||||
用法(把你的 AK/SK 填进来):
|
||||
PowerShell:
|
||||
$env:BAIDU_ROUTE_AK="你的AK"; $env:BAIDU_ROUTE_SK="你的SK"
|
||||
python scripts/probe_baidu_route.py
|
||||
bash:
|
||||
BAIDU_ROUTE_AK=... BAIDU_ROUTE_SK=... python scripts/probe_baidu_route.py
|
||||
|
||||
会依次尝试两种 SN 算法(官方样例 / 社区写法),打印谁通了、返回多少米多少秒。
|
||||
通了就把 AK/SK 写进 server_config.json:
|
||||
{ "baidu_route_ak": "...", "baidu_route_sk": "..." }
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import walk_route
|
||||
|
||||
# 校内两点(GCJ02):学生公寓附近 -> 教学楼附近
|
||||
ORIGIN = (36.529440, 116.783740)
|
||||
DEST = (36.534240, 116.787190)
|
||||
|
||||
|
||||
def main():
|
||||
ak = walk_route.get_ak()
|
||||
sk = walk_route.get_sk()
|
||||
print(f"AK: {ak[:8] + '…' if ak else '(未配置)'} SK: {'已配置(' + str(len(sk)) + '位)' if sk else '(未配置)'}")
|
||||
if not ak:
|
||||
print("先设置 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK 再跑")
|
||||
return 2
|
||||
|
||||
ok = False
|
||||
for mode in ("official", "simple"):
|
||||
try:
|
||||
got = walk_route._call_baidu(ak, sk, *ORIGIN, *DEST, mode)
|
||||
print(f"[{mode:8}] ✔ 通过 distance={got['distance']} 米 "
|
||||
f"duration={got['duration']} 秒 ({got['duration'] / 60:.1f} 分钟)")
|
||||
ok = True
|
||||
except Exception as exc:
|
||||
print(f"[{mode:8}] ✘ {exc}")
|
||||
|
||||
print("\n结论:", "SN 算法可用,把 AK/SK 写进 server_config.json 即可。" if ok else
|
||||
"两种算法都没通,检查 AK 是否开启了「步行路线规划(轻量)」、SK 是否正确、配额是否用尽。")
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+279
-279
@@ -1,279 +1,279 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""冒烟测试:验证应用可启动、路由无冲突、关键接口可响应。"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根
|
||||
|
||||
# 注意: app.py 导入时会重新包装 sys.stdout, 这里不能自己再包一层,
|
||||
# 否则旧包装器被 GC 时会关闭底层 buffer。编码由 PYTHONIOENCODING 控制。
|
||||
_ORIG_STDOUT = sys.stdout # 持有引用, 防止被 GC 后关闭底层流
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
PASS, FAIL = [], []
|
||||
|
||||
|
||||
def check(name, fn):
|
||||
try:
|
||||
detail = fn()
|
||||
PASS.append((name, detail))
|
||||
print(f" [PASS] {name}" + (f" — {detail}" if detail else ""))
|
||||
except Exception as e:
|
||||
FAIL.append((name, f"{type(e).__name__}: {e}"))
|
||||
print(f" [FAIL] {name} — {type(e).__name__}: {e}")
|
||||
|
||||
|
||||
print("=" * 60)
|
||||
print("1) 模块导入检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def import_app():
|
||||
import app as app_module
|
||||
return f"app 模块导入成功, 蓝图 {len(app_module.app.blueprints)} 个: {', '.join(app_module.app.blueprints)}"
|
||||
|
||||
|
||||
check("导入 app.py 及全部依赖 (db/wechat/timer/routes.*)", import_app)
|
||||
|
||||
|
||||
def import_side_modules():
|
||||
import rental_mail, email_utils, generate_icons # noqa: F401
|
||||
return "rental_mail / email_utils / generate_icons 导入成功"
|
||||
|
||||
|
||||
check("导入其余业务模块", import_side_modules)
|
||||
|
||||
app_obj = None
|
||||
try:
|
||||
import app as app_module
|
||||
app_obj = app_module.app
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("2) 路由冲突检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def route_conflicts():
|
||||
rules = defaultdict(list)
|
||||
for r in app_obj.url_map.iter_rules():
|
||||
if r.endpoint == "static":
|
||||
continue
|
||||
methods = sorted(m for m in r.methods if m not in ("HEAD", "OPTIONS"))
|
||||
for m in methods:
|
||||
rules[(m, r.rule)].append(r.endpoint)
|
||||
dupes = {k: v for k, v in rules.items() if len(v) > 1}
|
||||
if dupes:
|
||||
raise AssertionError(f"发现 {len(dupes)} 处路由冲突: {dupes}")
|
||||
return f"共 {len(rules)} 条 (method, path) 规则, 无重复注册"
|
||||
|
||||
|
||||
check("检查重复路由 (Flask 静默覆盖, 需显式检测)", route_conflicts)
|
||||
|
||||
|
||||
def route_summary():
|
||||
rules = sorted(r.rule for r in app_obj.url_map.iter_rules() if r.endpoint != "static")
|
||||
return f"{len(rules)} 条路由"
|
||||
|
||||
|
||||
check("路由注册成功", route_summary)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("3) 数据库连通性")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def db_check():
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
p = Path("users.db")
|
||||
if not p.exists():
|
||||
raise AssertionError("users.db 不存在")
|
||||
conn = sqlite3.connect(str(p))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
tables = [r[0] for r in cur.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
|
||||
counts = {}
|
||||
for t in ("users", "rentals", "bike_history", "sessions"):
|
||||
if t in tables:
|
||||
counts[t] = cur.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
|
||||
cur.execute("PRAGMA integrity_check")
|
||||
integrity = cur.fetchone()[0]
|
||||
conn.close()
|
||||
if integrity != "ok":
|
||||
raise AssertionError(f"数据库完整性异常: {integrity}")
|
||||
return f"表 {len(tables)} 张, 行数: {counts}"
|
||||
|
||||
|
||||
check("users.db 完整性与核心表", db_check)
|
||||
|
||||
|
||||
def db_init_check():
|
||||
"""init_db() 应可重复执行(幂等)而不报错 —— 用临时库验证。"""
|
||||
import db, tempfile, os
|
||||
from pathlib import Path
|
||||
fd, tmp = tempfile.mkstemp(suffix=".db")
|
||||
os.close(fd)
|
||||
old = db.DB_PATH
|
||||
db.DB_PATH = Path(tmp)
|
||||
try:
|
||||
db.init_db()
|
||||
db.init_db() # 二次调用验证幂等
|
||||
return "init_db 在临时库上执行两次均成功(幂等)"
|
||||
finally:
|
||||
db.DB_PATH = old
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
check("init_db 幂等性 (临时库)", db_init_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("4) 模板与静态资源")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def templates_check():
|
||||
from pathlib import Path
|
||||
tdir = Path("templates")
|
||||
files = sorted(p.name for p in tdir.glob("*.html"))
|
||||
if not files:
|
||||
raise AssertionError("templates 目录为空")
|
||||
return f"{len(files)} 个模板: {', '.join(files)}"
|
||||
|
||||
|
||||
check("模板文件存在", templates_check)
|
||||
|
||||
|
||||
def static_check():
|
||||
from pathlib import Path
|
||||
sdir = Path("static")
|
||||
total = sum(1 for _ in sdir.rglob("*") if _.is_file())
|
||||
if total == 0:
|
||||
raise AssertionError("static 目录为空")
|
||||
return f"{total} 个静态文件"
|
||||
|
||||
|
||||
check("静态资源存在", static_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("5) 关键接口冒烟 (Flask test client, 不真正监听端口)")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def client():
|
||||
app_obj.config["TESTING"] = True
|
||||
return app_obj.test_client()
|
||||
|
||||
|
||||
c = client()
|
||||
|
||||
EXPECTED = {
|
||||
# (path): 说明。允许 200/3xx;404 属于页面/路由缺失
|
||||
"/": "主页(地图)",
|
||||
"/admin": "管理后台(未登录应跳转登录)",
|
||||
"/admin/login": "管理员登录页",
|
||||
"/analysis.html": "数据分析页",
|
||||
"/rental/email-return": "邮件还车页",
|
||||
"/ring_progress.html": "寻车进度页",
|
||||
}
|
||||
|
||||
|
||||
def page(path):
|
||||
def fn():
|
||||
r = c.get(path)
|
||||
if r.status_code in (200, 301, 302, 304):
|
||||
return f"{path} -> {r.status_code}"
|
||||
if r.status_code == 404:
|
||||
raise AssertionError(f"{path} -> 404 (页面/路由缺失)")
|
||||
raise AssertionError(f"{path} -> {r.status_code}")
|
||||
return fn
|
||||
|
||||
|
||||
for path, name in EXPECTED.items():
|
||||
check(f"页面 {name} {path}", page(path))
|
||||
|
||||
# API 类: 401/400 = 接口在且鉴权/校验正常; 404/500 = 有问题
|
||||
API_ALLOW = {200, 400, 401, 302, 301}
|
||||
APIS = [
|
||||
("/api/bike_history", "无参数应返回400"),
|
||||
("/api/analysis/overview", "分析总览"),
|
||||
("/api/analysis/heatmap", "热力图"),
|
||||
("/api/history/stats", "历史统计"),
|
||||
("/api/history/bikes", "历史车辆列表"),
|
||||
("/api/history/heatmap", "历史热力图"),
|
||||
("/api/history/all_trajectory", "全量轨迹"),
|
||||
]
|
||||
|
||||
|
||||
def api(path):
|
||||
def fn():
|
||||
r = c.get(path)
|
||||
if r.status_code in API_ALLOW:
|
||||
return f"{path} -> {r.status_code}"
|
||||
raise AssertionError(f"{path} -> {r.status_code}")
|
||||
return fn
|
||||
|
||||
|
||||
for path, desc in APIS:
|
||||
check(f"API {desc} {path}", api(path))
|
||||
|
||||
|
||||
def protected_api_check():
|
||||
"""未登录访问受保护接口应返回 401(或明确拒绝) 而不是 500/404"""
|
||||
paths = (
|
||||
"/api/auth/rental_settings", "/api/rental/status",
|
||||
"/api/share/active", "/api/auth/profile", "/api/order/status",
|
||||
)
|
||||
for path in paths:
|
||||
r = c.get(path)
|
||||
if r.status_code == 404:
|
||||
raise AssertionError(f"{path} -> 404, 接口不存在")
|
||||
if r.status_code >= 500:
|
||||
raise AssertionError(f"{path} -> {r.status_code}, 服务端错误")
|
||||
if r.status_code == 200:
|
||||
body = r.get_json(silent=True) or {}
|
||||
if body.get("rtn_code") not in (401, 403):
|
||||
raise AssertionError(
|
||||
f"{path} 未登录返回 200 且 rtn_code={body.get('rtn_code')}, 疑似未鉴权")
|
||||
return "受保护接口未登录时均正确拒绝(无 500/404/越权)"
|
||||
|
||||
|
||||
check("受保护接口鉴权兜底", protected_api_check)
|
||||
|
||||
|
||||
def login_flow_check():
|
||||
"""登录接口对错误凭据应返回明确失败而非 500"""
|
||||
r = c.post("/api/auth/login",
|
||||
json={"email": "smoke_nonexist@example.test", "password": "wrong"})
|
||||
if r.status_code >= 500:
|
||||
raise AssertionError(f"/api/auth/login -> {r.status_code}")
|
||||
body = r.get_json(silent=True) or {}
|
||||
if r.status_code == 200 and body.get("rtn_code") == 0:
|
||||
raise AssertionError("错误凭据竟然登录成功!")
|
||||
return f"/api/auth/login 错误凭据 -> {r.status_code} rtn_code={body.get('rtn_code')} (拒绝正常)"
|
||||
|
||||
|
||||
check("登录接口错误凭据处理", login_flow_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("冒烟测试结果汇总")
|
||||
print("=" * 60)
|
||||
print(f"通过: {len(PASS)} 失败: {len(FAIL)}")
|
||||
if FAIL:
|
||||
print("\n失败项:")
|
||||
for name, err in FAIL:
|
||||
print(f" - {name}: {err}")
|
||||
sys.exit(1)
|
||||
print("全部通过 ✅")
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""冒烟测试:验证应用可启动、路由无冲突、关键接口可响应。"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根
|
||||
|
||||
# 注意: app.py 导入时会重新包装 sys.stdout, 这里不能自己再包一层,
|
||||
# 否则旧包装器被 GC 时会关闭底层 buffer。编码由 PYTHONIOENCODING 控制。
|
||||
_ORIG_STDOUT = sys.stdout # 持有引用, 防止被 GC 后关闭底层流
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
PASS, FAIL = [], []
|
||||
|
||||
|
||||
def check(name, fn):
|
||||
try:
|
||||
detail = fn()
|
||||
PASS.append((name, detail))
|
||||
print(f" [PASS] {name}" + (f" — {detail}" if detail else ""))
|
||||
except Exception as e:
|
||||
FAIL.append((name, f"{type(e).__name__}: {e}"))
|
||||
print(f" [FAIL] {name} — {type(e).__name__}: {e}")
|
||||
|
||||
|
||||
print("=" * 60)
|
||||
print("1) 模块导入检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def import_app():
|
||||
import app as app_module
|
||||
return f"app 模块导入成功, 蓝图 {len(app_module.app.blueprints)} 个: {', '.join(app_module.app.blueprints)}"
|
||||
|
||||
|
||||
check("导入 app.py 及全部依赖 (db/wechat/timer/routes.*)", import_app)
|
||||
|
||||
|
||||
def import_side_modules():
|
||||
import rental_mail, email_utils, generate_icons # noqa: F401
|
||||
return "rental_mail / email_utils / generate_icons 导入成功"
|
||||
|
||||
|
||||
check("导入其余业务模块", import_side_modules)
|
||||
|
||||
app_obj = None
|
||||
try:
|
||||
import app as app_module
|
||||
app_obj = app_module.app
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("2) 路由冲突检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def route_conflicts():
|
||||
rules = defaultdict(list)
|
||||
for r in app_obj.url_map.iter_rules():
|
||||
if r.endpoint == "static":
|
||||
continue
|
||||
methods = sorted(m for m in r.methods if m not in ("HEAD", "OPTIONS"))
|
||||
for m in methods:
|
||||
rules[(m, r.rule)].append(r.endpoint)
|
||||
dupes = {k: v for k, v in rules.items() if len(v) > 1}
|
||||
if dupes:
|
||||
raise AssertionError(f"发现 {len(dupes)} 处路由冲突: {dupes}")
|
||||
return f"共 {len(rules)} 条 (method, path) 规则, 无重复注册"
|
||||
|
||||
|
||||
check("检查重复路由 (Flask 静默覆盖, 需显式检测)", route_conflicts)
|
||||
|
||||
|
||||
def route_summary():
|
||||
rules = sorted(r.rule for r in app_obj.url_map.iter_rules() if r.endpoint != "static")
|
||||
return f"{len(rules)} 条路由"
|
||||
|
||||
|
||||
check("路由注册成功", route_summary)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("3) 数据库连通性")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def db_check():
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
p = Path("users.db")
|
||||
if not p.exists():
|
||||
raise AssertionError("users.db 不存在")
|
||||
conn = sqlite3.connect(str(p))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
tables = [r[0] for r in cur.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
|
||||
counts = {}
|
||||
for t in ("users", "rentals", "bike_history", "sessions"):
|
||||
if t in tables:
|
||||
counts[t] = cur.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
|
||||
cur.execute("PRAGMA integrity_check")
|
||||
integrity = cur.fetchone()[0]
|
||||
conn.close()
|
||||
if integrity != "ok":
|
||||
raise AssertionError(f"数据库完整性异常: {integrity}")
|
||||
return f"表 {len(tables)} 张, 行数: {counts}"
|
||||
|
||||
|
||||
check("users.db 完整性与核心表", db_check)
|
||||
|
||||
|
||||
def db_init_check():
|
||||
"""init_db() 应可重复执行(幂等)而不报错 —— 用临时库验证。"""
|
||||
import db, tempfile, os
|
||||
from pathlib import Path
|
||||
fd, tmp = tempfile.mkstemp(suffix=".db")
|
||||
os.close(fd)
|
||||
old = db.DB_PATH
|
||||
db.DB_PATH = Path(tmp)
|
||||
try:
|
||||
db.init_db()
|
||||
db.init_db() # 二次调用验证幂等
|
||||
return "init_db 在临时库上执行两次均成功(幂等)"
|
||||
finally:
|
||||
db.DB_PATH = old
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
check("init_db 幂等性 (临时库)", db_init_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("4) 模板与静态资源")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def templates_check():
|
||||
from pathlib import Path
|
||||
tdir = Path("templates")
|
||||
files = sorted(p.name for p in tdir.glob("*.html"))
|
||||
if not files:
|
||||
raise AssertionError("templates 目录为空")
|
||||
return f"{len(files)} 个模板: {', '.join(files)}"
|
||||
|
||||
|
||||
check("模板文件存在", templates_check)
|
||||
|
||||
|
||||
def static_check():
|
||||
from pathlib import Path
|
||||
sdir = Path("static")
|
||||
total = sum(1 for _ in sdir.rglob("*") if _.is_file())
|
||||
if total == 0:
|
||||
raise AssertionError("static 目录为空")
|
||||
return f"{total} 个静态文件"
|
||||
|
||||
|
||||
check("静态资源存在", static_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("5) 关键接口冒烟 (Flask test client, 不真正监听端口)")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def client():
|
||||
app_obj.config["TESTING"] = True
|
||||
return app_obj.test_client()
|
||||
|
||||
|
||||
c = client()
|
||||
|
||||
EXPECTED = {
|
||||
# (path): 说明。允许 200/3xx;404 属于页面/路由缺失
|
||||
"/": "主页(地图)",
|
||||
"/admin": "管理后台(未登录应跳转登录)",
|
||||
"/admin/login": "管理员登录页",
|
||||
"/analysis.html": "数据分析页",
|
||||
"/rental/email-return": "邮件还车页",
|
||||
"/ring_progress.html": "寻车进度页",
|
||||
}
|
||||
|
||||
|
||||
def page(path):
|
||||
def fn():
|
||||
r = c.get(path)
|
||||
if r.status_code in (200, 301, 302, 304):
|
||||
return f"{path} -> {r.status_code}"
|
||||
if r.status_code == 404:
|
||||
raise AssertionError(f"{path} -> 404 (页面/路由缺失)")
|
||||
raise AssertionError(f"{path} -> {r.status_code}")
|
||||
return fn
|
||||
|
||||
|
||||
for path, name in EXPECTED.items():
|
||||
check(f"页面 {name} {path}", page(path))
|
||||
|
||||
# API 类: 401/400 = 接口在且鉴权/校验正常; 404/500 = 有问题
|
||||
API_ALLOW = {200, 400, 401, 302, 301}
|
||||
APIS = [
|
||||
("/api/bike_history", "无参数应返回400"),
|
||||
("/api/analysis/overview", "分析总览"),
|
||||
("/api/analysis/heatmap", "热力图"),
|
||||
("/api/history/stats", "历史统计"),
|
||||
("/api/history/bikes", "历史车辆列表"),
|
||||
("/api/history/heatmap", "历史热力图"),
|
||||
("/api/history/all_trajectory", "全量轨迹"),
|
||||
]
|
||||
|
||||
|
||||
def api(path):
|
||||
def fn():
|
||||
r = c.get(path)
|
||||
if r.status_code in API_ALLOW:
|
||||
return f"{path} -> {r.status_code}"
|
||||
raise AssertionError(f"{path} -> {r.status_code}")
|
||||
return fn
|
||||
|
||||
|
||||
for path, desc in APIS:
|
||||
check(f"API {desc} {path}", api(path))
|
||||
|
||||
|
||||
def protected_api_check():
|
||||
"""未登录访问受保护接口应返回 401(或明确拒绝) 而不是 500/404"""
|
||||
paths = (
|
||||
"/api/auth/rental_settings", "/api/rental/status",
|
||||
"/api/share/active", "/api/auth/profile", "/api/order/status",
|
||||
)
|
||||
for path in paths:
|
||||
r = c.get(path)
|
||||
if r.status_code == 404:
|
||||
raise AssertionError(f"{path} -> 404, 接口不存在")
|
||||
if r.status_code >= 500:
|
||||
raise AssertionError(f"{path} -> {r.status_code}, 服务端错误")
|
||||
if r.status_code == 200:
|
||||
body = r.get_json(silent=True) or {}
|
||||
if body.get("rtn_code") not in (401, 403):
|
||||
raise AssertionError(
|
||||
f"{path} 未登录返回 200 且 rtn_code={body.get('rtn_code')}, 疑似未鉴权")
|
||||
return "受保护接口未登录时均正确拒绝(无 500/404/越权)"
|
||||
|
||||
|
||||
check("受保护接口鉴权兜底", protected_api_check)
|
||||
|
||||
|
||||
def login_flow_check():
|
||||
"""登录接口对错误凭据应返回明确失败而非 500"""
|
||||
r = c.post("/api/auth/login",
|
||||
json={"email": "smoke_nonexist@example.test", "password": "wrong"})
|
||||
if r.status_code >= 500:
|
||||
raise AssertionError(f"/api/auth/login -> {r.status_code}")
|
||||
body = r.get_json(silent=True) or {}
|
||||
if r.status_code == 200 and body.get("rtn_code") == 0:
|
||||
raise AssertionError("错误凭据竟然登录成功!")
|
||||
return f"/api/auth/login 错误凭据 -> {r.status_code} rtn_code={body.get('rtn_code')} (拒绝正常)"
|
||||
|
||||
|
||||
check("登录接口错误凭据处理", login_flow_check)
|
||||
|
||||
print()
|
||||
print("=" * 60)
|
||||
print("冒烟测试结果汇总")
|
||||
print("=" * 60)
|
||||
print(f"通过: {len(PASS)} 失败: {len(FAIL)}")
|
||||
if FAIL:
|
||||
print("\n失败项:")
|
||||
for name, err in FAIL:
|
||||
print(f" - {name}: {err}")
|
||||
sys.exit(1)
|
||||
print("全部通过 ✅")
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
/* Keep the map clear. Secondary tools open only on demand, in the original acrylic material. */
|
||||
[hidden] { display:none!important; }
|
||||
.map-tools-toggle,.discovery-toolbar,.place-results,.legend {
|
||||
background:var(--ui-header-acrylic)!important;
|
||||
border:1px solid var(--ui-line-strong);
|
||||
-webkit-backdrop-filter:blur(24px) saturate(1.4);
|
||||
backdrop-filter:blur(24px) saturate(1.4);
|
||||
box-shadow:var(--ui-shadow-sm);
|
||||
}
|
||||
.map-tools-toggle { position:absolute; z-index:130; top:12px; left:12px; min-height:44px; padding:10px 16px; border-radius:14px; color:var(--ui-ink); font:inherit; font-size:13px; cursor:pointer; }
|
||||
#map-filter-indicator { color:var(--ui-muted); font-size:11px; }
|
||||
.discovery-toolbar { position:absolute; z-index:155; bottom:12px; left:12px; width:min(360px,calc(100% - 24px)); max-height:min(68%,560px); padding:14px; border-radius:20px; overflow-y:auto; overscroll-behavior:contain; color:var(--ui-ink); font-size:13px; }
|
||||
.discovery-heading,.nearby-heading { display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:8px; }
|
||||
.discovery-heading h2 { font-size:17px; letter-spacing:-.3px; font-weight:650; }
|
||||
.discovery-toolbar button,.discovery-toolbar summary,.discovery-toolbar select,.discovery-toolbar input { font:inherit; }
|
||||
.discovery-toolbar button,.discovery-actions summary,.location-status button,.theme-options button,.order-filters button,.order-load-more,.sub-rule button,.preview-settings button {
|
||||
min-height:44px; border:1px solid var(--ui-line); border-radius:10px; padding:8px 12px;
|
||||
background:var(--ui-acrylic-soft); color:var(--ui-ink); cursor:pointer;
|
||||
}
|
||||
.discovery-heading button,.nearby-heading button { border:0; background:transparent; min-width:44px; padding:6px; color:var(--ui-muted); }
|
||||
.place-search-row { display:flex; align-items:center; gap:6px; }
|
||||
.place-search-row input { width:100%; min-width:0; min-height:44px; border:1px solid var(--ui-line-strong); border-radius:11px; padding:10px 12px; background:var(--ui-acrylic-soft); color:var(--ui-ink); font-size:14px; }
|
||||
.place-results { position:relative; margin-top:6px; max-height:150px; overflow-y:auto; border-radius:12px; }
|
||||
.place-results button { width:100%; display:flex; justify-content:space-between; align-items:center; border:0; border-radius:0; border-bottom:1px solid var(--ui-line); background:transparent; text-align:left; gap:12px; }
|
||||
.place-results small,.discovery-muted { color:var(--ui-muted); font-size:12px; }
|
||||
.discovery-actions { display:flex; align-items:flex-start; gap:8px; margin-top:8px; }
|
||||
.discovery-actions > button { flex:1; }
|
||||
.discovery-actions details { flex:1; }
|
||||
.discovery-actions details[open] { flex-basis:100%; }
|
||||
.discovery-actions:has(details[open]) { flex-wrap:wrap; }
|
||||
.discovery-actions summary { list-style:none; display:flex; justify-content:center; align-items:center; }
|
||||
.discovery-actions summary::-webkit-details-marker { display:none; }
|
||||
.discovery-filter-fields { display:grid; grid-template-columns:1fr 1fr; gap:10px; padding:12px 2px 4px; }
|
||||
.discovery-filter-fields label { display:flex; flex-direction:column; gap:6px; color:var(--ui-muted); font-size:12px; }
|
||||
.discovery-filter-fields .checkbox-label { flex-direction:row; align-items:center; grid-column:1/-1; color:var(--ui-ink); }
|
||||
.discovery-filter-fields input[type=checkbox] { width:18px; height:18px; }
|
||||
.discovery-filter-fields select,.nearby-sort select,.order-filters input,.order-filters select { min-height:44px; min-width:0; width:100%; border:1px solid var(--ui-line); border-radius:9px; padding:8px; background:var(--ui-acrylic-soft); color:var(--ui-ink); }
|
||||
.discovery-origin { width:100%; min-height:32px!important; padding:8px 0!important; border:0!important; background:transparent!important; color:var(--ui-muted)!important; font-size:12px!important; text-align:left; }
|
||||
.discovery-places { border-top:1px solid var(--ui-line); padding-top:4px; }
|
||||
.discovery-places > summary { min-height:36px; color:var(--ui-muted); cursor:pointer; line-height:36px; font-size:12px; }
|
||||
.favorite-places { display:flex; flex-wrap:wrap; gap:6px; padding:4px 0 8px; }
|
||||
.favorite-place { display:flex; border:1px solid var(--ui-line); border-radius:9px; overflow:hidden; }
|
||||
.favorite-place button { border:0; border-radius:0; background:transparent; min-height:36px; padding:6px 9px; }
|
||||
.favorite-place button:last-child { min-width:36px; padding:5px; color:var(--ui-muted); }
|
||||
#favorite-save { min-height:36px; font-size:12px; margin-bottom:6px; }
|
||||
.nearby-panel { display:flex; flex-direction:column; position:static; margin-top:8px; padding-top:10px; border-top:1px solid var(--ui-line); background:transparent; }
|
||||
.nearby-heading { margin-bottom:0; }
|
||||
.nearby-heading h2 { font-size:14px; font-weight:600; }
|
||||
.nearby-summary { color:var(--ui-muted); font-size:11px; line-height:1.6; padding:2px 0 8px; }
|
||||
.nearby-sort { display:flex; align-items:center; gap:10px; padding-bottom:6px; color:var(--ui-muted); font-size:12px; }
|
||||
.nearby-sort select { flex:1; width:auto; }
|
||||
.nearby-list { overflow-y:auto; max-height:210px; overscroll-behavior:contain; }
|
||||
.nearby-row { display:flex; justify-content:space-between; gap:12px; width:100%; padding:11px 0!important; border-width:0 0 1px!important; border-radius:0!important; background:transparent!important; text-align:left; }
|
||||
.nearby-row strong { font-size:14px; font-variant-numeric:tabular-nums; }
|
||||
.nearby-row-meta { display:block; color:var(--ui-muted); font-size:12px; margin-top:4px; }
|
||||
.nearby-row-end { display:flex; flex-direction:column; align-items:flex-end; gap:4px; color:var(--ui-muted); font-size:12px; white-space:nowrap; }
|
||||
.vehicle-status { color:var(--ui-ink); font-weight:600; }
|
||||
.vehicle-status.available { color:var(--discovery-available,#237947); }
|
||||
.vehicle-status.lowbattery,.vehicle-status.locked { color:var(--discovery-warning,#9a5a08); }
|
||||
.discovery-empty { padding:12px 0; color:var(--ui-muted); line-height:1.7; }
|
||||
.discovery-empty strong { color:var(--ui-ink); }
|
||||
.discovery-empty button { margin-top:8px; }
|
||||
.location-status { position:static; padding-top:8px; border-top:1px solid var(--ui-line); color:var(--ui-muted); font-size:12px; line-height:1.6; }
|
||||
.location-status-actions { display:flex; gap:8px; margin-top:6px; }
|
||||
.location-status-actions button { min-height:36px; padding:6px 9px; font-size:12px; }
|
||||
.legend { top:12px!important; right:12px!important; bottom:auto!important; }
|
||||
.legend summary { cursor:pointer; min-height:28px; line-height:28px; font-size:12px; color:var(--ui-muted); }
|
||||
.legend:not([open]) .legend-item { display:none; }
|
||||
body:has(#discovery-drawer:not([hidden])) .locate-fab { visibility:hidden; }
|
||||
.header-school-row { display:flex; align-items:center; gap:7px; }
|
||||
.preview-tag { font-size:10px; color:var(--ui-muted); border:1px solid var(--ui-line-strong); border-radius:5px; padding:1px 4px; line-height:1.3; }
|
||||
.preview-entry { display:flex; justify-content:center; gap:10px; align-items:center; color:var(--ui-muted); margin:12px 0 2px; font-size:12px; }
|
||||
.preview-entry button { padding:5px 2px; background:transparent; color:inherit; border:0; cursor:pointer; font:inherit; min-height:32px; }
|
||||
.preview-settings { padding:14px 0; }
|
||||
.preview-settings > div { display:flex; gap:8px; margin-top:8px; }
|
||||
.preview-settings button { flex:1; font:inherit; font-size:13px; }
|
||||
.theme-options { display:flex; gap:8px; padding:10px 0 14px; }
|
||||
.theme-options button { flex:1; font:inherit; font-size:13px; }
|
||||
.theme-options button[aria-pressed=true] { background:var(--ui-solid); color:var(--ui-on-solid); }
|
||||
.order-filters { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin:10px 0 14px; }
|
||||
.order-filters label { display:flex; flex-direction:column; gap:6px; color:var(--ui-muted); font-size:12px; min-width:0; }
|
||||
.order-filters input,.order-filters select { font:inherit; }
|
||||
.order-filter-actions { display:flex; gap:8px; grid-column:1/-1; }
|
||||
.order-load-more { margin-top:12px; }
|
||||
.sub-rule { border-bottom:1px solid var(--ui-line); padding:12px 0; font-size:13px; line-height:1.7; }
|
||||
.sub-rule-head { display:flex; justify-content:space-between; align-items:flex-start; gap:10px; }
|
||||
.sub-rule-meta,.sub-rule-result { color:var(--ui-muted); font-size:12px; margin-top:4px; }
|
||||
.sub-rule-actions { display:flex; gap:6px; flex-wrap:wrap; margin-top:8px; }
|
||||
.sub-rule-actions button { min-height:40px; padding:6px 12px; font:inherit; }
|
||||
.sub-rule-actions .danger { color:var(--danger); }
|
||||
.sub-editor-heading { display:flex; justify-content:space-between; align-items:center; margin-bottom:10px; }
|
||||
.sub-editor-heading button { min-height:40px; padding:6px 10px; border:1px solid var(--ui-line); border-radius:8px; background:var(--ui-acrylic-soft); color:var(--ui-ink); }
|
||||
.settings-page { background:color-mix(in srgb,var(--ui-canvas) 82%,transparent)!important; -webkit-backdrop-filter:blur(32px) saturate(1.3); backdrop-filter:blur(32px) saturate(1.3); }
|
||||
.settings-page .settings-group { background:var(--ui-acrylic-soft)!important; }
|
||||
.bike-card:not(.show) { visibility:hidden; pointer-events:none; }
|
||||
.bike-card.show { visibility:visible; }
|
||||
.battery-unknown .battery-unit { display:none; }
|
||||
.auth-modal:not(.show),.qr-modal:not(.show),.unlock-confirm-modal:not(.show),.return-confirm-modal:not(.show),.token-expired-modal:not(.show),.lost-modal:not(.show),.return-modal:not(.show),.bell-modal:not(.show) { visibility:hidden; }
|
||||
html,body { overflow:clip; }
|
||||
body { animation:none!important; }
|
||||
.locate-btn.locate-fab { min-width:44px; min-height:44px; }
|
||||
.auth-close,.bike-card-close,.qr-close { min-width:44px; min-height:44px; }
|
||||
.sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip-path:inset(50%); white-space:nowrap; border:0; }
|
||||
button:disabled { cursor:wait; opacity:.65; }
|
||||
@media(max-width:768px) {
|
||||
.map-tools-toggle { top:10px; left:10px; padding:9px 14px; border-radius:13px; }
|
||||
.legend { top:10px!important; right:10px!important; padding:6px 10px!important; }
|
||||
.discovery-toolbar { left:10px; bottom:10px; width:calc(100% - 20px); max-height:64%; padding:12px; }
|
||||
.locate-btn.locate-fab { width:44px; height:44px; padding:0; border-radius:50%; bottom:94px; right:12px; }
|
||||
.locate-fab-label { display:none!important; }
|
||||
.nearby-list { max-height:180px; }
|
||||
}
|
||||
@media(prefers-reduced-motion:reduce) { .discovery-toolbar { transition:none; } }
|
||||
|
||||
.discovery-toolbar[data-view=list] > .place-search-wrap,
|
||||
.discovery-toolbar[data-view=list] > .discovery-actions,
|
||||
.discovery-toolbar[data-view=list] > .discovery-origin,
|
||||
.discovery-toolbar[data-view=list] > .discovery-places,
|
||||
.discovery-toolbar[data-view=list] > .location-status { display:none!important; }
|
||||
.discovery-toolbar[data-view=list] .nearby-heading h2 { display:none; }
|
||||
.discovery-toolbar[data-view=list] .nearby-panel { margin-top:0; padding-top:0; border-top:0; }
|
||||
.discovery-toolbar[data-view=list] .nearby-heading { justify-content:flex-start; }
|
||||
.discovery-toolbar[data-view=list] #nearby-close { min-height:32px; padding:3px 0; color:var(--ui-muted); font-size:12px; }
|
||||
+2898
-2706
File diff suppressed because it is too large
Load Diff
@@ -1,114 +0,0 @@
|
||||
/* Explicit light / dark modes, selected before first paint. */
|
||||
:root[data-theme="light"] {
|
||||
--bg-primary: #ffffff;
|
||||
--bg-secondary: #f5f5f7;
|
||||
--bg-card: #ffffff;
|
||||
--text-primary: #1d1d1f;
|
||||
--text-secondary: #6e6e73;
|
||||
--text-tertiary: #86868b;
|
||||
--border-color: #e5e5ea;
|
||||
--accent-color: #0071e3;
|
||||
--accent-hover: #0077ed;
|
||||
--accent-soft: rgba(0, 113, 227, 0.10);
|
||||
--success: #34c759;
|
||||
--success-press: #2fb950;
|
||||
--warning: #ff9f0a;
|
||||
--danger: #ff3b30;
|
||||
--error-color: #ff3b30;
|
||||
--overlay: rgba(0, 0, 0, 0.45);
|
||||
--shadow-sm: 0 2px 8px rgba(0,0,0,0.08);
|
||||
--shadow-md: 0 4px 20px rgba(0,0,0,0.12);
|
||||
--shadow-lg: 0 8px 32px rgba(0,0,0,0.16);
|
||||
--shadow-up: 0 -4px 20px rgba(0,0,0,0.08);
|
||||
--radius-sm: 8px;
|
||||
--radius-md: 12px;
|
||||
--radius-lg: 16px;
|
||||
--radius-xl: 20px;
|
||||
--transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
--ease-spring: cubic-bezier(0.34, 1.3, 0.5, 1);
|
||||
--ui-canvas: #f6f6f4;
|
||||
--ui-surface: #fbfbfa;
|
||||
--ui-surface-raised: #f0f0ee;
|
||||
--ui-ink: #171719;
|
||||
--ui-muted: #68686f;
|
||||
--ui-faint: #929299;
|
||||
--ui-line: rgba(23, 23, 25, .09);
|
||||
--ui-line-strong: rgba(23, 23, 25, .15);
|
||||
--ui-solid: #1c1c1f;
|
||||
--ui-on-solid: #f8f8f6;
|
||||
--ui-acrylic: color-mix(in srgb, var(--ui-surface) 68%, transparent);
|
||||
--ui-acrylic-soft: color-mix(in srgb, var(--ui-surface) 46%, transparent);
|
||||
--ui-header-acrylic: rgba(251, 251, 250, .64);
|
||||
--ui-overlay: rgba(12, 12, 14, .52);
|
||||
--ui-focus: rgba(23, 23, 25, .24);
|
||||
--ui-shadow-sm: 0 1px 2px rgba(18, 18, 20, .04), 0 8px 24px rgba(18, 18, 20, .05);
|
||||
--ui-shadow-md: 0 18px 52px rgba(18, 18, 20, .11);
|
||||
--ui-shadow-lg: 0 32px 90px rgba(18, 18, 20, .16);
|
||||
--ui-r-sm: 8px;
|
||||
--ui-r-md: 12px;
|
||||
--ui-r-lg: 16px;
|
||||
--ui-r-xl: 20px;
|
||||
--ui-r-2xl: 24px;
|
||||
--ui-ease: cubic-bezier(.16, 1, .3, 1);
|
||||
--ui-fast: 160ms;
|
||||
--ui-normal: 280ms;
|
||||
--discovery-available: #237947;
|
||||
--discovery-warning: #915807;
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--bg-primary: #000000;
|
||||
--bg-secondary: #1c1c1e;
|
||||
--bg-card: #2c2c2e;
|
||||
--text-primary: #f5f5f7;
|
||||
--text-secondary: #b0b0b7;
|
||||
--text-tertiary: #636366;
|
||||
--border-color: #38383a;
|
||||
--accent-color: #0a84ff;
|
||||
--accent-hover: #409cff;
|
||||
--accent-soft: rgba(10, 132, 255, 0.16);
|
||||
--success: #30d158;
|
||||
--success-press: #28bd4d;
|
||||
--warning: #ff9f0a;
|
||||
--danger: #ff453a;
|
||||
--error-color: #ff453a;
|
||||
--overlay: rgba(0, 0, 0, 0.6);
|
||||
--shadow-sm: 0 2px 8px rgba(0,0,0,0.3);
|
||||
--shadow-md: 0 4px 20px rgba(0,0,0,0.4);
|
||||
--shadow-lg: 0 8px 32px rgba(0,0,0,0.5);
|
||||
--shadow-up: 0 -4px 20px rgba(0,0,0,0.4);
|
||||
--radius-sm: 8px;
|
||||
--radius-md: 12px;
|
||||
--radius-lg: 16px;
|
||||
--radius-xl: 20px;
|
||||
--transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
--ease-spring: cubic-bezier(0.34, 1.3, 0.5, 1);
|
||||
--ui-canvas: #101011;
|
||||
--ui-surface: #18181a;
|
||||
--ui-surface-raised: #222225;
|
||||
--ui-ink: #f1f1ef;
|
||||
--ui-muted: #b0b0b7;
|
||||
--ui-faint: #77777f;
|
||||
--ui-line: rgba(241, 241, 239, .09);
|
||||
--ui-line-strong: rgba(241, 241, 239, .16);
|
||||
--ui-solid: #eeeeec;
|
||||
--ui-on-solid: #151517;
|
||||
--ui-acrylic: color-mix(in srgb, var(--ui-surface) 68%, transparent);
|
||||
--ui-acrylic-soft: color-mix(in srgb, var(--ui-surface) 46%, transparent);
|
||||
--ui-header-acrylic: rgba(238, 238, 236, .07);
|
||||
--ui-overlay: rgba(3, 3, 4, .68);
|
||||
--ui-focus: rgba(241, 241, 239, .28);
|
||||
--ui-shadow-sm: 0 1px 2px rgba(2, 2, 3, .22), 0 10px 28px rgba(2, 2, 3, .18);
|
||||
--ui-shadow-md: 0 20px 56px rgba(2, 2, 3, .32);
|
||||
--ui-shadow-lg: 0 36px 100px rgba(2, 2, 3, .46);
|
||||
--ui-r-sm: 8px;
|
||||
--ui-r-md: 12px;
|
||||
--ui-r-lg: 16px;
|
||||
--ui-r-xl: 20px;
|
||||
--ui-r-2xl: 24px;
|
||||
--ui-ease: cubic-bezier(.16, 1, .3, 1);
|
||||
--ui-fast: 160ms;
|
||||
--ui-normal: 280ms;
|
||||
--discovery-available: #78d99e;
|
||||
--discovery-warning: #f3c57b;
|
||||
}
|
||||
:root[data-theme="dark"] .preview-notice { background:#352d1d; color:#f3cf85; }
|
||||
@@ -1,32 +0,0 @@
|
||||
/* Bounded requests; mutation requests are never retried automatically. */
|
||||
(function () {
|
||||
'use strict';
|
||||
const pending = new Map();
|
||||
async function request(url, options = {}) {
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
if (options.signal?.aborted) controller.abort();
|
||||
else options.signal?.addEventListener('abort', abort, { once: true });
|
||||
const timer = setTimeout(abort, options.timeout || 15000);
|
||||
try {
|
||||
return await fetch(url, { ...options, signal: controller.signal });
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') throw new Error('请求超时或已取消,请刷新状态后重试');
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
options.signal?.removeEventListener('abort', abort);
|
||||
}
|
||||
}
|
||||
async function run(key, button, action) {
|
||||
if (pending.has(key)) return pending.get(key);
|
||||
if (button) { button.disabled = true; button.setAttribute('aria-busy', 'true'); }
|
||||
const task = Promise.resolve().then(action).finally(() => {
|
||||
pending.delete(key);
|
||||
if (button) { button.disabled = false; button.removeAttribute('aria-busy'); }
|
||||
});
|
||||
pending.set(key, task);
|
||||
return task;
|
||||
}
|
||||
window.AppAPI = { fetch: request, run };
|
||||
})();
|
||||
@@ -1,41 +0,0 @@
|
||||
/* Shared vehicle rules. Unknown battery data is never invented. */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
function electric(bike) {
|
||||
const raw = bike?.electric_quantity ?? bike?.electricQuantity ?? bike?.electric;
|
||||
if (raw === null || raw === undefined || typeof raw === 'boolean' || String(raw).trim() === '') return null;
|
||||
const n = Number(raw);
|
||||
return Number.isFinite(n) && n >= 0 && n <= 100 ? n : null;
|
||||
}
|
||||
function state(bike) {
|
||||
const s = Number(bike?.state), occupied = Number(bike?.status), e = electric(bike);
|
||||
if (s === 1 && occupied === 1) return 'inuse';
|
||||
if (s === 4) return 'locked';
|
||||
if (s === 2) return 'reserved';
|
||||
if (s === 10 || (e !== null && e < 20)) return 'lowbattery';
|
||||
if (s === 1 && occupied === 0) return 'available';
|
||||
return 'unknown';
|
||||
}
|
||||
const labels = { available: '可用', inuse: '使用中', locked: '欠压', reserved: '损坏', lowbattery: '低电量', unknown: '状态未知' };
|
||||
function kind(bike) {
|
||||
const code = String(bike?.code ?? bike?.bike_code ?? '');
|
||||
if (/^\d{8}$/.test(code)) return 'red';
|
||||
return Number(code.slice(0, 3)) >= 511 ? 'big' : 'small';
|
||||
}
|
||||
function validCode(code) { return /^(?:\d{5}|\d{8})$/.test(String(code)); }
|
||||
function distance(a, b) {
|
||||
if (!a || !b || ![a.lat, a.lng, b.lat, b.lng].every(Number.isFinite)) return null;
|
||||
const rad = Math.PI / 180, dlat = (b.lat - a.lat) * rad, dlng = (b.lng - a.lng) * rad;
|
||||
const h = Math.sin(dlat / 2) ** 2 + Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dlng / 2) ** 2;
|
||||
return 12742000 * Math.asin(Math.sqrt(Math.min(1, h)));
|
||||
}
|
||||
function matches(bike, filters) {
|
||||
const e = electric(bike);
|
||||
return (!filters.onlyAvailable || state(bike) === 'available') &&
|
||||
(!filters.kind || filters.kind === 'all' || kind(bike) === filters.kind) &&
|
||||
(!(filters.minElectric > 0) || (e !== null && e >= filters.minElectric));
|
||||
}
|
||||
const api = { electric, state, labels, kind, validCode, distance, matches };
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
||||
root.BikeData = api;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,54 +0,0 @@
|
||||
// ========== 启动 ==========
|
||||
// 启动时检查登录状态,然后检查租车
|
||||
checkAuthStatus().then(() => {
|
||||
if (authToken && typeof SettingsPages !== "undefined") SettingsPages.restore();
|
||||
checkRentalStatus();
|
||||
if (authToken) shareAfterLogin();
|
||||
});
|
||||
|
||||
// 未登录:全屏登录门覆盖地图(后端 /api/map 同样有登录门禁)
|
||||
if (!authToken) showLoginGate();
|
||||
|
||||
document.addEventListener("DOMContentLoaded", initMap);
|
||||
window.addEventListener("xbniu-map-ready", initMap);
|
||||
document.getElementById("scan-input").addEventListener("keydown", e => {
|
||||
if (e.key === "Enter") scanCode();
|
||||
});
|
||||
// Refresh at the shared snapshot's expiry, not 60 seconds after an old cache hit.
|
||||
setInterval(updateMapFreshnessBadge, 1000);
|
||||
|
||||
// 进行中订单:每 2 分钟主动刷新一次(与上游对账 + 重算剩余时长/预计还车)
|
||||
setInterval(async () => {
|
||||
if (!authToken || document.visibilityState !== "visible") return;
|
||||
if (!currentOrder || Number(currentOrder.status) !== 2) return;
|
||||
try {
|
||||
await syncWechatOrder(); // 上游可能已被还车/换单
|
||||
checkOrderStatus(); // 刷新横幅状态
|
||||
if (currentOrder && currentOrder.order_id) {
|
||||
fetchOrderCountdown(currentOrder.order_id); // 重算剩余 + 预计还车
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[订单2分钟刷新] 失败:", e);
|
||||
}
|
||||
}, 120000);
|
||||
|
||||
// 页面重新可见时检查租车状态
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
if (authToken && map) loadMapData(currentType, false, true);
|
||||
checkAuthStatus().then(async () => {
|
||||
// 从微信或其他端回到页面时,先主动对账,再刷新本地横幅。
|
||||
if (authToken) await syncWechatOrder();
|
||||
// 如果有租车计时横幅,同步服务端时间
|
||||
const rentalBar = document.getElementById("rental-bar");
|
||||
console.log("[visibilitychange] 同步服务端用车状态");
|
||||
checkRentalStatus();
|
||||
// 如果有订单横幅且在进行中,同步倒计时
|
||||
const orderBanner = document.getElementById("order-banner");
|
||||
if (orderBanner && orderBanner.classList.contains("show") && currentOrder && currentOrder.status === 2) {
|
||||
console.log("[visibilitychange] order-banner 进行中,同步倒计时");
|
||||
fetchOrderCountdown(currentOrder.order_id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,198 +0,0 @@
|
||||
/* Find vehicles by location, availability, battery and kind. Coordinates here are BD09. */
|
||||
(function () {
|
||||
'use strict';
|
||||
const storageKey = 'xbniu_discovery', favoriteKey = 'xbniu_places';
|
||||
let filters = { onlyAvailable: false, minElectric: 0, kind: 'all', radius: 500, sort: 'distance' };
|
||||
let favorites = [], locations = [], origin = null, originName = '', initialized = false, renderFrame = null;
|
||||
const byId = id => document.getElementById(id);
|
||||
const escape = text => String(text ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(storageKey) || '{}');
|
||||
filters.onlyAvailable = saved.onlyAvailable === true;
|
||||
if ([0,20,40,60,80].includes(saved.minElectric)) filters.minElectric = saved.minElectric;
|
||||
if (['all','small','big','red'].includes(saved.kind)) filters.kind = saved.kind;
|
||||
if ([200,500,1000,0].includes(saved.radius)) filters.radius = saved.radius;
|
||||
if (['distance','electric'].includes(saved.sort)) filters.sort = saved.sort;
|
||||
const stored = JSON.parse(localStorage.getItem(favoriteKey) || '[]');
|
||||
if (Array.isArray(stored)) favorites = stored.filter(p => p && typeof p.name === 'string' && Number.isFinite(p.lat) && Number.isFinite(p.lng) && Math.abs(p.lat) <= 90 && Math.abs(p.lng) <= 180).slice(0, 12);
|
||||
} catch (_) {}
|
||||
function center() {
|
||||
if (origin) return origin;
|
||||
if (autoLocationMarker) return autoLocationMarker.getPosition();
|
||||
return map?.getCenter() || null;
|
||||
}
|
||||
function items(availableOnly = false) {
|
||||
const point = center();
|
||||
return Object.values(markersData).filter(b => BikeData.matches(b, { ...filters, onlyAvailable: availableOnly || filters.onlyAvailable }))
|
||||
.map(b => ({ bike: b, id: BikeClusters.bikeId(b), distance: BikeData.distance(point, offsetCoord(b.latitude, b.longitude)), electric: BikeData.electric(b) }))
|
||||
.filter(row => !filters.radius || row.distance === null || row.distance <= filters.radius)
|
||||
.sort((a, b) => filters.sort === 'electric'
|
||||
? (b.electric ?? -1) - (a.electric ?? -1) || (a.distance ?? Infinity) - (b.distance ?? Infinity)
|
||||
: (a.distance ?? Infinity) - (b.distance ?? Infinity) || (b.electric ?? -1) - (a.electric ?? -1));
|
||||
}
|
||||
function visibleBikes(bikes) { return bikes.filter(b => BikeData.matches(b, filters)); }
|
||||
function persist() { try { localStorage.setItem(storageKey, JSON.stringify(filters)); } catch (_) {} }
|
||||
function render() {
|
||||
if (!initialized) return;
|
||||
const rows = items();
|
||||
byId('nearby-count').textContent = rows.length;
|
||||
byId('map-filter-indicator').hidden = !(filters.onlyAvailable || filters.minElectric || filters.kind !== 'all');
|
||||
byId('discovery-origin').textContent = originName || (autoLocationMarker ? '以我的位置查找' : '以地图中心查找');
|
||||
byId('nearby-summary').textContent = `${originName || (autoLocationMarker ? '我的位置' : '地图中心')} · ${filters.radius ? filters.radius + ' 米内' : '全部范围'} · ${rows.length} 辆,直线距离`;
|
||||
const batteryText = e => e === null ? '电量未知' : `${Math.round(e)}% 电量`;
|
||||
byId('nearby-list').innerHTML = rows.length ? rows.slice(0, 100).map(row => {
|
||||
const s = BikeData.state(row.bike), k = { small:'小车', big:'大车', red:'红车' }[BikeData.kind(row.bike)];
|
||||
const distance = row.distance === null ? '距离待确认' : row.distance < 1000 ? `${Math.round(row.distance)} 米` : `${(row.distance / 1000).toFixed(1)} 公里`;
|
||||
return `<button class="nearby-row" data-bike-id="${escape(row.id)}"><span><strong>#${escape(row.bike.code)}</strong><span class="nearby-row-meta">${k} · ${batteryText(row.electric)}</span></span><span class="nearby-row-end"><span class="vehicle-status ${s}">${BikeData.labels[s]}</span><span>${distance}</span></span></button>`;
|
||||
}).join('') : '<div class="discovery-empty"><strong>这里暂时没有符合条件的车辆</strong><p>可以扩大范围、降低电量要求或切换车型。</p><button type="button" data-relax>放宽筛选条件</button></div>';
|
||||
if (rows.length > 100) byId('nearby-summary').textContent += ',先展示前 100 辆,请缩小范围';
|
||||
}
|
||||
function refresh() {
|
||||
if (!initialized) return;
|
||||
persist();
|
||||
rebuildMarkersForZoom();
|
||||
render();
|
||||
}
|
||||
function relax() {
|
||||
filters = { onlyAvailable: true, minElectric: 0, kind: 'all', radius: 0, sort: 'distance' };
|
||||
fillControls(); refresh();
|
||||
showToast('已扩大至全部范围,保留可用车辆');
|
||||
}
|
||||
function fillControls() {
|
||||
byId('filter-available').checked = filters.onlyAvailable;
|
||||
byId('filter-electric').value = filters.minElectric;
|
||||
byId('filter-kind').value = filters.kind;
|
||||
byId('filter-radius').value = filters.radius;
|
||||
byId('nearby-sort').value = filters.sort;
|
||||
}
|
||||
function openTools() {
|
||||
byId('discovery-drawer').hidden = false;
|
||||
byId('map-tools-toggle').setAttribute('aria-expanded', 'true');
|
||||
render();
|
||||
}
|
||||
function closeTools(restoreFocus = true) {
|
||||
byId('discovery-drawer').hidden = true;
|
||||
byId('discovery-drawer').dataset.view = 'tools';
|
||||
byId('discovery-title').textContent = '找车';
|
||||
byId('nearby-panel').hidden = true;
|
||||
byId('nearby-toggle').setAttribute('aria-expanded', 'false');
|
||||
byId('map-tools-toggle').setAttribute('aria-expanded', 'false');
|
||||
byId('discovery-filters').open = false;
|
||||
byId('place-results').hidden = true;
|
||||
if (restoreFocus) byId('map-tools-toggle').focus({preventScroll:true});
|
||||
}
|
||||
function showList(open = true) {
|
||||
if (open) { openTools(); byId('discovery-filters').open = false; }
|
||||
byId('nearby-panel').hidden = !open;
|
||||
byId('discovery-drawer').dataset.view = open ? 'list' : 'tools';
|
||||
byId('discovery-title').textContent = open ? '附近车辆' : '找车';
|
||||
byId('nearby-toggle').setAttribute('aria-expanded', String(open));
|
||||
if (open) render();
|
||||
}
|
||||
function choosePlace(point, name) {
|
||||
if (!map) { showToast('地图正在加载,请稍后重试'); return; }
|
||||
origin = { lat: point.lat, lng: point.lng }; originName = name;
|
||||
map.panTo(new BMapGL.Point(point.lng, point.lat));
|
||||
byId('place-search').value = name;
|
||||
byId('place-results').hidden = true;
|
||||
render(); showList();
|
||||
}
|
||||
function searchPlaces() {
|
||||
const q = byId('place-search').value.trim().toLocaleLowerCase();
|
||||
const selected = locations.filter(p => !q || p.name.toLocaleLowerCase().includes(q)).slice(0, 8);
|
||||
byId('place-results').hidden = false;
|
||||
byId('place-results').innerHTML = selected.length ? selected.map(p => `<button type="button" data-place-id="${p.id}"><span>${escape(p.name)}</span><small>${p.kind === 'parking' ? '停车点' : '校园地点'}</small></button>`).join('') : '<p class="discovery-empty">未找到地点,可拖动地图后收藏当前位置。</p>';
|
||||
}
|
||||
function renderFavorites() {
|
||||
byId('favorite-places').innerHTML = favorites.length ? favorites.map((p, index) => `<span class="favorite-place"><button type="button" data-favorite="${index}">${escape(p.name)}</button><button type="button" data-remove-favorite="${index}" aria-label="删除常用地点 ${escape(p.name)}">×</button></span>`).join('') : '<span class="discovery-muted">常用地点保存在这台设备</span>';
|
||||
}
|
||||
function savePlace() {
|
||||
const p = origin || map?.getCenter();
|
||||
if (!p) { showToast('地图加载后可收藏地点'); return; }
|
||||
const name = byId('place-search').value.trim().slice(0, 24) || originName || `地图位置 ${favorites.length + 1}`;
|
||||
if (favorites.length >= 12) { showToast('最多收藏 12 个地点,请先移除不需要的'); return; }
|
||||
if (favorites.some(f => f.name === name)) { showToast('已收藏同名地点'); return; }
|
||||
favorites.push({ name, lat: p.lat, lng: p.lng });
|
||||
try { localStorage.setItem(favoriteKey, JSON.stringify(favorites)); } catch (_) { showToast('浏览器未允许保存常用地点'); return; }
|
||||
renderFavorites(); showToast('已收藏当前查找地点');
|
||||
}
|
||||
function locationStatus(message, retry = false) {
|
||||
const box = byId('location-status'); if (!box) return;
|
||||
box.hidden = false;
|
||||
byId('location-message').textContent = message;
|
||||
byId('location-retry').hidden = !retry;
|
||||
}
|
||||
async function nearest(point, name = "我的位置") {
|
||||
if (!authToken) { showLoginGate(); return; }
|
||||
if (point) { origin = { lat: point.lat, lng: point.lng }; originName = name; }
|
||||
const candidates = items(true).filter(row => row.electric !== null && row.electric >= 20);
|
||||
if (!candidates.length) {
|
||||
showList(); locationStatus('没有符合当前条件的可用车,可在列表中放宽筛选。');
|
||||
return;
|
||||
}
|
||||
candidates.sort((a, b) => (a.distance ?? Infinity) - (b.distance ?? Infinity));
|
||||
const row = candidates[0];
|
||||
nearestBikeId = row.id; closeTools(false); showBikeDetail(row.id);
|
||||
showToast(`${originName || "地图中心"}最近可用:#${row.bike.code},${Math.round(row.distance || 0)} 米,电量 ${row.electric}%`);
|
||||
}
|
||||
async function init() {
|
||||
if (initialized) return;
|
||||
initialized = true; fillControls(); renderFavorites();
|
||||
byId('map-tools-toggle').addEventListener('click', () => { if (byId('discovery-drawer').hidden) openTools(); else closeTools(); });
|
||||
byId('discovery-close').addEventListener('click', () => closeTools());
|
||||
byId('discovery-drawer').addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); closeTools(); } });
|
||||
document.addEventListener('pointerdown', event => { if (!byId('discovery-drawer').hidden && !event.target.closest('#discovery-drawer,#map-tools-toggle')) closeTools(false); });
|
||||
['filter-available','filter-electric','filter-kind','filter-radius','nearby-sort'].forEach(id => byId(id).addEventListener('change', () => {
|
||||
filters.onlyAvailable = byId('filter-available').checked;
|
||||
filters.minElectric = Number(byId('filter-electric').value);
|
||||
filters.kind = byId('filter-kind').value;
|
||||
filters.radius = Number(byId('filter-radius').value);
|
||||
filters.sort = byId('nearby-sort').value; refresh();
|
||||
}));
|
||||
byId('nearby-toggle').addEventListener('click', () => showList(byId('nearby-panel').hidden));
|
||||
byId('discovery-filters').addEventListener('toggle', () => {
|
||||
if (byId('discovery-filters').open && !byId('nearby-panel').hidden) showList(false);
|
||||
});
|
||||
byId('nearby-close').addEventListener('click', () => showList(false));
|
||||
byId('nearby-panel').addEventListener('keydown', e => { if (e.key === 'Escape') showList(false); });
|
||||
byId('nearby-list').addEventListener('click', event => {
|
||||
const row = event.target.closest('[data-bike-id]');
|
||||
if (row) { closeTools(false); showBikeDetail(row.dataset.bikeId); }
|
||||
if (event.target.closest('[data-relax]')) relax();
|
||||
});
|
||||
byId('place-search').addEventListener('input', searchPlaces);
|
||||
byId('place-search').addEventListener('focus', searchPlaces);
|
||||
byId('place-search').addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape') byId('place-results').hidden = true;
|
||||
if (e.key === 'ArrowDown') { e.preventDefault(); byId('place-results').querySelector('button')?.focus(); }
|
||||
if (e.key === 'Enter') { e.preventDefault(); byId('place-results').querySelector('button')?.click(); }
|
||||
});
|
||||
byId('place-results').addEventListener('click', e => {
|
||||
const button = e.target.closest('[data-place-id]');
|
||||
const place = locations.find(p => String(p.id) === button?.dataset.placeId);
|
||||
if (place) { const p = offsetCoord(place.latitude, place.longitude); choosePlace(p, place.name); }
|
||||
});
|
||||
byId('favorite-save').addEventListener('click', savePlace);
|
||||
byId('favorite-places').addEventListener('click', e => {
|
||||
const remove = e.target.closest('[data-remove-favorite]');
|
||||
if (remove) { favorites.splice(Number(remove.dataset.removeFavorite), 1); try { localStorage.setItem(favoriteKey, JSON.stringify(favorites)); } catch (_) {} renderFavorites(); return; }
|
||||
const button = e.target.closest('[data-favorite]');
|
||||
if (button) { const place = favorites[Number(button.dataset.favorite)]; if (place) choosePlace(place, place.name); }
|
||||
});
|
||||
byId('location-center').addEventListener('click', () => { origin = null; originName = ''; if (autoLocationMarker) { const p = map.getCenter(); origin = {lat:p.lat,lng:p.lng}; originName='地图中心'; } render(); showList(); locationStatus('已按地图中心查找,无需定位权限。'); });
|
||||
byId('location-retry').addEventListener('click', () => { origin = null; originName = ''; startAutoLocation(); });
|
||||
byId('discovery-origin').addEventListener('click', () => { origin = null; originName = ''; byId('place-search').value = ''; refresh(); });
|
||||
document.addEventListener('click', e => { if (!e.target.closest('.place-search-wrap')) byId('place-results').hidden = true; });
|
||||
map.addEventListener('moveend', () => { if (!renderFrame) renderFrame = requestAnimationFrame(() => { renderFrame = null; render(); }); });
|
||||
map.addEventListener('dragend', () => {
|
||||
const point = map.getCenter(); origin = {lat:point.lat,lng:point.lng}; originName = '地图中心';
|
||||
byId('place-search').value = ''; render();
|
||||
});
|
||||
try {
|
||||
const response = await AppAPI.fetch('/api/campus/locations'); const data = await response.json();
|
||||
locations = Array.isArray(data.data) ? data.data : [];
|
||||
} catch (_) { locationStatus('校园地点加载失败,可拖动地图查找或重试刷新。'); }
|
||||
render();
|
||||
}
|
||||
window.BikeDiscovery = { init, render, visibleBikes, locationStatus, nearest, showList, openTools, closeTools };
|
||||
})();
|
||||
@@ -1,191 +0,0 @@
|
||||
// ========== 订单历史(我的 → 订单历史) ==========
|
||||
function fmtDuration(seconds) {
|
||||
if (seconds === null || seconds === undefined) return "--";
|
||||
const mins = Math.round(seconds / 60);
|
||||
if (mins < 60) return `${mins} 分钟`;
|
||||
return `${Math.floor(mins / 60)} 小时 ${mins % 60} 分钟`;
|
||||
}
|
||||
function fmtOrderTime(s) {
|
||||
if (!s) return "--";
|
||||
return String(s).replace("T", " ").slice(5, 16); // MM-DD HH:MM
|
||||
}
|
||||
function fmtClock(s) {
|
||||
if (!s) return "--";
|
||||
return String(s).slice(11, 16); // HH:MM
|
||||
}
|
||||
function orderCardHtml(o) {
|
||||
const badge = o.returned
|
||||
? '<span class="badge muted" style="padding:2px 8px;border-radius:8px;font-size:11px;background:var(--ui-surface-raised);color:var(--ui-muted);">已完成</span>'
|
||||
: '<span class="badge" style="padding:2px 8px;border-radius:8px;font-size:11px;background:var(--ui-surface-raised);color:var(--discovery-available);">进行中</span>';
|
||||
const sharedRow = o.shared
|
||||
? `<div style="margin-top:2px;">${o.role === "owner" ? "共享给" : "使用"} <b>${escHtml(o.partner || "--")}</b> 的车</div>` : "";
|
||||
// 多轮续租合并显示:共 N 轮 · 总用时 · 起止时钟
|
||||
const roundsRow = (o.rounds && o.rounds > 1)
|
||||
? `<div style="margin-top:2px;color:var(--ui-muted);">共 ${o.rounds} 轮 · 总用时 ${fmtDuration(o.duration_seconds)}</div>` : "";
|
||||
const timeRow = `${fmtOrderTime(o.start_time)} → ${fmtOrderTime(o.end_time)}`;
|
||||
return `
|
||||
<div class="device-item" style="display:block;padding:10px 12px;border-bottom:1px solid var(--bg-tertiary,#ececf1);">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;">
|
||||
<b style="font-size:14px;">#${escHtml(o.bike_code)}</b>
|
||||
<span style="display:flex;align-items:center;gap:6px;">
|
||||
<span style="font-size:12px;color:var(--text-secondary);">${o.duration_seconds !== null ? fmtDuration(o.duration_seconds) : ""}</span>
|
||||
${badge}
|
||||
</span>
|
||||
</div>
|
||||
<div style="font-size:12.5px;color:var(--text-secondary);margin-top:3px;line-height:1.7;">
|
||||
<div>${timeRow}</div>
|
||||
<div>${escHtml(o.start_label || "起点未知")} <span style="margin:0 3px;">→</span> ${escHtml(o.end_label || (o.returned ? "终点未知" : "骑行中"))}</div>
|
||||
${roundsRow}
|
||||
${sharedRow}
|
||||
</div>
|
||||
<div style="margin-top:6px;text-align:right;">
|
||||
<button class="btn" style="padding:4px 10px;border:none;border-radius:8px;font-size:12px;background:#e7f0fd;color:var(--ui-muted);"
|
||||
onclick="openOrderTrajectory(${o.id})">查看轨迹</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
// ========== 订单骑行轨迹 ==========
|
||||
let orderTrajMap = null;
|
||||
let orderTrajOverlays = [];
|
||||
async function openOrderTrajectory(rentalId){
|
||||
SettingsPages.open("order-traj-modal");
|
||||
document.getElementById("order-traj-summary").textContent = "加载轨迹中...";
|
||||
document.getElementById("order-traj-hint").textContent = "轨迹来自每 5-10 分钟一次的车辆定位采集。";
|
||||
try{
|
||||
const resp = await apiFetch(`/api/user/orders/trajectory?rental_id=${encodeURIComponent(rentalId)}`, {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code !== 0) {
|
||||
document.getElementById("order-traj-summary").textContent = data.message || "轨迹加载失败";
|
||||
return;
|
||||
}
|
||||
renderOrderTrajectory(data.data);
|
||||
}catch(e){
|
||||
document.getElementById("order-traj-summary").textContent = "网络错误,请重试";
|
||||
}
|
||||
}
|
||||
function closeOrderTrajModal(){
|
||||
SettingsPages.back();
|
||||
// 保留地图实例,下次复用;只清理覆盖物
|
||||
if (orderTrajMap) {
|
||||
try { orderTrajMap.clearOverlays(); } catch(e) {}
|
||||
}
|
||||
orderTrajOverlays = [];
|
||||
}
|
||||
function renderOrderTrajectory(t){
|
||||
const pts = t.points || [];
|
||||
// textContent 不解析 HTML,这里不能用 escHtml(会把 & 显示成 &)
|
||||
document.getElementById("order-traj-summary").textContent =
|
||||
`#${t.bike_code} · ${fmtOrderTime(t.start_time)} → ${fmtOrderTime(t.end_time)} · ` +
|
||||
`${t.start_label || "起点未知"} → ${t.end_label || (t.returned ? "终点未知" : "骑行中")}`;
|
||||
|
||||
const initMap = () => {
|
||||
if (!orderTrajMap) {
|
||||
orderTrajMap = new BMapGL.Map("order-traj-map");
|
||||
orderTrajMap.enableScrollWheelZoom(true);
|
||||
}
|
||||
const overlayPts = [];
|
||||
try { orderTrajMap.clearOverlays(); } catch(e) {}
|
||||
const toBd = (lat, lng) => offsetCoord(lat, lng);
|
||||
|
||||
// 轨迹线(GCJ02 → BD09 逐点转换)
|
||||
const linePts = pts.map(p => {
|
||||
const c = toBd(p.lat, p.lng);
|
||||
return new BMapGL.Point(c.lng, c.lat);
|
||||
});
|
||||
// 采集缺失时用订单起终点兜底成两点直线
|
||||
if (linePts.length < 2 && (t.start_point || t.end_point)) {
|
||||
const s = t.start_point, e = t.end_point || t.start_point;
|
||||
const cs = toBd(s.lat, s.lng), ce = toBd(e.lat, e.lng);
|
||||
linePts.push(new BMapGL.Point(cs.lng, cs.lat), new BMapGL.Point(ce.lng, ce.lat));
|
||||
}
|
||||
if (linePts.length >= 2) {
|
||||
const poly = new BMapGL.Polyline(linePts, {
|
||||
strokeColor: "#0a84ff", strokeWeight: 5, strokeOpacity: 0.85,
|
||||
});
|
||||
orderTrajMap.addOverlay(poly);
|
||||
overlayPts.push(...linePts);
|
||||
}
|
||||
// 起终点标记
|
||||
const mark = (pt, color, text) => {
|
||||
if (!pt) return;
|
||||
const c = toBd(pt.lat, pt.lng);
|
||||
const p = new BMapGL.Point(c.lng, c.lat);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = 26;
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx.beginPath(); ctx.arc(13, 13, 10, 0, Math.PI * 2);
|
||||
ctx.fillStyle = color; ctx.fill();
|
||||
ctx.fillStyle = "#fff"; ctx.font = "bold 12px Arial";
|
||||
ctx.textAlign = "center"; ctx.textBaseline = "middle";
|
||||
ctx.fillText(text, 13, 13);
|
||||
const marker = new BMapGL.Marker(p, {
|
||||
icon: new BMapGL.Icon(canvas.toDataURL(), new BMapGL.Size(26, 26), new BMapGL.Size(13, 13))
|
||||
});
|
||||
orderTrajMap.addOverlay(marker);
|
||||
overlayPts.push(p);
|
||||
};
|
||||
mark(t.start_point, "#34c759", "起");
|
||||
mark(t.end_point, "#ff3b30", "终");
|
||||
|
||||
if (overlayPts.length) {
|
||||
try {
|
||||
orderTrajMap.setViewport(overlayPts, { margins: [30, 30, 30, 30] });
|
||||
} catch (e) {
|
||||
orderTrajMap.centerAndZoom(overlayPts[0], 18);
|
||||
}
|
||||
} else {
|
||||
apiFetch("/api/config").then(r => r.json()).then(cfg => {
|
||||
const c = offsetCoord(cfg.center_lat, cfg.center_lng);
|
||||
orderTrajMap.centerAndZoom(new BMapGL.Point(c.lng, c.lat), 17);
|
||||
});
|
||||
}
|
||||
document.getElementById("order-traj-hint").textContent = pts.length
|
||||
? `共 ${pts.length} 个定位点`
|
||||
: "该时间段没有采集到定位点(采集间隔 5-10 分钟),已用订单起终点示意";
|
||||
};
|
||||
|
||||
// 弹窗刚显示,等一帧再初始化,避免容器尺寸为 0
|
||||
setTimeout(initMap, 60);
|
||||
}
|
||||
let orderHistoryRows = [], orderHistorySerial = 0, orderHistoryController = null;
|
||||
async function openOrdersModal() {
|
||||
closeAllModals(); SettingsPages.open("orders-modal");
|
||||
await loadOrderPage(true);
|
||||
}
|
||||
function closeOrdersModal() { SettingsPages.back(); }
|
||||
function resetOrderFilters() {
|
||||
["orders-from", "orders-to", "orders-code"].forEach(id => document.getElementById(id).value = "");
|
||||
document.getElementById("orders-source").value = "all";
|
||||
loadOrderPage(true);
|
||||
}
|
||||
async function loadOrderPage(reset) {
|
||||
const from = document.getElementById("orders-from").value, to = document.getElementById("orders-to").value;
|
||||
const code = document.getElementById("orders-code").value.trim();
|
||||
if (from && to && from > to) { showToast("开始日期不能晚于结束日期"); return; }
|
||||
if (code && !/^\d{1,8}$/.test(code)) { showToast("车牌筛选只能包含最多8位数字"); return; }
|
||||
const serial = ++orderHistorySerial;
|
||||
orderHistoryController?.abort(); orderHistoryController = new AbortController();
|
||||
const box = document.getElementById("orders-list"), more = document.getElementById("orders-more");
|
||||
if (reset) { orderHistoryRows = []; box.innerHTML = '<div class="device-loading">正在查询记录...</div>'; }
|
||||
more.disabled = true;
|
||||
document.getElementById("orders-search").disabled = true;
|
||||
const query = new URLSearchParams({limit:"20", offset:String(orderHistoryRows.length), from, to, code, source:document.getElementById("orders-source").value});
|
||||
try {
|
||||
const response = await apiFetch(`/api/user/orders?${query}`, { headers:{Authorization:`Bearer ${authToken}`}, signal:orderHistoryController.signal });
|
||||
const data = await response.json();
|
||||
if (serial !== orderHistorySerial) return;
|
||||
if (data.rtn_code !== 0) throw new Error(data.message || "查询失败");
|
||||
orderHistoryRows.push(...(data.data || []));
|
||||
document.getElementById("orders-summary").textContent = `共 ${data.total ?? orderHistoryRows.length} 条记录,已显示 ${orderHistoryRows.length} 条`;
|
||||
box.innerHTML = orderHistoryRows.length ? orderHistoryRows.map(orderCardHtml).join("") : '<div class="device-loading">没有符合条件的订单,可调整日期、车牌或来源后重试。</div>';
|
||||
more.hidden = !data.has_more;
|
||||
} catch (error) {
|
||||
if (serial !== orderHistorySerial) return;
|
||||
if (reset) box.innerHTML = `<div class="device-loading">${escHtml(error.message)},请点击“查询记录”重试。</div>`;
|
||||
else showToast(error.message || "加载失败,请重试");
|
||||
} finally {
|
||||
if (serial === orderHistorySerial) { more.disabled = false; document.getElementById("orders-search").disabled = false; }
|
||||
}
|
||||
}
|
||||
@@ -1,976 +0,0 @@
|
||||
// ========== 订单状态检测 ==========
|
||||
let currentOrder = null; // 当前订单信息
|
||||
|
||||
async function checkOrderStatus() {
|
||||
if (!authToken) {
|
||||
hideOrderBanner();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await apiFetch("/api/order/status", {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
});
|
||||
const data = await resp.json();
|
||||
|
||||
if (data.rtn_code === 0) {
|
||||
if (!data.has_credentials) {
|
||||
// 用户没有配置凭据
|
||||
hideOrderBanner();
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.has_order && data.order) {
|
||||
currentOrder = data.order;
|
||||
// 仅当“当前微信订单本身就是我共享出去的这笔订单”时隐藏普通横幅。
|
||||
// 骑行者自己账号另有待支付/进行中订单时,必须与借用中的共享横幅同时保留。
|
||||
if (data.order.shared) {
|
||||
hideOrderBanner();
|
||||
} else {
|
||||
showOrderBanner(data.order);
|
||||
}
|
||||
} else {
|
||||
currentOrder = null;
|
||||
hideOrderBanner();
|
||||
}
|
||||
} else if (data.rtn_code === 102001 || data.token_invalid) {
|
||||
// token_id 已失效(小程序重新登录会踢掉旧会话):弹窗引导重新配置(带冷却,避免每20秒轮询骚扰)
|
||||
notifyCredentialInvalid(data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("检查订单状态失败:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function showOrderBanner(order) {
|
||||
const banner = document.getElementById("order-banner");
|
||||
const icon = document.getElementById("order-banner-icon");
|
||||
const text = document.getElementById("order-banner-text");
|
||||
const btn = document.getElementById("order-banner-btn");
|
||||
|
||||
banner.classList.remove("warning", "riding");
|
||||
|
||||
if (Number(order.status) === 1) {
|
||||
// 待支付
|
||||
banner.classList.add("warning");
|
||||
icon.innerHTML = '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>';
|
||||
text.textContent = `待支付订单 #${order.code || order.order_id.slice(-6)}`;
|
||||
btn.textContent = "去支付";
|
||||
hideOrderCountdown();
|
||||
const progress = document.getElementById("order-final-time");
|
||||
progress.textContent = "待支付 · 骑行已结束";
|
||||
progress.style.display = "inline";
|
||||
} else if (Number(order.status) === 2) {
|
||||
// 进行中 - 获取倒计时
|
||||
banner.classList.add("riding");
|
||||
icon.innerHTML = '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><circle cx="5.5" cy="17.5" r="3.5"/><circle cx="18.5" cy="17.5" r="3.5"/><path d="M15 6h3l2 4-2.5 1.5a8 8 0 0 1-7 3.5c-2.5 0-4.5-1.5-5.5-3.5L2 12l4-4h4"/></svg>';
|
||||
if (order.shared) {
|
||||
const sName = partnerLabel(order.shared.rider_name, order.shared.rider_email, order.shared.remark);
|
||||
text.textContent = ("共享中 #" + (order.code || order.order_id.slice(-6)) + " · " + sName + "使用中");
|
||||
} else {
|
||||
text.textContent = `进行中 #${order.code || order.order_id.slice(-6)}`;
|
||||
}
|
||||
btn.textContent = "还车";
|
||||
if (String(orderCountdownOrderId) !== String(order.order_id)) {
|
||||
hideOrderCountdown();
|
||||
const progress = document.getElementById("order-final-time");
|
||||
progress.textContent = "骑行中 · 正在同步计时";
|
||||
progress.style.display = "inline";
|
||||
}
|
||||
// 从后端获取剩余时间并启动倒计时
|
||||
fetchOrderCountdown(order.order_id);
|
||||
}
|
||||
|
||||
banner.classList.add("show");
|
||||
}
|
||||
|
||||
let orderCountdownTimer = null;
|
||||
let orderCountdownSeconds = 0;
|
||||
let orderCountdownDeadline = null;
|
||||
let orderCountdownOrderId = null;
|
||||
|
||||
function rideProgressText(summary) {
|
||||
const current = Math.max(1, Number(summary.current_round) || 1);
|
||||
const total = Math.max(current, Number(summary.total_rounds) || current);
|
||||
const end = String(summary.final_end_time || summary.end_time || "").match(/(?:T|\s)(\d{2}:\d{2})/);
|
||||
const phase = summary.auto_return ? "自动还车已开启" : "手动还车";
|
||||
return `第 ${current}/${total} 轮 · ${phase}` + (end ? ` · 预计 ${end[1]} 结束` : "");
|
||||
}
|
||||
|
||||
function remainingTimeText(seconds) {
|
||||
const remaining = Math.max(0, Math.ceil(Number(seconds) || 0));
|
||||
return `${Math.floor(remaining / 60)}:${String(remaining % 60).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function fetchOrderCountdown(orderId) {
|
||||
if (!authToken || !orderId) return;
|
||||
|
||||
apiFetch(`/api/rental/status?order_id=${encodeURIComponent(orderId)}`, {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (!currentOrder || String(currentOrder.order_id) !== String(orderId) || Number(currentOrder.status) !== 2) return;
|
||||
if (data.rtn_code === 0 && data.data && data.data.active) {
|
||||
orderCountdownSeconds = Math.max(0, Number(data.data.remaining_seconds) || 0);
|
||||
orderCountdownDeadline = performance.now() + orderCountdownSeconds * 1000;
|
||||
orderCountdownOrderId = orderId;
|
||||
// 多轮适配:展示计划总轮数与最终预计还车时间
|
||||
const finalEl = document.getElementById("order-final-time");
|
||||
const addBtn = document.getElementById("order-banner-add-round-btn");
|
||||
if (finalEl) {
|
||||
finalEl.textContent = rideProgressText(data.data);
|
||||
finalEl.style.display = "inline";
|
||||
}
|
||||
if (addBtn) {
|
||||
// 真实订单才可加轮; reminder 计时不显示
|
||||
const eligible = data.data.order_id && String(data.data.source) !== "reminder";
|
||||
addBtn.style.display = eligible ? "inline-block" : "none";
|
||||
}
|
||||
showOrderCountdown();
|
||||
startOrderCountdown();
|
||||
} else if (data.rtn_code === 0) {
|
||||
hideOrderCountdown();
|
||||
const progress = document.getElementById("order-final-time");
|
||||
progress.textContent = "骑行中 · 计时同步中";
|
||||
progress.style.display = "inline";
|
||||
}
|
||||
})
|
||||
.catch(err => console.error("获取倒计时失败:", err));
|
||||
}
|
||||
|
||||
function showOrderCountdown() {
|
||||
const el = document.getElementById("order-countdown");
|
||||
el.style.display = "inline";
|
||||
updateOrderCountdownText();
|
||||
}
|
||||
|
||||
function hideOrderCountdown() {
|
||||
orderCountdownDeadline = null;
|
||||
orderCountdownOrderId = null;
|
||||
document.getElementById("order-banner-add-round-btn").style.display = "none";
|
||||
document.getElementById("order-final-time").style.display = "none";
|
||||
const el = document.getElementById("order-countdown");
|
||||
el.style.display = "none";
|
||||
if (orderCountdownTimer) {
|
||||
clearInterval(orderCountdownTimer);
|
||||
orderCountdownTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function updateOrderCountdownText() {
|
||||
const el = document.getElementById("order-countdown");
|
||||
const remaining = Math.max(0, orderCountdownSeconds);
|
||||
const mins = Math.floor(remaining / 60);
|
||||
const secs = remaining % 60;
|
||||
el.textContent = remaining > 0 ? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}` : "本轮到期 · 同步状态中";
|
||||
|
||||
// 变色提示
|
||||
if (remaining <= 60) {
|
||||
el.style.color = "#ff3b30";
|
||||
} else if (remaining <= 300) {
|
||||
el.style.color = "#ffcc00";
|
||||
} else {
|
||||
el.style.color = "white";
|
||||
}
|
||||
}
|
||||
|
||||
function startOrderCountdown() {
|
||||
if (orderCountdownTimer) clearInterval(orderCountdownTimer);
|
||||
orderCountdownTimer = setInterval(() => {
|
||||
orderCountdownSeconds = Math.max(0, Math.ceil((orderCountdownDeadline - performance.now()) / 1000));
|
||||
updateOrderCountdownText();
|
||||
if (orderCountdownSeconds <= 0) {
|
||||
clearInterval(orderCountdownTimer);
|
||||
// 倒计时结束,刷新订单状态
|
||||
checkOrderStatus();
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function hideOrderBanner() {
|
||||
document.getElementById("order-banner").classList.remove("show");
|
||||
hideOrderCountdown();
|
||||
closeOrderActionsModal();
|
||||
}
|
||||
|
||||
function isOrderActionEligible(order) {
|
||||
if (!order) return false;
|
||||
const type = String(order.type || "").toLowerCase();
|
||||
const source = String(order.source || "").toLowerCase();
|
||||
return type !== "reminder" && source !== "reminder";
|
||||
}
|
||||
|
||||
function handleOrderBannerSurfaceClick(event) {
|
||||
// 横幅右侧已有的两个按钮继续走原有行为,不触发全屏面板。
|
||||
if (event && event.target && event.target.closest && event.target.closest("button")) return;
|
||||
if (!isOrderActionEligible(currentOrder)) return;
|
||||
showOrderActionsModal();
|
||||
}
|
||||
|
||||
function showOrderActionsModal() {
|
||||
if (!isOrderActionEligible(currentOrder)) return;
|
||||
|
||||
const modal = document.getElementById("order-actions-modal");
|
||||
const meta = document.getElementById("order-actions-meta");
|
||||
const status = document.getElementById("order-actions-status");
|
||||
const hint = document.getElementById("order-actions-hint");
|
||||
const code = currentOrder.code || currentOrder.order_id || "未知";
|
||||
const pending = Number(currentOrder.status) === 1;
|
||||
|
||||
meta.textContent = `车辆 #${code}`;
|
||||
status.textContent = pending ? "待支付订单" : "订单进行中";
|
||||
status.classList.toggle("warning", pending);
|
||||
status.classList.toggle("riding", !pending);
|
||||
hint.textContent = pending
|
||||
? "当前订单尚未支付,请先完成支付后再使用车辆操作。"
|
||||
: "临时锁车不会结束订单,确认车辆停放安全后再操作。";
|
||||
|
||||
// 待支付订单明确不展示临时锁车/临时开车。
|
||||
["order-action-lock", "order-action-unlock"].forEach(id => {
|
||||
const button = document.getElementById(id);
|
||||
if (button) button.style.display = pending ? "none" : "flex";
|
||||
});
|
||||
const pay = document.getElementById("order-action-pay");
|
||||
const ret = document.getElementById("order-action-return");
|
||||
if (pay) pay.style.display = pending ? "flex" : "none";
|
||||
if (ret) ret.style.display = pending ? "none" : "flex";
|
||||
|
||||
modal.classList.add("show");
|
||||
modal.setAttribute("aria-hidden", "false");
|
||||
document.body.classList.add("order-actions-open");
|
||||
window.setTimeout(() => document.getElementById("order-actions-close")?.focus(), 0);
|
||||
}
|
||||
|
||||
function closeOrderActionsModal() {
|
||||
const modal = document.getElementById("order-actions-modal");
|
||||
if (!modal) return;
|
||||
modal.classList.remove("show");
|
||||
modal.setAttribute("aria-hidden", "true");
|
||||
document.body.classList.remove("order-actions-open");
|
||||
}
|
||||
|
||||
function viewBikeDetailFromOrderModal() {
|
||||
closeOrderActionsModal();
|
||||
viewBikeDetailFromOrder();
|
||||
}
|
||||
|
||||
async function findCurrentOrderBike() {
|
||||
if (!isOrderActionEligible(currentOrder)) return;
|
||||
const code = (currentOrder.code || "").toString().trim();
|
||||
if (!code) {
|
||||
showToast("该订单没有车牌信息");
|
||||
return;
|
||||
}
|
||||
|
||||
const button = document.getElementById("order-action-find");
|
||||
if (button) {
|
||||
button.disabled = true;
|
||||
button.querySelector("strong").textContent = "发送中...";
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await _doFindBikeRequest(code);
|
||||
if (data && (data.rtn_code === 0 || data.success)) {
|
||||
showToast("寻车指令已发送,请听声音");
|
||||
} else {
|
||||
showToast((data && data.message) || "寻车失败");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("订单寻车失败:", err);
|
||||
showToast("寻车失败,请重试");
|
||||
} finally {
|
||||
if (button) {
|
||||
button.disabled = false;
|
||||
button.querySelector("strong").textContent = "寻车";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function payCurrentOrderFromModal() {
|
||||
closeOrderActionsModal();
|
||||
tryCardPayOrRedirect();
|
||||
}
|
||||
|
||||
function returnCurrentOrderFromModal() {
|
||||
closeOrderActionsModal();
|
||||
showReturnConfirm();
|
||||
}
|
||||
|
||||
function handleOrderBannerClick() {
|
||||
if (!currentOrder) {
|
||||
showToast("订单状态已变化,正在刷新,请稍后重试");
|
||||
checkOrderStatus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (Number(currentOrder.status) === 1) {
|
||||
// 待支付 - 先检查是否有月卡/周卡
|
||||
tryCardPayOrRedirect();
|
||||
} else if (Number(currentOrder.status) === 2) {
|
||||
// 进行中 - 显示还车确认弹窗
|
||||
showReturnConfirm();
|
||||
} else {
|
||||
showToast("订单状态已变化,正在刷新,请稍后重试");
|
||||
checkOrderStatus();
|
||||
}
|
||||
}
|
||||
|
||||
// 查看详情:等同在搜索框输入当前订单车牌并点击查询,直接弹出车辆详情
|
||||
function viewBikeDetailFromOrder() {
|
||||
if (!currentOrder) { showToast("当前没有进行中的订单"); return; }
|
||||
const code = (currentOrder.code || "").toString().trim();
|
||||
if (!code) { showToast("该订单没有车牌信息"); return; }
|
||||
document.getElementById("scan-input").value = code;
|
||||
scanCode();
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", event => {
|
||||
if (event.key !== "Escape") return;
|
||||
// 确认弹窗优先响应 ESC(原生壳没有系统对话框,全靠页面内弹窗)
|
||||
const _cm = document.getElementById("app-confirm-modal");
|
||||
if (_cm && _cm.classList.contains("show")) { appConfirmClose(); return; }
|
||||
const _arm = document.getElementById("add-round-modal");
|
||||
if (_arm && _arm.classList.contains("show")) { closeAddRoundModal(); return; }
|
||||
const _oam = document.getElementById("order-actions-modal");
|
||||
if (_oam && _oam.classList.contains("show")) { closeOrderActionsModal(); return; }
|
||||
});
|
||||
|
||||
// ========== 月卡/周卡自动支付 ==========
|
||||
let cardPayLoading = false;
|
||||
|
||||
async function tryCardPayOrRedirect() {
|
||||
if (cardPayLoading || !currentOrder) return;
|
||||
|
||||
const btn = document.getElementById("order-banner-btn");
|
||||
cardPayLoading = true;
|
||||
btn.textContent = "检测中…";
|
||||
btn.disabled = true;
|
||||
|
||||
try {
|
||||
// 1. 查询可用支付方式
|
||||
const methodsResp = await apiFetch(
|
||||
`/api/order/pay_methods?code=${encodeURIComponent(currentOrder.code || "")}`,
|
||||
{ headers: { "Authorization": `Bearer ${authToken}` } }
|
||||
);
|
||||
const methodsData = await methodsResp.json();
|
||||
|
||||
if (methodsData.rtn_code !== 0) {
|
||||
// 接口失败,降级提示跳转
|
||||
showToast("请到小白超人小程序支付订单");
|
||||
return;
|
||||
}
|
||||
|
||||
const cardMethods = methodsData.data?.card_methods || [];
|
||||
|
||||
if (cardMethods.length === 0) {
|
||||
// 没有月卡/周卡 → 原来逻辑
|
||||
showToast("未找到月卡,请到小白超人小程序支付");
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 优先选 get_type=2(推荐/激活)的卡,否则取第一个
|
||||
const preferred = cardMethods.find(m => m.get_type === 2) || cardMethods[0];
|
||||
const cardTypeName = preferred.type === "3" || preferred.type === 3 ? "月卡" : "周卡";
|
||||
|
||||
// 3. 更新按钮状态
|
||||
btn.textContent = `${cardTypeName}支付中…`;
|
||||
|
||||
// 4. 调用月卡支付接口
|
||||
const payResp = await apiFetch("/api/order/pay_with_card", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
order_id: currentOrder.order_id,
|
||||
code: currentOrder.code || "",
|
||||
type: String(preferred.type),
|
||||
package_id: String(preferred.package_id)
|
||||
})
|
||||
});
|
||||
const payData = await payResp.json();
|
||||
|
||||
if (payData.rtn_code === 0 && payData.data?.paid) {
|
||||
// 月卡支付成功
|
||||
showToast(`${cardTypeName}支付成功 ✓`);
|
||||
currentOrder = null;
|
||||
hideOrderBanner();
|
||||
refreshMap();
|
||||
} else if (payData.rtn_code === 0 && payData.data?.need_wechat_pay) {
|
||||
// 月卡不足,需要微信支付
|
||||
showToast("月卡余额不足,请到小白超人小程序完成支付");
|
||||
} else {
|
||||
showToast(payData.message || "支付失败,请到小白超人小程序支付");
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error("月卡支付失败:", err);
|
||||
showToast("请到小白超人小程序支付订单");
|
||||
} finally {
|
||||
cardPayLoading = false;
|
||||
btn.textContent = "去支付";
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 还车确认 ==========
|
||||
let returnLoading = false;
|
||||
let pendingReturnOrder = null;
|
||||
|
||||
async function getOrderOperationLocation() {
|
||||
let position = null;
|
||||
if (navigator.geolocation) {
|
||||
position = await new Promise(resolve => {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
pos => resolve(pos),
|
||||
err => {
|
||||
console.error("获取位置失败:", err);
|
||||
resolve(null);
|
||||
},
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const latitude = Number.isFinite(position?.coords?.latitude)
|
||||
? position.coords.latitude : 36.67;
|
||||
const longitude = Number.isFinite(position?.coords?.longitude)
|
||||
? position.coords.longitude : 116.98;
|
||||
return { latitude, longitude };
|
||||
}
|
||||
|
||||
function showReturnConfirm() {
|
||||
if (returnLoading) return;
|
||||
if (!currentOrder || Number(currentOrder.status) !== 2) {
|
||||
showToast("当前没有可还车的进行中订单,正在刷新");
|
||||
checkOrderStatus();
|
||||
return;
|
||||
}
|
||||
pendingReturnOrder = { ...currentOrder };
|
||||
document.getElementById("return-confirm-text").textContent =
|
||||
`车辆 #${currentOrder.code || currentOrder.order_id} 正在骑行,确认要还车吗?`;
|
||||
document.getElementById("return-confirm-modal").classList.add("show");
|
||||
document.getElementById("return-confirm-btn").disabled = false;
|
||||
document.getElementById("return-confirm-btn").textContent = "确认还车";
|
||||
}
|
||||
|
||||
function closeReturnConfirm() {
|
||||
document.getElementById("return-confirm-modal").classList.remove("show");
|
||||
pendingReturnOrder = null;
|
||||
}
|
||||
|
||||
async function doReturnBike() {
|
||||
if (returnLoading) return;
|
||||
const order = pendingReturnOrder;
|
||||
if (!order) {
|
||||
showToast("请重新点击还车并确认订单");
|
||||
return;
|
||||
}
|
||||
|
||||
returnLoading = true;
|
||||
const btn = document.getElementById("return-confirm-btn");
|
||||
btn.disabled = true;
|
||||
btn.textContent = "还车中...";
|
||||
|
||||
try {
|
||||
// 还车和临时锁车共用同一套当前位置获取逻辑。
|
||||
const { latitude, longitude } = await getOrderOperationLocation();
|
||||
|
||||
const resp = await apiFetch("/api/order/return", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
order_id: order.order_id,
|
||||
code: order.code,
|
||||
latitude: latitude,
|
||||
longitude: longitude
|
||||
})
|
||||
});
|
||||
|
||||
const data = await resp.json();
|
||||
|
||||
if (data.rtn_code === 0) {
|
||||
let msg = data.used_nearest ? "还车成功(已切换至最近停车点)" : "还车成功";
|
||||
// 显示月卡支付结果
|
||||
if (data.card_pay) {
|
||||
msg += data.card_pay.success ? `,${data.card_pay.message}` : `,${data.card_pay.message}`;
|
||||
}
|
||||
showToast(msg);
|
||||
closeReturnConfirm();
|
||||
if (!currentOrder || String(currentOrder.order_id) === String(order.order_id)) {
|
||||
currentOrder = null;
|
||||
hideOrderBanner();
|
||||
}
|
||||
// 刷新地图
|
||||
refreshMap();
|
||||
refreshShareBanners();
|
||||
} else {
|
||||
showToast(data.message || "还车失败");
|
||||
}
|
||||
} catch (err) {
|
||||
showToast("还车失败,请重试");
|
||||
} finally {
|
||||
returnLoading = false;
|
||||
btn.disabled = false;
|
||||
btn.textContent = "确认还车";
|
||||
}
|
||||
}
|
||||
|
||||
let orderTempActionLoading = false;
|
||||
|
||||
async function tempLockCurrentOrder() {
|
||||
if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return;
|
||||
const button = document.getElementById("order-action-lock");
|
||||
orderTempActionLoading = true;
|
||||
if (button) {
|
||||
button.disabled = true;
|
||||
button.querySelector("strong").textContent = "锁车中...";
|
||||
}
|
||||
|
||||
try {
|
||||
const { latitude, longitude } = await getOrderOperationLocation();
|
||||
const resp = await apiFetch("/api/order/temp_lock", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
order_id: currentOrder.order_id,
|
||||
code: currentOrder.code,
|
||||
latitude,
|
||||
longitude
|
||||
})
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code === 0) {
|
||||
showToast(data.used_nearest ? "临时锁车成功(已切换至最近停车点)" : "临时锁车成功");
|
||||
const status = document.getElementById("order-actions-status");
|
||||
if (status) status.textContent = "车辆已临时锁定,订单仍在进行中";
|
||||
} else {
|
||||
showToast(data.message || "临时锁车失败");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("临时锁车失败:", err);
|
||||
showToast("临时锁车失败,请重试");
|
||||
} finally {
|
||||
orderTempActionLoading = false;
|
||||
if (button) {
|
||||
button.disabled = false;
|
||||
button.querySelector("strong").textContent = "临时锁车";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function tempUnlockCurrentOrder() {
|
||||
if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return;
|
||||
const button = document.getElementById("order-action-unlock");
|
||||
orderTempActionLoading = true;
|
||||
if (button) {
|
||||
button.disabled = true;
|
||||
button.querySelector("strong").textContent = "开车中...";
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await apiFetch("/api/order/temp_unlock", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({ order_id: currentOrder.order_id })
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code === 0) {
|
||||
showToast(data.message || "临时开车成功");
|
||||
const status = document.getElementById("order-actions-status");
|
||||
if (status) status.textContent = "车辆正在解锁,请稍候";
|
||||
} else {
|
||||
showToast(data.message || "临时开车失败");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("临时开车失败:", err);
|
||||
showToast("临时开车失败,请重试");
|
||||
} finally {
|
||||
orderTempActionLoading = false;
|
||||
if (button) {
|
||||
button.disabled = false;
|
||||
button.querySelector("strong").textContent = "临时开车";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 一键开锁 ==========
|
||||
let unlockPendingCode = null; // 待开锁的车牌
|
||||
let unlockPendingPosition = null; // 待开锁的位置
|
||||
|
||||
function handleQuickUnlock() {
|
||||
const qrBox = document.getElementById("qrcode-box");
|
||||
const code = qrBox.dataset.bikeCode;
|
||||
|
||||
if (!code) {
|
||||
showToast("无法获取车辆编码");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!currentUser) {
|
||||
showToast("请先登录");
|
||||
return;
|
||||
}
|
||||
|
||||
// 保存待开锁信息(用车辆自身坐标 + 随机抖动 ±0.0001,不依赖用户真实定位)
|
||||
const baseLat = parseFloat(selectedBike?.latitude) || 36.67;
|
||||
const baseLng = parseFloat(selectedBike?.longitude) || 116.98;
|
||||
const jit = 0.0001;
|
||||
unlockPendingCode = code;
|
||||
unlockPendingPosition = {
|
||||
lat: baseLat + (Math.random() * 2 - 1) * jit,
|
||||
lng: baseLng + (Math.random() * 2 - 1) * jit
|
||||
};
|
||||
|
||||
// 有共享绑定 → 先选开锁账号;否则直接确认
|
||||
openUnlockAccountChooser();
|
||||
}
|
||||
|
||||
// ===== 开锁账号选择(自己 / 共享者列表) =====
|
||||
let unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" };
|
||||
let unlockSrcList = [];
|
||||
let unlockSrcShowAll = false;
|
||||
|
||||
function openUnlockAccountChooser() {
|
||||
unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" };
|
||||
unlockSrcShowAll = false;
|
||||
if (!authToken || !currentUser) { proceedToUnlockConfirm(); return; }
|
||||
apiFetch("/api/share/sources", { headers: { "Authorization": "Bearer " + authToken } })
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.rtn_code !== 0 || !data.data) { proceedToUnlockConfirm(); return; }
|
||||
const d = data.data;
|
||||
if (!d.has_any) { proceedToUnlockConfirm(); return; }
|
||||
renderUnlockSrcList(d);
|
||||
document.getElementById("unlock-src-modal").classList.add("show");
|
||||
})
|
||||
.catch(() => proceedToUnlockConfirm());
|
||||
}
|
||||
|
||||
function renderUnlockSrcList(d) {
|
||||
const box = document.getElementById("unlock-src-list");
|
||||
let html = "";
|
||||
html += '<button class="unlock-src-item" onclick="chooseUnlockSrc(0)"><span>自己的账号</span><span class="tag">自己付费</span></button>';
|
||||
const srcs = d.sources || [];
|
||||
unlockSrcList = srcs.slice();
|
||||
if (srcs.length === 0 && d.hidden_count > 0) {
|
||||
html += '<div class="share-desc">共享者今日次数都已用完,可查看或直接用自己的账号。</div>';
|
||||
}
|
||||
srcs.forEach(s => {
|
||||
const dis = s.can_use ? "" : "unavailable";
|
||||
const tagTxt = s.can_use ? ("剩余可用 " + s.remaining_today + " 次") : (s.reasons && s.reasons.length ? s.reasons.join(" / ") : "不可用");
|
||||
const label = partnerLabel(s.owner_name, s.owner_email, s.remark);
|
||||
html += '<button class="unlock-src-item ' + dis + '" onclick="chooseUnlockSrc(' + s.owner_user_id + ')"><span>' + escHtml(label) + '</span><span class="tag">' + escHtml(tagTxt) + '</span></button>';
|
||||
});
|
||||
if (d.hidden_count > 0) {
|
||||
html += '<a class="unlock-src-more" onclick="event.stopPropagation();loadUnlockSrcShowAll()">还有 ' + d.hidden_count + ' 位共享者今日次数已用完(点击查看)</a>';
|
||||
}
|
||||
box.innerHTML = html;
|
||||
}
|
||||
|
||||
function loadUnlockSrcShowAll() {
|
||||
unlockSrcShowAll = true;
|
||||
apiFetch("/api/share/sources?show_unavailable=1", { headers: { "Authorization": "Bearer " + authToken } })
|
||||
.then(r => r.json())
|
||||
.then(data => { if (data.rtn_code === 0) renderUnlockSrcList(data.data); });
|
||||
}
|
||||
|
||||
function chooseUnlockSrc(ownerId) {
|
||||
ownerId = ownerId || 0;
|
||||
const rec = unlockSrcList.find(x => Number(x.owner_user_id) === Number(ownerId));
|
||||
if (ownerId && !rec) { closeUnlockSrc(); return; }
|
||||
unlockChoice = rec
|
||||
? { mode: "shared", owner_user_id: rec.owner_user_id, owner_email: rec.owner_email,
|
||||
owner_display: partnerLabel(rec.owner_name, rec.owner_email, rec.remark) }
|
||||
: { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" };
|
||||
closeUnlockSrc();
|
||||
proceedToUnlockConfirm();
|
||||
}
|
||||
|
||||
function closeUnlockSrc() {
|
||||
document.getElementById("unlock-src-modal").classList.remove("show");
|
||||
}
|
||||
|
||||
function proceedToUnlockConfirm() {
|
||||
if (!unlockPendingCode) return;
|
||||
const btn = document.getElementById("unlock-confirm-btn");
|
||||
btn.disabled = false;
|
||||
btn.textContent = unlockChoice.mode === "shared"
|
||||
? ("确认用 " + (unlockChoice.owner_display || "对方") + " 的共享开锁")
|
||||
: "确认开锁";
|
||||
// 开锁前预览:月卡余量 + 自动续租轮次预估(共享单用车主的卡)
|
||||
loadUnlockPreview(unlockPendingCode,
|
||||
unlockChoice.mode === "shared" ? unlockChoice.owner_user_id : null);
|
||||
document.getElementById("unlock-confirm-modal").classList.add("show");
|
||||
}
|
||||
|
||||
function closeUnlockConfirm() {
|
||||
document.getElementById("unlock-confirm-modal").classList.remove("show");
|
||||
unlockPendingCode = null;
|
||||
unlockPendingPosition = null;
|
||||
}
|
||||
|
||||
async function doUnlockBike() {
|
||||
if (!unlockPendingCode || !authToken) {
|
||||
closeUnlockConfirm();
|
||||
return;
|
||||
}
|
||||
|
||||
const btn = document.getElementById("unlock-confirm-btn");
|
||||
btn.disabled = true;
|
||||
btn.textContent = "开锁中...";
|
||||
const isShared = unlockChoice && unlockChoice.mode === "shared";
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
code: unlockPendingCode,
|
||||
latitude: unlockPendingPosition.lat,
|
||||
longitude: unlockPendingPosition.lng
|
||||
};
|
||||
if (isShared) payload.owner_user_id = unlockChoice.owner_user_id;
|
||||
|
||||
const resp = await apiFetch(isShared ? "/api/order/shared_unlock" : "/api/order/unlock", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await resp.json();
|
||||
console.log("[开锁] 响应:", data);
|
||||
|
||||
closeUnlockConfirm();
|
||||
|
||||
if (data.rtn_code === 0) {
|
||||
showToast(data.message || "开锁成功!");
|
||||
closeQrModal();
|
||||
|
||||
if (isShared) {
|
||||
// 共享开锁:横幅由后端订单状态驱动,不启动本地计时
|
||||
refreshShareBanners();
|
||||
checkOrderStatus();
|
||||
} else {
|
||||
// 启动前端计时器;end_time/轮次预估取自后端开锁响应
|
||||
const _ud = data.data || {};
|
||||
startRentalFromServer(data.order_id, unlockPendingCode, 19,
|
||||
_ud.end_time, _ud);
|
||||
// 刷新订单状态
|
||||
checkOrderStatus();
|
||||
}
|
||||
} else if (data.need_pay) {
|
||||
// 未支付订单月卡也付不了 → 提示用户并刷新订单横幅
|
||||
showToast(data.message || "存在未支付订单,请先支付");
|
||||
checkOrderStatus(); // 刷新横幅显示待支付
|
||||
} else {
|
||||
showToast(data.message || "开锁失败");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[开锁] 请求失败:", err);
|
||||
showToast("开锁失败,请重试");
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = isShared ? "确认共享开锁" : "确认开锁";
|
||||
unlockPendingCode = null;
|
||||
unlockPendingPosition = null;
|
||||
unlockChoice = { mode: "own", owner_user_id: null, owner_email: null };
|
||||
}
|
||||
}
|
||||
|
||||
async function quickUnlock(code, latitude, longitude) {
|
||||
if (!authToken) {
|
||||
showToast("请先登录");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await apiFetch("/api/order/unlock", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
code: code,
|
||||
latitude: latitude,
|
||||
longitude: longitude
|
||||
})
|
||||
});
|
||||
const data = await resp.json();
|
||||
console.log("[开锁] 响应:", data); // 调试日志
|
||||
|
||||
if (data.rtn_code === 0) {
|
||||
showToast(data.message || "开锁成功!");
|
||||
closeQrModal();
|
||||
|
||||
// 启动前端计时器;end_time/轮次预估取自后端开锁响应
|
||||
const _qd = data.data || {};
|
||||
startRentalFromServer(data.order_id, code, 19, _qd.end_time, _qd);
|
||||
|
||||
// 刷新订单状态
|
||||
checkOrderStatus();
|
||||
} else {
|
||||
showToast(data.message || "开锁失败");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[开锁] 请求失败:", err); // 调试日志
|
||||
showToast("开锁失败,请重试");
|
||||
}
|
||||
}
|
||||
|
||||
// 从后端计时器启动前端计时器(隐藏横幅,由后端控制邮件通知)
|
||||
function startRentalFromServer(rentalId, bikeCode, durationMinutes, endTime, summary) {
|
||||
// 启动本地计时器(不显示横幅,由后端统一管理)
|
||||
const remaining = durationMinutes * 60;
|
||||
activeRental = {
|
||||
rental_id: rentalId,
|
||||
bike_code: bikeCode,
|
||||
remaining_seconds: remaining,
|
||||
source: "unlock", // 网页开锁 → 真实订单,+1轮可用
|
||||
end_time: endTime || null,
|
||||
final_end_time: (summary && summary.final_end_time) || endTime || null,
|
||||
current_round: (summary && summary.current_round) || 1,
|
||||
total_rounds: (summary && summary.total_rounds) || null,
|
||||
auto_return: true
|
||||
};
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
|
||||
// 启动倒计时更新(每秒)
|
||||
if (rentalCountdownTimer) clearInterval(rentalCountdownTimer);
|
||||
rentalCountdownTimer = setInterval(() => {
|
||||
if (activeRental && activeRental.remaining_seconds > 0) {
|
||||
activeRental.remaining_seconds--;
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
|
||||
// 到期动作由后端依据订单类型及用户设置执行
|
||||
// 这里不需要做任何操作
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// ========== 开锁前预览(月卡余量 + 轮次预估) ==========
|
||||
function renderUnlockPreview(p) {
|
||||
const box = document.getElementById("unlock-preview");
|
||||
if (!box) return;
|
||||
if (!p) { box.style.display = "none"; box.innerHTML = ""; return; }
|
||||
const lines = [];
|
||||
lines.push(`<div><b style="color:var(--text-primary);">${p.shared ? "共享预览(用车主的卡与轮次)" : "本次用车预览"}</b></div>`);
|
||||
if (p.has_card) {
|
||||
const cardText = (p.cards || []).slice(0, 3).map(c =>
|
||||
`${escHtml(c.name)}${c.remain === null ? "(不限次)" : ` 剩 ${c.remain} 次`}`).join(",");
|
||||
lines.push(`<div>优惠卡:${cardText}${p.card_note ? ` · ${escHtml(p.card_note)}` : ""}</div>`);
|
||||
} else {
|
||||
lines.push(`<div style="color:#c62828;">未检测到优惠卡:本次费用将按小程序计费(还车后需支付)</div>`);
|
||||
}
|
||||
if (p.auto_return) {
|
||||
lines.push(`<div>自动续租:计划 ${p.rounds_planned} 轮 × ${p.duration_minutes} 分钟,预计 ${escHtml(p.est_end_time)} 前还车</div>`);
|
||||
} else {
|
||||
lines.push(`<div>自动还车未开启:本轮 ${p.duration_minutes} 分钟,请留意到期手动还车</div>`);
|
||||
}
|
||||
box.innerHTML = lines.join("");
|
||||
box.style.display = "block";
|
||||
}
|
||||
async function loadUnlockPreview(code, ownerUserId) {
|
||||
const box = document.getElementById("unlock-preview");
|
||||
if (box) { box.style.display = "block"; box.innerHTML = '<div style="color:var(--text-secondary);">预览加载中...</div>'; }
|
||||
try {
|
||||
const q = new URLSearchParams({ code: String(code) });
|
||||
if (ownerUserId) q.set("owner_user_id", ownerUserId);
|
||||
const resp = await apiFetch(`/api/order/preview?${q.toString()}`, {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
});
|
||||
const data = await resp.json();
|
||||
renderUnlockPreview(data.rtn_code === 0 ? data.data : null);
|
||||
} catch (err) {
|
||||
renderUnlockPreview(null);
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 手动 +1 轮 ==========
|
||||
// ========== 手动 +1 轮(带确认弹窗) ==========
|
||||
// 语义:只把「计划轮数」+1。当前这一轮照常到点 → 自动还车 → 优惠卡支付
|
||||
// → 立刻重新开锁同一辆车进入下一轮(绝不延长本轮时长)。
|
||||
let _addRoundTarget = null;
|
||||
function showAddRoundConfirm(target) {
|
||||
_addRoundTarget = target;
|
||||
const remainSec = target.kind === "rental"
|
||||
? (activeRental && activeRental.remaining_seconds) || orderCountdownSeconds || 0
|
||||
: orderCountdownSeconds || 0;
|
||||
const mins = Math.max(1, Math.round(remainSec / 60));
|
||||
const btn = document.getElementById("add-round-confirm-btn");
|
||||
if (btn) { btn.disabled = false; btn.textContent = "确认加 1 轮"; }
|
||||
const text = document.getElementById("add-round-text");
|
||||
if (text) {
|
||||
text.innerHTML =
|
||||
`当前这一轮还剩约 <b>${mins} 分钟</b>,<b>不会延长</b>。<br/>` +
|
||||
`到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`;
|
||||
}
|
||||
document.getElementById("add-round-modal").classList.add("show");
|
||||
}
|
||||
function closeAddRoundModal() {
|
||||
document.getElementById("add-round-modal").classList.remove("show");
|
||||
_addRoundTarget = null;
|
||||
}
|
||||
async function confirmAddRound() {
|
||||
if (!_addRoundTarget || !authToken) { closeAddRoundModal(); return; }
|
||||
const btn = document.getElementById("add-round-confirm-btn");
|
||||
if (btn) { btn.disabled = true; btn.textContent = "提交中..."; }
|
||||
const payload = _addRoundTarget.kind === "rental"
|
||||
? { rental_id: _addRoundTarget.value }
|
||||
: { order_id: _addRoundTarget.value };
|
||||
try {
|
||||
const resp = await apiFetch("/api/order/add_round", {
|
||||
method: "POST",
|
||||
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code === 0) {
|
||||
showToast(data.message || "已加 1 轮");
|
||||
// 本轮剩余不变,只更新计划轮数与预计还车时间
|
||||
if (activeRental) {
|
||||
activeRental.total_rounds = data.data.total_rounds;
|
||||
activeRental.final_end_time = data.data.final_end_time;
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
updateRentalFinalTime();
|
||||
}
|
||||
if (currentOrder && currentOrder.order_id) fetchOrderCountdown(currentOrder.order_id);
|
||||
checkOrderStatus();
|
||||
} else {
|
||||
showToast(data.message || "加轮失败");
|
||||
}
|
||||
} catch (err) {
|
||||
showToast("网络错误,请重试");
|
||||
} finally {
|
||||
closeAddRoundModal();
|
||||
}
|
||||
}
|
||||
function addRoundForCurrent() {
|
||||
if (!activeRental || !authToken) { showToast("当前没有进行中的订单"); return; }
|
||||
showAddRoundConfirm({ kind: "rental", value: activeRental.rental_id });
|
||||
}
|
||||
function addRoundFromBanner() {
|
||||
if (!currentOrder || !currentOrder.order_id) { showToast("当前没有进行中的订单"); return; }
|
||||
showAddRoundConfirm({ kind: "order", value: currentOrder.order_id });
|
||||
}
|
||||
// 页面加载时检查订单状态和租车状态
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
if (authToken) {
|
||||
await syncWechatOrder(); // 先同步微信订单状态
|
||||
checkOrderStatus();
|
||||
checkRentalStatus(); // 再恢复租车横幅
|
||||
checkStrictGuide(); // 强签名验证:缺 AccessToken 进页面立即引导
|
||||
refreshAuthExpiry(); // 登录态有效期:不足 2 天在主页面挂提醒横幅
|
||||
}
|
||||
});
|
||||
@@ -1,499 +0,0 @@
|
||||
// ========== 用车计时相关 ==========
|
||||
function clearRentalState() {
|
||||
if (rentalCountdownTimer) {
|
||||
clearInterval(rentalCountdownTimer);
|
||||
rentalCountdownTimer = null;
|
||||
}
|
||||
activeRental = null;
|
||||
localStorage.removeItem(RENTAL_KEY);
|
||||
const bar = document.getElementById("rental-bar");
|
||||
if (bar) bar.classList.remove("show");
|
||||
}
|
||||
|
||||
async function openRentalSettingsModal() {
|
||||
closeAllModals();
|
||||
SettingsPages.open("rental-settings-modal");
|
||||
try {
|
||||
const resp = await apiFetch("/api/auth/rental_settings", {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
});
|
||||
const result = await resp.json();
|
||||
if (result.rtn_code !== 0) throw new Error(result.message || "加载失败");
|
||||
const settings = result.data;
|
||||
document.getElementById("rs-reminder-enabled").checked = !!settings.reminder_enabled;
|
||||
document.getElementById("rs-duration").value = settings.rental_duration_minutes || 19;
|
||||
document.getElementById("rs-auto-return").checked = !!settings.auto_return_enabled;
|
||||
document.getElementById("rs-rounds").value = settings.rental_rounds || 1;
|
||||
document.getElementById("rs-protect-card").checked = settings.protect_card !== false;
|
||||
const selected = new Set((settings.reminder_minutes || []).map(String));
|
||||
document.querySelectorAll("#rs-minute-options input").forEach(el => el.checked = selected.has(el.value));
|
||||
} catch (err) {
|
||||
showToast("设置加载失败:" + friendlyError(err));
|
||||
}
|
||||
}
|
||||
|
||||
function closeRentalSettingsModal() { SettingsPages.back(); }
|
||||
|
||||
async function saveRentalSettings() {
|
||||
const reminderMinutes = [...document.querySelectorAll("#rs-minute-options input:checked")].map(el => Number(el.value));
|
||||
const payload = {
|
||||
reminder_enabled: document.getElementById("rs-reminder-enabled").checked,
|
||||
reminder_minutes: reminderMinutes,
|
||||
rental_duration_minutes: Number(document.getElementById("rs-duration").value),
|
||||
auto_return_enabled: document.getElementById("rs-auto-return").checked,
|
||||
rental_rounds: Number(document.getElementById("rs-rounds").value),
|
||||
protect_card: document.getElementById("rs-protect-card").checked
|
||||
};
|
||||
try {
|
||||
const resp = await apiFetch("/api/auth/rental_settings", {
|
||||
method: "POST",
|
||||
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const result = await resp.json();
|
||||
if (result.rtn_code !== 0) throw new Error(result.message || "保存失败");
|
||||
closeRentalSettingsModal();
|
||||
showToast("用车设置已保存");
|
||||
} catch (err) {
|
||||
showToast("保存失败:" + friendlyError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function syncWechatOrder() {
|
||||
if (!authToken) return;
|
||||
try {
|
||||
const resp = await apiFetch("/api/rental/sync", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
});
|
||||
const data = await resp.json();
|
||||
console.log("[syncWechatOrder] 同步结果:", data);
|
||||
if (data.rtn_code === 0 && data.data && data.data.active && data.data.source === "reminder") {
|
||||
const r = data.data;
|
||||
activeRental = {
|
||||
rental_id: r.rental_id,
|
||||
bike_code: r.bike_code,
|
||||
end_time: r.end_time,
|
||||
source: r.source || "reminder",
|
||||
remaining_seconds: r.remaining_seconds
|
||||
};
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
} else if (data.rtn_code === 0 && data.data) {
|
||||
// 真实订单走订单横幅(checkOrderStatus / fetchOrderCountdown 驱动),
|
||||
// 本地计时条只承载 reminder 计时
|
||||
clearRentalState();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[syncWechatOrder] 同步失败:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function checkRentalStatus() {
|
||||
// 已登录才查询
|
||||
if (!authToken) {
|
||||
console.log("[checkRentalStatus] 无token,跳过");
|
||||
return;
|
||||
}
|
||||
|
||||
apiFetch("/api/rental/status", {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
console.log("[checkRentalStatus] 响应:", data);
|
||||
if (data.rtn_code === 0 && data.data && data.data.active) {
|
||||
const r = data.data;
|
||||
|
||||
// 剩余时间 <= 0 也视为无活跃
|
||||
if (r.remaining_seconds <= 0) {
|
||||
clearRentalState();
|
||||
return;
|
||||
}
|
||||
|
||||
// 既然后端已按用户过滤,有记录就直接显示状态栏
|
||||
activeRental = {
|
||||
rental_id: r.rental_id,
|
||||
order_id: r.order_id || null,
|
||||
bike_code: r.bike_code,
|
||||
email: r.email,
|
||||
end_time: r.end_time,
|
||||
final_end_time: r.final_end_time || null,
|
||||
current_round: r.current_round || 1,
|
||||
total_rounds: r.total_rounds || null,
|
||||
source: r.source || null,
|
||||
remaining_seconds: r.remaining_seconds
|
||||
};
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
showRentalBar();
|
||||
} else {
|
||||
// 无活跃租车,清空
|
||||
console.log("[checkRentalStatus] 无活跃租车");
|
||||
clearRentalState();
|
||||
}
|
||||
})
|
||||
.catch(err => console.error("检查租车状态失败:", err));
|
||||
}
|
||||
|
||||
function startRental(bikeCode) {
|
||||
// 先显示二维码,用户体验更好
|
||||
showQrModal(bikeCode);
|
||||
closeCard();
|
||||
|
||||
console.log("[startRental] authToken:", authToken, "currentUser:", currentUser);
|
||||
|
||||
if (!currentUser) {
|
||||
showToast("登录后可开启用车计时提醒");
|
||||
return;
|
||||
}
|
||||
|
||||
// 调后端开启计时
|
||||
apiFetch("/api/rental/start", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${authToken}`
|
||||
},
|
||||
body: JSON.stringify({ bike_code: bikeCode })
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.rtn_code === 0) {
|
||||
const now = new Date();
|
||||
const endTime = new Date(now.getTime() + data.data.remaining_seconds * 1000);
|
||||
activeRental = {
|
||||
rental_id: data.data.rental_id,
|
||||
bike_code: bikeCode,
|
||||
email: currentUser.email,
|
||||
remaining_seconds: data.data.remaining_seconds,
|
||||
end_time: endTime.toISOString().slice(0, 19).replace('T', ' ')
|
||||
};
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
showRentalBar();
|
||||
showToast("提醒计时已开始;未绑定微信订单,请到期前手动还车");
|
||||
} else {
|
||||
showToast(data.message || "计时启动失败");
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
showToast("计时未开启,请检查网络");
|
||||
console.error("启动计时失败:", err);
|
||||
});
|
||||
}
|
||||
|
||||
function showRentalBar() {
|
||||
if (!activeRental) return;
|
||||
const bar = document.getElementById("rental-bar");
|
||||
document.getElementById("rental-bike-code").textContent = `#${activeRental.bike_code}`;
|
||||
// +1轮 按钮仅对真实微信订单展示(reminder 计时不支持)
|
||||
const addBtn = document.getElementById("rental-add-round-btn");
|
||||
if (addBtn) {
|
||||
const realOrder = activeRental.source ? activeRental.source !== "reminder"
|
||||
: !!activeRental.order_id;
|
||||
addBtn.style.display = realOrder ? "inline-flex" : "none";
|
||||
}
|
||||
updateRentalFinalTime();
|
||||
bar.classList.add("show");
|
||||
updateRentalCountdown();
|
||||
// 每秒更新倒计时
|
||||
if (rentalCountdownTimer) clearInterval(rentalCountdownTimer);
|
||||
rentalCountdownTimer = setInterval(updateRentalCountdown, 1000);
|
||||
}
|
||||
|
||||
function updateRentalFinalTime() {
|
||||
const el = document.getElementById("rental-final-time");
|
||||
if (!el) return;
|
||||
if (activeRental && activeRental.final_end_time) {
|
||||
const hhmm = String(activeRental.final_end_time).slice(11, 16);
|
||||
const total = activeRental.total_rounds || activeRental.rounds_planned;
|
||||
el.textContent = total ? ` · 共${total}轮 预计${hhmm}还车` : ` · 预计${hhmm}还车`;
|
||||
el.style.display = "inline";
|
||||
} else {
|
||||
el.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
function updateRentalCountdown() {
|
||||
if (!activeRental) return;
|
||||
const el = document.getElementById("rental-time");
|
||||
const remaining = Math.max(0, activeRental.remaining_seconds - 1);
|
||||
activeRental.remaining_seconds = remaining;
|
||||
localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental));
|
||||
|
||||
const mins = Math.floor(remaining / 60);
|
||||
const secs = remaining % 60;
|
||||
el.textContent = `${mins}:${secs.toString().padStart(2, "0")}`;
|
||||
|
||||
// 变色提示
|
||||
if (remaining <= 60) {
|
||||
el.style.color = "#ff3b30";
|
||||
} else if (remaining <= 300) {
|
||||
el.style.color = "#ff9f0a";
|
||||
} else {
|
||||
el.style.color = "white";
|
||||
}
|
||||
|
||||
if (remaining <= 0) {
|
||||
clearInterval(rentalCountdownTimer);
|
||||
// 超时后每分钟查一次后端确认状态
|
||||
rentalCountdownTimer = setInterval(checkRentalStatus, 60000);
|
||||
}
|
||||
}
|
||||
|
||||
function showReturnModal() {
|
||||
if (!activeRental) return;
|
||||
document.getElementById("return-bike-code").textContent = `#${activeRental.bike_code}`;
|
||||
document.getElementById("return-modal").classList.add("show");
|
||||
}
|
||||
|
||||
function closeReturnModal() {
|
||||
document.getElementById("return-modal").classList.remove("show");
|
||||
}
|
||||
|
||||
async function confirmReturn() {
|
||||
closeReturnModal();
|
||||
if (!activeRental) return;
|
||||
|
||||
try {
|
||||
const response = await apiFetch("/api/rental/return", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${authToken}`
|
||||
},
|
||||
body: JSON.stringify({ rental_id: activeRental.rental_id })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
// 只有后端返回成功才清除本地状态
|
||||
if (data.rtn_code === 0) {
|
||||
clearRentalState();
|
||||
showToast("已确认还车,祝您使用愉快!");
|
||||
} else {
|
||||
// 后端返回错误,保持本地状态,提示用户
|
||||
showToast(data.message || "还车失败,请重试");
|
||||
console.error("还车失败:", data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("确认还车失败:", err);
|
||||
showToast("网络错误,请检查网络后重试");
|
||||
}
|
||||
}
|
||||
|
||||
// 原生壳(Android)判定:UA 由 Android WebView 注入 xbniu-native,head 脚本已给 <html> 加 in-native-shell
|
||||
function isNativeShell() {
|
||||
return document.documentElement && document.documentElement.classList.contains('in-native-shell');
|
||||
}
|
||||
// 网页点“开锁用车”时,把开锁交给安卓原生(原生里选账号/共享并开锁);返回 true 表示已交给原生
|
||||
function nativeUnlockBike(code) {
|
||||
try {
|
||||
if (isNativeShell() && window.xbniuAndroid && typeof window.xbniuAndroid.unlock === 'function') {
|
||||
window.xbniuAndroid.unlock(String(code));
|
||||
return true;
|
||||
}
|
||||
} catch (e) { console.error("[原生桥] 调用失败:", e); }
|
||||
return false;
|
||||
}
|
||||
|
||||
function unlockBike() {
|
||||
if (!selectedBike) return;
|
||||
|
||||
// 检查车辆状态
|
||||
const bikeState = getBikeState(selectedBike);
|
||||
if (bikeState === 'inuse') {
|
||||
showToast("该车正在使用中,请稍后再试");
|
||||
closeCard();
|
||||
return;
|
||||
}
|
||||
if (bikeState === 'locked') {
|
||||
showToast("该车已锁定,无法使用");
|
||||
closeCard();
|
||||
return;
|
||||
}
|
||||
if (bikeState === 'reserved') {
|
||||
showToast("该车已被预约");
|
||||
closeCard();
|
||||
return;
|
||||
}
|
||||
|
||||
// 原生壳:点击即交给安卓原生开锁(账号选择在原生 BikeDetailActivity),不在此出网页二维码
|
||||
if (nativeUnlockBike(selectedBike.code)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 网页端默认:显示二维码弹窗(长按二维码才开始计时)
|
||||
showQrModal(selectedBike.code);
|
||||
}
|
||||
|
||||
// 显示二维码弹窗(适配微信扫码 - img格式)
|
||||
let currentQrPosition = null; // 当前二维码对应的位置
|
||||
|
||||
function showQrModal(code) {
|
||||
const modal = document.getElementById("qr-modal");
|
||||
const qrBox = document.getElementById("qrcode-box");
|
||||
const quickBtn = document.getElementById("quick-unlock-btn");
|
||||
|
||||
// 清空旧的二维码
|
||||
qrBox.innerHTML = "";
|
||||
|
||||
// 获取当前位置
|
||||
currentQrPosition = null;
|
||||
if (navigator.geolocation) {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
pos => {
|
||||
currentQrPosition = {
|
||||
lat: pos.coords.latitude,
|
||||
lng: pos.coords.longitude
|
||||
};
|
||||
},
|
||||
err => console.error("获取位置失败:", err),
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
}
|
||||
|
||||
// 生成新二维码
|
||||
const url = "http://bike.sdlongren.com/bicycle?code=" + code;
|
||||
|
||||
// 判断暗色模式
|
||||
const isDark = UIPreferences.isDark();
|
||||
const dark = isDark ? '#ffffff' : '#000000';
|
||||
const light = isDark ? '#1a1a1a' : '#ffffff';
|
||||
|
||||
// 生成 img 格式二维码(参考 xbcr.html)
|
||||
createQrImage(url, dark, light, function(dataUrl) {
|
||||
qrBox.innerHTML = ""; // 清空旧内容
|
||||
if (!dataUrl) {
|
||||
// 二维码库不可用:明确告知并保留一键开锁入口,避免“点了没反应”
|
||||
qrBox.innerHTML = '<div style="padding:30px 10px;color:var(--text-secondary);font-size:13px;">二维码生成组件加载失败,<br/>可直接使用下方一键开锁。</div>';
|
||||
modal.classList.add("show");
|
||||
quickBtn.style.display = (authToken && currentUser) ? "block" : "none";
|
||||
showToast("二维码组件加载失败,可一键开锁");
|
||||
return;
|
||||
}
|
||||
const img = document.createElement('img');
|
||||
img.src = dataUrl;
|
||||
img.alt = '用车二维码';
|
||||
img.style.cssText = 'width:160px;height:160px;border-radius:4px;box-shadow:rgba(0,0,0,0.4) 2px 2px 8px;display:block;';
|
||||
qrBox.appendChild(img);
|
||||
qrBox.dataset.bikeCode = code; // 存车牌,长按时用
|
||||
modal.classList.add("show");
|
||||
|
||||
// 如果用户已登录,显示一键开锁按钮
|
||||
if (authToken && currentUser) {
|
||||
quickBtn.style.display = "block";
|
||||
} else {
|
||||
quickBtn.style.display = "none";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 生成高质量二维码图片(img格式,适配微信长按识别)
|
||||
function createQrImage(text, dark, light, callback) {
|
||||
const size = 160;
|
||||
const padding = 20;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = canvas.height = size + padding * 2;
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// 白色背景
|
||||
ctx.fillStyle = light;
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
// 生成二维码到临时容器
|
||||
const tmp = document.createElement('div');
|
||||
tmp.style.display = 'none';
|
||||
document.body.appendChild(tmp);
|
||||
|
||||
// qrcodejs 加载失败时(如外链 CDN 不可达)给出明确提示,而不是无声无息
|
||||
if (typeof QRCode === "undefined") {
|
||||
document.body.removeChild(tmp);
|
||||
callback(null);
|
||||
return;
|
||||
}
|
||||
|
||||
new QRCode(tmp, {
|
||||
text: text,
|
||||
width: size,
|
||||
height: size,
|
||||
colorDark: dark,
|
||||
colorLight: light,
|
||||
correctLevel: QRCode.CorrectLevel.L
|
||||
});
|
||||
|
||||
// 从临时容器提取 canvas 并画到带padding的画布上
|
||||
setTimeout(function() {
|
||||
var qrCanvas = tmp.querySelector('canvas');
|
||||
if (qrCanvas) {
|
||||
ctx.drawImage(qrCanvas, padding, padding);
|
||||
}
|
||||
document.body.removeChild(tmp);
|
||||
callback(qrCanvas ? canvas.toDataURL('image/png', 1) : null);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// 关闭二维码弹窗
|
||||
function closeQrModal() {
|
||||
document.getElementById("qr-modal").classList.remove("show");
|
||||
document.getElementById("quick-unlock-btn").style.display = "none";
|
||||
// 清除长按定时器
|
||||
longPressTimer = null;
|
||||
longPressTarget = null;
|
||||
currentQrPosition = null;
|
||||
}
|
||||
|
||||
// 长按检测变量
|
||||
let longPressTimer = null;
|
||||
let longPressTarget = null;
|
||||
let qrModalBikeCode = null; // 当前二维码对应的车牌
|
||||
|
||||
// 二维码弹窗的二维码区域长按检测
|
||||
function setupQrLongPress() {
|
||||
const qrBox = document.getElementById("qrcode-box");
|
||||
|
||||
// 统一用 pointer 事件(兼容触摸和鼠标)
|
||||
qrBox.addEventListener("pointerdown", function(e) {
|
||||
if (!currentUser) return;
|
||||
e.preventDefault(); // 阻止右键菜单等默认行为
|
||||
qrModalBikeCode = qrBox.dataset.bikeCode || "";
|
||||
longPressTimer = setTimeout(() => {
|
||||
longPressTimer = null;
|
||||
if (qrModalBikeCode && currentUser) {
|
||||
// 视觉反馈
|
||||
qrBox.style.backgroundColor = "rgba(52,199,89,0.2)";
|
||||
setTimeout(() => { qrBox.style.backgroundColor = "white"; }, 500);
|
||||
startRental(qrModalBikeCode);
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
|
||||
qrBox.addEventListener("pointerup", function(e) {
|
||||
if (longPressTimer) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
}
|
||||
});
|
||||
|
||||
qrBox.addEventListener("pointerleave", function(e) {
|
||||
if (longPressTimer) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
}
|
||||
});
|
||||
|
||||
qrBox.addEventListener("pointercancel", function(e) {
|
||||
if (longPressTimer) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 页面加载时初始化长按检测
|
||||
setupQrLongPress();
|
||||
|
||||
// 点击遮罩关闭
|
||||
document.getElementById("qr-modal").addEventListener("click", function(e) {
|
||||
if (e.target === this) closeQrModal();
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
// ========== 订阅提醒(编辑、复制与最近执行结果) ==========
|
||||
let subscribeLocations = [], subscribeRuleCache = [], subscribeEditId = null;
|
||||
const SUB_WEEKDAYS = {0:"每天",1:"周一",2:"周二",3:"周三",4:"周四",5:"周五",6:"周六",7:"周日"};
|
||||
async function openSubscribeModal() {
|
||||
closeAllModals(); SettingsPages.open("subscribe-modal");
|
||||
await loadSubscribeLocations(); resetSubscribeEditor(); await loadSubscribeRules();
|
||||
}
|
||||
function closeSubscribeModal() { SettingsPages.back(); }
|
||||
async function loadSubscribeLocations() {
|
||||
const select = document.getElementById("sub-location");
|
||||
try {
|
||||
const response = await apiFetch("/api/campus/locations"); const data = await response.json();
|
||||
subscribeLocations = (data.data || []).filter(p => p.kind === "parking");
|
||||
select.innerHTML = subscribeLocations.length ? subscribeLocations.map(p => `<option value="${p.id}">${escHtml(p.name)}</option>`).join("") : '<option value="">管理员尚未配置停车点</option>';
|
||||
} catch (error) { select.innerHTML = '<option value="">加载失败,请返回后重试</option>'; }
|
||||
}
|
||||
function subRuleRowHtml(rule) {
|
||||
const time = `${String(Math.floor(rule.minute_of_day / 60)).padStart(2,"0")}:${String(rule.minute_of_day % 60).padStart(2,"0")}`;
|
||||
const status = {success:"执行成功", failed:"执行失败", no_match:"没有符合条件的车辆", running:"执行中"}[rule.last_run_status] || "尚未执行";
|
||||
return `<article class="sub-rule"><div class="sub-rule-head"><strong>${escHtml(rule.location_name || "停车点已删除")}</strong><span>${SUB_WEEKDAYS[rule.weekday]} ${time}</span></div><div class="sub-rule-meta">${rule.enabled ? "已启用" : "已停用"} · ${(rule.kind_labels || []).join("/")} · 电量 ${rule.min_electric}-${rule.max_electric}% · ${rule.auto_unlock ? "自动开锁" : "仅提醒"}</div><div class="sub-rule-result">${status}${rule.last_run_at ? " · " + escHtml(rule.last_run_at) : ""}${rule.last_run_message ? "<br>" + escHtml(rule.last_run_message) : ""}</div><div class="sub-rule-actions"><button onclick="editSubscribeRule(${rule.id},false)">编辑</button><button onclick="editSubscribeRule(${rule.id},true)">复制</button><button onclick="toggleSubscribeRule(${rule.id},${rule.enabled ? 0 : 1})">${rule.enabled ? "停用" : "启用"}</button><button class="danger" onclick="deleteSubscribeRule(${rule.id})">删除</button></div></article>`;
|
||||
}
|
||||
async function loadSubscribeRules() {
|
||||
const box = document.getElementById("subscribe-list");
|
||||
box.innerHTML = '<div class="device-loading">正在加载订阅...</div>';
|
||||
try {
|
||||
const response = await apiFetch("/api/subscribe/rules", {headers:{Authorization:`Bearer ${authToken}`}}); const data = await response.json();
|
||||
if (data.rtn_code !== 0) throw new Error(data.message || "加载失败");
|
||||
subscribeRuleCache = data.data || [];
|
||||
box.innerHTML = subscribeRuleCache.length ? subscribeRuleCache.map(subRuleRowHtml).join("") : '<div class="device-loading">暂无订阅,可以在下方添加停车点和用车时间。</div>';
|
||||
} catch (error) { box.innerHTML = `<div class="device-loading">${escHtml(error.message)},请返回后重试。</div>`; }
|
||||
}
|
||||
function toggleSubAdvanced() { const box = document.getElementById("sub-advanced"); box.style.display = box.style.display === "none" ? "block" : "none"; }
|
||||
function resetSubscribeEditor() {
|
||||
subscribeEditId = null;
|
||||
document.getElementById("sub-editor-title").textContent = "新增规则";
|
||||
document.getElementById("sub-save").textContent = "添加规则";
|
||||
document.getElementById("sub-cancel-edit").hidden = true;
|
||||
document.getElementById("sub-weekday").value = "0";
|
||||
document.getElementById("sub-time").value = "11:55";
|
||||
document.getElementById("sub-notify").checked = true;
|
||||
document.getElementById("sub-auto").checked = false;
|
||||
document.getElementById("sub-min-e").value = 0;
|
||||
document.getElementById("sub-max-e").value = 100;
|
||||
document.getElementById("sub-sort").value = "electric_desc";
|
||||
document.getElementById("sub-retry").value = 3;
|
||||
document.querySelectorAll(".sub-kind").forEach(el => el.checked = true);
|
||||
}
|
||||
function editSubscribeRule(id, copy) {
|
||||
const rule = subscribeRuleCache.find(r => r.id === id); if (!rule) return;
|
||||
subscribeEditId = copy ? null : id;
|
||||
document.getElementById("sub-editor-title").textContent = copy ? "复制规则(保存后新增)" : "编辑规则";
|
||||
document.getElementById("sub-save").textContent = copy ? "添加副本" : "保存修改";
|
||||
document.getElementById("sub-cancel-edit").hidden = false;
|
||||
document.getElementById("sub-location").value = rule.location_id;
|
||||
document.getElementById("sub-weekday").value = rule.weekday;
|
||||
document.getElementById("sub-time").value = `${String(Math.floor(rule.minute_of_day / 60)).padStart(2,"0")}:${String(rule.minute_of_day % 60).padStart(2,"0")}`;
|
||||
document.getElementById("sub-notify").checked = rule.notify_enabled;
|
||||
document.getElementById("sub-auto").checked = rule.auto_unlock;
|
||||
document.getElementById("sub-min-e").value = rule.min_electric;
|
||||
document.getElementById("sub-max-e").value = rule.max_electric;
|
||||
document.getElementById("sub-sort").value = rule.sort_by;
|
||||
document.getElementById("sub-retry").value = rule.retry_times;
|
||||
document.querySelectorAll(".sub-kind").forEach(el => el.checked = rule.kinds.includes(el.value));
|
||||
document.getElementById("sub-advanced").style.display = "block";
|
||||
document.getElementById("sub-time").focus({preventScroll:true});
|
||||
document.getElementById("sub-editor-title").scrollIntoView({block:"nearest"});
|
||||
}
|
||||
async function addSubscribeRule() {
|
||||
return AppAPI.run("subscription-save", document.getElementById("sub-save"), async () => {
|
||||
const payload = {location_id:Number(document.getElementById("sub-location").value), weekday:Number(document.getElementById("sub-weekday").value), time:document.getElementById("sub-time").value,
|
||||
notify_enabled:document.getElementById("sub-notify").checked, auto_unlock:document.getElementById("sub-auto").checked,
|
||||
kinds:[...document.querySelectorAll(".sub-kind:checked")].map(el => el.value), min_electric:Number(document.getElementById("sub-min-e").value), max_electric:Number(document.getElementById("sub-max-e").value), sort_by:document.getElementById("sub-sort").value, retry_times:Number(document.getElementById("sub-retry").value)};
|
||||
if (!payload.location_id || !payload.time || !payload.kinds.length) { showToast("请选择停车点、时间和至少一种车型"); return; }
|
||||
if (payload.min_electric < 0 || payload.max_electric > 100 || payload.min_electric > payload.max_electric) { showToast("电量区间应在0-100且下限不高于上限"); return; }
|
||||
if (!payload.notify_enabled && !payload.auto_unlock) { showToast("请至少开启邮件提醒或自动开锁"); return; }
|
||||
if (payload.auto_unlock && !await appConfirm("命中规则后将使用当前账号真实开锁车辆。请核对停车点、时间与筛选条件。", {title:"确认自动开锁规则",okText:subscribeEditId ? "确认保存" : "确认添加"})) return;
|
||||
try {
|
||||
const response = await apiFetch(subscribeEditId ? `/api/subscribe/rules/${subscribeEditId}` : "/api/subscribe/rules", {method:subscribeEditId ? "PUT" : "POST", headers:{Authorization:`Bearer ${authToken}`,"Content-Type":"application/json"},body:JSON.stringify(payload)});
|
||||
const data = await response.json(); if (data.rtn_code !== 0) throw new Error(data.message || "保存失败");
|
||||
resetSubscribeEditor(); await loadSubscribeRules(); showToast("订阅规则已保存");
|
||||
} catch (error) { showToast(error.message || "保存失败,请重试"); }
|
||||
});
|
||||
}
|
||||
async function toggleSubscribeRule(id, enabled) {
|
||||
return AppAPI.run(`subscription-${id}`, null, async () => {
|
||||
try { const response = await apiFetch(`/api/subscribe/rules/${id}`, {method:"PUT",headers:{Authorization:`Bearer ${authToken}`,"Content-Type":"application/json"},body:JSON.stringify({enabled:!!enabled})}); const data = await response.json(); if (data.rtn_code !== 0) throw new Error(data.message); await loadSubscribeRules(); }
|
||||
catch (error) { showToast(error.message || "操作失败"); }
|
||||
});
|
||||
}
|
||||
async function deleteSubscribeRule(id) {
|
||||
if (!await appConfirm("确定删除这条订阅规则吗?", {title:"删除订阅",okText:"删除"})) return;
|
||||
return AppAPI.run(`subscription-${id}`, null, async () => {
|
||||
try { const response = await apiFetch(`/api/subscribe/rules/${id}`, {method:"DELETE",headers:{Authorization:`Bearer ${authToken}`}}); const data = await response.json(); if (data.rtn_code !== 0) throw new Error(data.message); if (subscribeEditId === id) resetSubscribeEditor(); await loadSubscribeRules(); }
|
||||
catch (error) { showToast(error.message || "删除失败"); }
|
||||
});
|
||||
}
|
||||
@@ -1,458 +0,0 @@
|
||||
// ========== 通用确认弹窗(替换 window.confirm) ==========
|
||||
// 为什么不用 confirm:原生壳是 Android WebView,WebView 默认不弹 JS 原生对话框
|
||||
// (Chromium 需要宿主实现 onJsConfirm,未实现时 confirm 直接返回 false,用户点不到"确认")。
|
||||
// 这里用页面内弹窗,行为一致但任何环境都能用。
|
||||
let _appConfirmResolve = null;
|
||||
function appConfirm(message, opts) {
|
||||
const o = opts || {};
|
||||
const modal = document.getElementById("app-confirm-modal");
|
||||
const titleEl = document.getElementById("app-confirm-title");
|
||||
const textEl = document.getElementById("app-confirm-text");
|
||||
const okBtn = document.getElementById("app-confirm-ok");
|
||||
const cancelBtn = document.getElementById("app-confirm-cancel");
|
||||
if (!modal || !textEl) { // 极老页面兜底
|
||||
return Promise.resolve(window.confirm ? window.confirm(message) : true);
|
||||
}
|
||||
titleEl.textContent = o.title || "确认操作";
|
||||
// 支持换行(保留 \n 的排版)
|
||||
textEl.innerHTML = String(message || "")
|
||||
.split("\n")
|
||||
.map(line => escHtml(line))
|
||||
.join("<br/>");
|
||||
okBtn.textContent = o.okText || "确认";
|
||||
cancelBtn.textContent = o.cancelText || "取消";
|
||||
okBtn.classList.toggle("danger", !!o.danger);
|
||||
|
||||
return new Promise(resolve => {
|
||||
_appConfirmResolve = resolve;
|
||||
const finish = (val) => {
|
||||
modal.classList.remove("show");
|
||||
okBtn.onclick = null;
|
||||
cancelBtn.onclick = null;
|
||||
modal.onclick = null;
|
||||
_appConfirmResolve = null;
|
||||
resolve(val);
|
||||
};
|
||||
okBtn.onclick = (e) => { e.stopPropagation(); finish(true); };
|
||||
cancelBtn.onclick = (e) => { e.stopPropagation(); finish(false); };
|
||||
modal.onclick = (e) => { if (e.target === modal) finish(false); };
|
||||
modal.classList.add("show");
|
||||
});
|
||||
}
|
||||
function appConfirmClose() {
|
||||
if (_appConfirmResolve) {
|
||||
const r = _appConfirmResolve;
|
||||
_appConfirmResolve = null;
|
||||
document.getElementById("app-confirm-modal").classList.remove("show");
|
||||
r(false);
|
||||
}
|
||||
}
|
||||
|
||||
function mapSnapshotNow() {
|
||||
return renderedMapSnapshot
|
||||
? renderedMapSnapshot.serverTime + (performance.now() - renderedMapSnapshot.receivedAt) / 1000
|
||||
: Date.now() / 1000;
|
||||
}
|
||||
|
||||
function updateMapFreshnessBadge() {
|
||||
const el = document.getElementById("update-time");
|
||||
if (!el) return;
|
||||
const stamp = Number(renderedMapSnapshot?.fetched_at);
|
||||
if (renderedMapSnapshot && Number.isFinite(stamp) && renderedMapSnapshot.fetched_at !== null) {
|
||||
el.textContent = new Date(stamp * 1000).toLocaleTimeString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai', hour: '2-digit', minute: '2-digit'
|
||||
});
|
||||
const expired = mapSnapshotNow() >= Number(renderedMapSnapshot.expires_at);
|
||||
el.classList.toggle("stale", expired || mapRefreshFailed);
|
||||
} else if (mapRefreshFailed) {
|
||||
el.textContent = "更新失败";
|
||||
el.classList.add("stale");
|
||||
}
|
||||
el.onclick = showFreshnessDetail;
|
||||
el.style.cursor = "pointer";
|
||||
}
|
||||
|
||||
function updateTime() {
|
||||
if (renderedMapSnapshot) { updateMapFreshnessBadge(); return; }
|
||||
// Compatibility for a server without snapshot metadata; never show client time.
|
||||
apiFetch(`/api/map/freshness?type=${encodeURIComponent(currentType)}`, { cache: "no-store" })
|
||||
.then(r => r.json())
|
||||
.then(result => {
|
||||
if (result.rtn_code !== 0 || !result.data?.latest) return;
|
||||
const el = document.getElementById("update-time");
|
||||
if (!el) return;
|
||||
el.textContent = String(result.data.latest).slice(11, 16);
|
||||
el.classList.toggle("stale", result.data.status === "stale" || result.data.stale_seconds >= 60);
|
||||
el.onclick = showFreshnessDetail;
|
||||
el.style.cursor = "pointer";
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
function showFreshnessDetail() {
|
||||
if (renderedMapSnapshot && renderedMapSnapshot.fetched_at !== null) {
|
||||
const seconds = Math.max(0, Math.floor(mapSnapshotNow() - renderedMapSnapshot.fetched_at));
|
||||
const when = new Date(renderedMapSnapshot.fetched_at * 1000).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai' });
|
||||
const age = seconds < 60 ? `${seconds} 秒前` : `${Math.floor(seconds / 60)} 分钟前`;
|
||||
showToast(`车辆数据更新于 ${when}(${age})${mapRefreshFailed ? ',更新暂时失败,正在自动重试' : ''}`);
|
||||
return;
|
||||
}
|
||||
showToast(mapRefreshFailed ? "地图数据暂时不可用,正在自动重试" : "正在获取最新车辆数据");
|
||||
}
|
||||
|
||||
function showToast(msg) {
|
||||
const t = document.getElementById("toast");
|
||||
t.textContent = msg;
|
||||
t.classList.add("show");
|
||||
setTimeout(() => t.classList.remove("show"), 2500);
|
||||
}
|
||||
|
||||
// ========== 抓包工具下载 ==========
|
||||
// 安装包是 Windows exe,任何手机/平板都跑不了;微信、QQ、支付宝等内置
|
||||
// WebView 还会直接拦截 exe 下载。这两类情况都改为提示复制链接到电脑浏览器。
|
||||
const CAPTURE_TOOL_PATH = "/download/capture-tool.exe";
|
||||
|
||||
// 鸿蒙 UA 有两种:老版 HarmonyOS + Android 兼容层,新版纯 OpenHarmony/ArkWeb;
|
||||
// 微信鸿蒙版仍带 MicroMessenger,但部分版本 UA 精简后只剩 HarmonyOS。
|
||||
function detectHarmony() {
|
||||
const ua = navigator.userAgent || "";
|
||||
return /OpenHarmony|HarmonyOS|ArkWeb|HMSCore/i.test(ua);
|
||||
}
|
||||
function detectMobile() {
|
||||
const ua = navigator.userAgent || "";
|
||||
const touchPoints = navigator.maxTouchPoints || 0;
|
||||
// iPadOS 13+ 默认「请求桌面网站」,UA 伪装成 macOS;
|
||||
// 靠触点数区分真正的 Mac(0)与 iPad(>1)
|
||||
if (/Macintosh/.test(ua) && touchPoints > 1) return "iPad";
|
||||
// 鸿蒙平板也常带 Tablet,先于手机判断
|
||||
if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) {
|
||||
return /Tablet/i.test(ua) ? "鸿蒙平板" : "鸿蒙手机";
|
||||
}
|
||||
if (/iPhone|iPod/.test(ua)) return "iPhone";
|
||||
if (/iPad/.test(ua)) return "iPad";
|
||||
if (/Android/.test(ua)) return /Tablet/i.test(ua) ? "安卓平板" : "安卓手机";
|
||||
// 兜底:UA 明确标了 Mobile 但没给出具体平台
|
||||
if (/Mobile/i.test(ua)) return "手机";
|
||||
return null;
|
||||
}
|
||||
// 返回需要拦截的"环境名",null 表示可以直接下载
|
||||
function detectInAppBrowser() {
|
||||
const ua = navigator.userAgent || "";
|
||||
// 原生壳优先判断:它是最外层容器,UA 里可能同时带 Android
|
||||
if (/xbniu-native/i.test(ua)) return "APP";
|
||||
if (/MicroMessenger/i.test(ua)) return detectHarmony() ? "鸿蒙微信" : "微信";
|
||||
if (/\bQQ\/|QQBrowser/i.test(ua)) return "QQ";
|
||||
if (/AlipayClient/i.test(ua)) return "支付宝";
|
||||
if (/DingTalk/i.test(ua)) return "钉钉";
|
||||
if (/Weibo/i.test(ua)) return "微博";
|
||||
if (/aweme|ByteDance/i.test(ua)) return "抖音";
|
||||
return null;
|
||||
}
|
||||
function captureToolUrl() {
|
||||
return new URL(CAPTURE_TOOL_PATH, window.location.href).href;
|
||||
}
|
||||
// 返回 true 时放行 <a download> 的原生下载
|
||||
function onDownloadCaptureTool(event) {
|
||||
const app = detectInAppBrowser();
|
||||
const mobile = app ? null : detectMobile(); // 内嵌环境优先,文案更具体
|
||||
if (!app && !mobile) return true;
|
||||
if (event) event.preventDefault();
|
||||
showDownloadTipModal(app, mobile);
|
||||
return false;
|
||||
}
|
||||
function showDownloadTipModal(appName, mobileName) {
|
||||
const title = document.getElementById("download-tip-title");
|
||||
const desc = document.getElementById("download-tip-desc");
|
||||
const hint = document.getElementById("download-tip-hint");
|
||||
title.textContent = "请在电脑上下载安装";
|
||||
if (appName) {
|
||||
desc.textContent = `${appName}内无法直接下载安装包。请复制下面的链接,在电脑浏览器中打开下载。`;
|
||||
hint.textContent = "安装包为 Windows 程序,手机端下载后无法运行。";
|
||||
} else {
|
||||
// 普通移动端浏览器:能下载但装了也用不了,引导去电脑
|
||||
desc.textContent = `当前是${mobileName || "移动设备"},安装包为 Windows 程序,在此设备上无法运行。请复制下面的链接,在电脑浏览器中打开下载。`;
|
||||
hint.textContent = "";
|
||||
}
|
||||
hint.style.display = hint.textContent ? "block" : "none";
|
||||
document.getElementById("download-tip-link").value = captureToolUrl();
|
||||
document.getElementById("download-tip-modal").classList.add("show");
|
||||
}
|
||||
function closeDownloadTipModal() {
|
||||
document.getElementById("download-tip-modal").classList.remove("show");
|
||||
}
|
||||
|
||||
// ========== 数据导出(CSV 直链,1 小时有效) ==========
|
||||
// 流程:POST /api/export/create(登录态)→ 拿到免登录直链。
|
||||
// UA 复用 detectInAppBrowser:微信/QQ/支付宝/钉钉/微博/抖音/原生壳内无法直接下载,
|
||||
// 弹「复制链接到外部浏览器」提示;普通浏览器直接触发下载。
|
||||
function closeExportTipModal() {
|
||||
document.getElementById("export-tip-modal").classList.remove("show");
|
||||
}
|
||||
async function copyExportLink() {
|
||||
const url = document.getElementById("export-tip-link").value;
|
||||
const input = document.getElementById("export-tip-link");
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(url);
|
||||
showToast("链接已复制,请在浏览器中打开");
|
||||
return;
|
||||
}
|
||||
throw new Error("clipboard unavailable");
|
||||
} catch (e) {
|
||||
try {
|
||||
input.removeAttribute("readonly");
|
||||
input.select();
|
||||
document.execCommand("copy");
|
||||
input.setAttribute("readonly", "");
|
||||
showToast("链接已复制,请在浏览器中打开");
|
||||
} catch (e2) {
|
||||
showToast("复制失败,请长按链接手动复制");
|
||||
}
|
||||
}
|
||||
}
|
||||
async function exportHistoryCsv() {
|
||||
if (!authToken) { showToast("请先登录"); return; }
|
||||
showToast("正在生成导出链接...");
|
||||
try {
|
||||
const resp = await apiFetch("/api/export/create", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${authToken}` },
|
||||
body: JSON.stringify({ type: "history_csv" })
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code !== 0) {
|
||||
showToast(data.message || "生成导出链接失败");
|
||||
return;
|
||||
}
|
||||
const url = new URL(data.data.url, window.location.href).href;
|
||||
const app = detectInAppBrowser();
|
||||
if (app) {
|
||||
// 微信/原生壳等内嵌环境:给直链,复制到外部浏览器下载(直链免登录,1小时有效)
|
||||
document.getElementById("export-tip-desc").textContent =
|
||||
`${app}内无法直接下载文件。请复制下面的链接到系统浏览器打开(免登录,${data.data.ttl_hours} 小时内有效)。`;
|
||||
document.getElementById("export-tip-link").value = url;
|
||||
document.getElementById("export-tip-modal").classList.add("show");
|
||||
return;
|
||||
}
|
||||
// 普通浏览器:直接下载,同时保留直链以便换浏览器使用
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
showToast(`已开始下载(直链 ${data.data.ttl_hours} 小时内有效)`);
|
||||
} catch (err) {
|
||||
showToast("导出失败,请重试");
|
||||
}
|
||||
}
|
||||
async function copyDownloadLink() {
|
||||
const url = captureToolUrl();
|
||||
const input = document.getElementById("download-tip-link");
|
||||
// 微信等 WebView 常禁用 navigator.clipboard(非安全上下文或权限拒绝),
|
||||
// 回退到选中 + execCommand 的老办法
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(url);
|
||||
showToast("链接已复制");
|
||||
return;
|
||||
}
|
||||
throw new Error("clipboard unavailable");
|
||||
} catch (e) {
|
||||
try {
|
||||
input.removeAttribute("readonly");
|
||||
input.select();
|
||||
input.setSelectionRange(0, url.length);
|
||||
const ok = document.execCommand("copy");
|
||||
input.setAttribute("readonly", "readonly");
|
||||
showToast(ok ? "链接已复制" : "复制失败,请长按链接手动复制");
|
||||
} catch (e2) {
|
||||
showToast("复制失败,请长按链接手动复制");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 底层异常转用户提示:网关/错误页返回 HTML 时 resp.json() 会抛
|
||||
// "Unexpected token '<' ... is not valid JSON",直接展示既难懂又含 token 字样易引起误解
|
||||
function friendlyError(e) {
|
||||
const msg = (e && e.message) || "";
|
||||
if (/Unexpected token|is not valid JSON|JSON\.parse/i.test(msg)) {
|
||||
return "服务响应异常,请稍后重试";
|
||||
}
|
||||
return msg || "网络错误,请重试";
|
||||
}
|
||||
|
||||
// ========== Token失效弹窗 ==========
|
||||
// 仅在真正检测到微信凭据失效时调用;带冷却时间,避免轮询/刷新反复打扰
|
||||
let _credInvalidLastShownAt = 0;
|
||||
const CRED_INVALID_MODAL_COOLDOWN = 10 * 60 * 1000; // 10 分钟内不重复弹出
|
||||
function notifyCredentialInvalid(message) {
|
||||
const modal = document.getElementById("token-expired-modal");
|
||||
if (!modal || modal.classList.contains("show")) return;
|
||||
if (Date.now() - _credInvalidLastShownAt < CRED_INVALID_MODAL_COOLDOWN) return;
|
||||
_credInvalidLastShownAt = Date.now();
|
||||
showTokenExpiredModal(null, message);
|
||||
}
|
||||
function showTokenExpiredModal(customTitle, customDesc) {
|
||||
document.getElementById("token-expired-title").textContent = customTitle || "token已失效,请重新登录";
|
||||
document.getElementById("token-expired-desc").textContent = customDesc || "您的微信凭据已过期,请重新抓包获取最新的 Token ID(及 AccessToken)";
|
||||
document.getElementById("token-expired-modal").classList.add("show");
|
||||
// 预填当前用户已有的token信息
|
||||
loadExpiredTokenFields();
|
||||
}
|
||||
function closeTokenExpiredModal() {
|
||||
document.getElementById("token-expired-modal").classList.remove("show");
|
||||
document.getElementById("expired-tip").textContent = "";
|
||||
}
|
||||
async function loadExpiredTokenFields() {
|
||||
if (!authToken) return;
|
||||
try {
|
||||
const resp = await apiFetch("/api/auth/profile", {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code === 0 && data.data) {
|
||||
document.getElementById("expired-token-id").value = data.data.token_id || "";
|
||||
document.getElementById("expired-signature").value = data.data.token || "";
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
async function saveExpiredToken() {
|
||||
if (!authToken) {
|
||||
document.getElementById("expired-tip").textContent = "请先登录";
|
||||
return;
|
||||
}
|
||||
const token_id = document.getElementById("expired-token-id").value.trim();
|
||||
const access_token = document.getElementById("expired-signature").value.trim();
|
||||
const tip = document.getElementById("expired-tip");
|
||||
|
||||
if (!token_id) {
|
||||
tip.textContent = "Token ID 必填;AccessToken 选填";
|
||||
return;
|
||||
}
|
||||
|
||||
tip.textContent = "验证中...";
|
||||
try {
|
||||
const verifyResp = await apiFetch("/api/auth/verify_token", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${authToken}` },
|
||||
body: JSON.stringify({ access_token, token_id })
|
||||
});
|
||||
const verifyData = await verifyResp.json();
|
||||
if (!verifyData.valid) {
|
||||
tip.textContent = verifyData.message || "凭据验证失败,请检查 Token ID 是否正确";
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
tip.textContent = "验证失败";
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await apiFetch("/api/auth/save_token", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${authToken}`
|
||||
},
|
||||
body: JSON.stringify({ access_token, token_id })
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code === 0) {
|
||||
tip.textContent = "";
|
||||
closeTokenExpiredModal();
|
||||
showToast("凭证已更新 ✓");
|
||||
} else {
|
||||
tip.textContent = data.message || "保存失败";
|
||||
}
|
||||
} catch (err) {
|
||||
tip.textContent = "保存失败";
|
||||
}
|
||||
}
|
||||
|
||||
// ================= 版本号 & 更新说明 =================
|
||||
const VERSION_TAG = "v1.7.0-preview";
|
||||
const VERSION_LOGS = [
|
||||
{ v: "v1.7.0 预览", items: ["新增附近列表、车型与电量筛选、校园地点搜索和常用地点", "完善定位失败引导、订阅编辑与执行结果、历史订单筛选和分页", "统一车辆状态,支持5位和8位车牌,增加浅色、深色和跟随系统"] },
|
||||
{ v: "v1.6.0", items: [
|
||||
"新增用车设置:可独立开启或关闭邮件提醒,并多选到期前 10、5、3、2、1 分钟及到期时提醒",
|
||||
"支持实时调整用车到期时间,当前订单也会立即按新时长更新;默认 19 分钟,月卡前 20 分钟免费并预留 1 分钟容错",
|
||||
"新增自动还车开关;关闭后到期邮件只提醒手动还车,不再显示已自动还车或自动还车失败",
|
||||
"共享用车按实际骑行人的到期与自动还车设置执行,车主和骑行人分别按各自设置接收美化后的 HTML 邮件及一键还车入口",
|
||||
"修复共享车主重复显示订单横幅,并修复普通/共享车辆已锁车但接口响应异常时误报还车失败的问题"
|
||||
] },
|
||||
{ v: "v1.5.0", items: [
|
||||
"新增共享电动车自定义昵称"
|
||||
] },
|
||||
{ v: "v1.4.0", items: [
|
||||
"支持多设备同时登录:同一账号可在多台设备/多个浏览器同时在线,不再相互顶下线",
|
||||
"个人中心新增“登录设备管理”:可查看当前账号各登录设备(记录系统/浏览器与最近活跃),随时下线其它设备或一键下线其它所有设备",
|
||||
"统一个人中心/凭证/设备管理的深浅色模式适配"
|
||||
] },
|
||||
{ v: "v1.3.0", items: [
|
||||
"新增「共享电动车」功能:向车主申请共享其电动车;接受后可设置每天可用次数、是否需要车主持有优惠卡、优惠卡剩余次数下限(低于则不能用)",
|
||||
"开锁时可选择“用自己的账号”或“用共享者的账号”(附实时可用次数;今日次数用完的共享者默认隐藏)",
|
||||
"用车横幅区分“共享中/使用XX的车中”,车主与被共享者都能还车",
|
||||
"个人中心新增“共享电动车”入口,双Tab管理(可使用的/我共享的),双方都可解绑"
|
||||
] },
|
||||
{ v: "v1.2.0", items: [
|
||||
"修复远程扫码被拦截:开锁上报车辆附近随机位置",
|
||||
"请求头对齐当前版本微信环境"
|
||||
] }
|
||||
];
|
||||
// 右下角版本徽标始终跟随 VERSION_TAG,避免与更新说明不一致
|
||||
(function () {
|
||||
var b = document.getElementById("version-badge");
|
||||
if (b) b.textContent = VERSION_TAG;
|
||||
})();
|
||||
let versionModalInited = false;
|
||||
let versionAutoTries = 0;
|
||||
function openVersionModal() {
|
||||
if (!versionModalInited) {
|
||||
const el = document.getElementById("version-content");
|
||||
el.innerHTML = VERSION_LOGS.map(l =>
|
||||
`<h4>${l.v}</h4><ul>${l.items.map(i => `<li>${i}</li>`).join("")}</ul>`
|
||||
).join("");
|
||||
versionModalInited = true;
|
||||
}
|
||||
// 记录已查看当前版本,避免每次打开都弹
|
||||
try { localStorage.setItem("version_seen", VERSION_TAG); } catch (e) {}
|
||||
document.getElementById("version-modal").classList.add("show");
|
||||
}
|
||||
function closeVersionModal() {
|
||||
document.getElementById("version-modal").classList.remove("show");
|
||||
}
|
||||
// 新版本/首次打开自动弹当前版本更新说明(每版本每浏览器只自动弹一次)
|
||||
function maybeAutoShowVersion() {
|
||||
// Update notes are available from Settings; first visits stay focused on finding a bike.
|
||||
}
|
||||
|
||||
async function previewLogin(button) {
|
||||
button = button || document.querySelector("[data-preview-demo]") || document.getElementById("auth-btn");
|
||||
await doLogin("demo@preview.local", "preview123", document.getElementById("gate-tip"), button);
|
||||
if (currentUser?.email === "demo@preview.local" && typeof SettingsPages !== "undefined") SettingsPages.close();
|
||||
}
|
||||
async function createPreviewSession() {
|
||||
return AppAPI.run("preview-session", null, async () => {
|
||||
try {
|
||||
let result = null;
|
||||
const saved = localStorage.getItem("xbniu_preview_live_token");
|
||||
if (saved) {
|
||||
const status = await (await apiFetch("/api/auth/status", {headers:{Authorization:`Bearer ${saved}`}})).json();
|
||||
if (status.data?.logged_in) result = {rtn_code:0,data:{token:saved,email:status.data.email}};
|
||||
}
|
||||
if (!result) result = await (await apiFetch("/api/preview/session", {method:"POST"})).json();
|
||||
if (result.rtn_code !== 0) throw new Error(result.message || "创建失败");
|
||||
if (currentUser?.email !== result.data.email) resetMapForAccount();
|
||||
authToken = result.data.token; currentUser = {email:result.data.email}; localStorage.setItem("auth_token",authToken);
|
||||
localStorage.setItem("xbniu_preview_live_token", authToken);
|
||||
updateAuthButton(); hideLoginGate(); closeAllModals(); clearRentalState(); hideOrderBanner();
|
||||
currentOrder = null;
|
||||
if (map) loadMapData(currentType, false);
|
||||
showToast("独立测试账号已创建,请填写微信凭证后测试真实接口");
|
||||
openSettingsPage(); openAuthModal();
|
||||
} catch (error) { showToast(error.message || "创建失败,请重试"); }
|
||||
});
|
||||
}
|
||||
+5017
-1339
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,766 @@
|
||||
/* 跟随式导航:路线规划/跟随/偏航重算/朝向/箭头/指引 + 步行距离精算。
|
||||
* 从 static/js/map.js 拆出(保持全局函数名不变,其他模块按原名调用)。 */
|
||||
|
||||
|
||||
// ========== 步行路线精算(真实道路距离 + 耗时)==========
|
||||
const _walkRouteCache = new Map(); // `${code}|${我的坐标}` -> {d, t}
|
||||
// 超过这个直线距离就不显示「距离/步行」——太远的车走过去没有意义,
|
||||
// 而且会让百度步行规划白白消耗配额。直线估算与精算共用同一个阈值。
|
||||
const MAX_WALK_DISTANCE_M = 20000;
|
||||
|
||||
function parseWalkDistance(text) {
|
||||
const s = String(text || "");
|
||||
const km = s.match(/([\d.]+)\s*公里/);
|
||||
if (km) return Math.round(parseFloat(km[1]) * 1000);
|
||||
const m = s.match(/([\d.]+)\s*米/);
|
||||
return m ? Math.round(parseFloat(m[1])) : 0;
|
||||
}
|
||||
|
||||
function parseWalkDuration(text) {
|
||||
const s = String(text || "");
|
||||
let sec = 0;
|
||||
const h = s.match(/([\d.]+)\s*小时/);
|
||||
const min = s.match(/([\d.]+)\s*分钟/);
|
||||
if (h) sec += Math.round(parseFloat(h[1]) * 3600);
|
||||
if (min) sec += Math.round(parseFloat(min[1]) * 60);
|
||||
return sec;
|
||||
}
|
||||
|
||||
async function refineWalkRoute(bike) {
|
||||
const bikeCode = String((bike && bike.code) || "");
|
||||
if (!bikeCode) return;
|
||||
const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker)
|
||||
? autoLocationMarker.getPosition() : null;
|
||||
if (!me || !bike.latitude || !bike.longitude) return;
|
||||
|
||||
// 太远就整块不显示(与直线估算口径一致,别让精算把隐藏的行又显示回来)
|
||||
const c0 = offsetCoord(bike.latitude, bike.longitude);
|
||||
if (calcDistance(me.lat, me.lng, c0.lat, c0.lng) > MAX_WALK_DISTANCE_M) return;
|
||||
|
||||
const key = bikeCode + "|" + me.lat.toFixed(4) + "," + me.lng.toFixed(4);
|
||||
|
||||
const apply = (distanceM, seconds) => {
|
||||
if (!selectedBike || String(selectedBike.code) !== bikeCode) return; // 已换车
|
||||
const distEl = document.getElementById("card-distance");
|
||||
const walkEl = document.getElementById("card-walk");
|
||||
const metaLeft = document.getElementById("card-meta-left");
|
||||
if (!distEl || !walkEl || !metaLeft) return;
|
||||
distEl.textContent = distanceM < 1000
|
||||
? `步行 ${Math.round(distanceM)} 米`
|
||||
: `步行 ${(distanceM / 1000).toFixed(1)} 公里`;
|
||||
walkEl.textContent = `约 ${Math.max(1, Math.round(seconds / 60))} 分钟`;
|
||||
metaLeft.hidden = false;
|
||||
};
|
||||
|
||||
const cached = _walkRouteCache.get(key);
|
||||
if (cached) { apply(cached.d, cached.t); return; }
|
||||
|
||||
// ① 后端(百度 Web 服务 API,需服务端 AK + SK,结果服务端缓存 7 天)
|
||||
try {
|
||||
const gcj = (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02)
|
||||
? coordtransform.bd09togcj02(me.lng, me.lat) : null;
|
||||
if (gcj) {
|
||||
const url = "/api/walk_route?origin_lat=" + gcj[1] + "&origin_lng=" + gcj[0]
|
||||
+ "&dest_lat=" + bike.latitude + "&dest_lng=" + bike.longitude;
|
||||
const resp = await fetch(url, {
|
||||
headers: { "Authorization": "Bearer " + authToken }
|
||||
});
|
||||
const data = await resp.json();
|
||||
const d = data && data.data;
|
||||
if (data.rtn_code === 0 && d && d.distance > 0 && d.duration > 0
|
||||
&& (d.source === "baidu" || d.source === "cache")) {
|
||||
_walkRouteCache.set(key, { d: d.distance, t: d.duration });
|
||||
apply(d.distance, d.duration);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (e) { /* 忽略,走 SDK */ }
|
||||
|
||||
// ② 浏览器端 JS API 步行规划(现成浏览器 AK,返回 "1.6公里"/"23分钟" 字符串)
|
||||
try {
|
||||
if (typeof BMapGL !== "undefined" && BMapGL.WalkingRoute && map) {
|
||||
const plan = await new Promise(resolve => {
|
||||
let done = false;
|
||||
const finish = v => { if (!done) { done = true; resolve(v); } };
|
||||
const walk = new BMapGL.WalkingRoute(map, {
|
||||
renderOptions: { map: null, panel: null },
|
||||
onSearchComplete: res => {
|
||||
if (!res || res.getStatus() !== 0) return finish(null);
|
||||
try {
|
||||
const p = res.getPlan(0);
|
||||
const d = parseWalkDistance(p.getDistance());
|
||||
const t = parseWalkDuration(p.getDuration());
|
||||
finish(d > 0 && t > 0 ? { d: d, t: t } : null);
|
||||
} catch (err) { finish(null); }
|
||||
}
|
||||
});
|
||||
walk.search(me, new BMapGL.Point(bike.longitude, bike.latitude));
|
||||
setTimeout(() => finish(null), 8000);
|
||||
});
|
||||
if (plan) {
|
||||
_walkRouteCache.set(key, plan);
|
||||
apply(plan.d, plan.t);
|
||||
}
|
||||
}
|
||||
} catch (e) { /* 保留直线估算 */ }
|
||||
}
|
||||
|
||||
// ========== 跟随式导航 ==========
|
||||
// 状态:null = 未导航;对象存在 = 导航中
|
||||
// { ptsGcj, ptsBD, idx, walking, follow, timer, watchId, destCode, distance, duration }
|
||||
let _nav = null;
|
||||
let _navLoading = false;
|
||||
// 每次 start/stop 都自增;await 回来发现变了就说明中途被关掉了,别再自动开起来
|
||||
let _navEpoch = 0;
|
||||
|
||||
// 偏航阈值:百度会把起点吸附到最近道路,和真实 GPS 天然差 20~50 米,
|
||||
// 所以阈值不能太小,且重算要有冷却,否则会陷入"重算->又偏->再重算"。
|
||||
const NAV_DEVIATE_M = 60;
|
||||
const NAV_RECOMPUTE_COOLDOWN_MS = 12000;
|
||||
// 偏差在这个范围内就把箭头吸附到路线上(10 米内才贴线,超过了就老实显示真实位置)
|
||||
const NAV_SNAP_M = 10;
|
||||
const NAV_BOTTOM_RATIO = 0.20; // 当前位置压在屏幕下方约 80% 高度处
|
||||
const NAV_FREE_TIMEOUT = 8000; // 拖动后多久自动回正
|
||||
|
||||
function _haversineM(lat1, lng1, lat2, lng2) {
|
||||
const R = 6371000;
|
||||
const dLat = (lat2 - lat1) * Math.PI / 180;
|
||||
const dLng = (lng2 - lng1) * Math.PI / 180;
|
||||
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||||
Math.sin(dLng / 2) * Math.sin(dLng / 2);
|
||||
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
}
|
||||
|
||||
// 浏览器定位给的是 WGS84,转成 GCJ02 才能和百度/上游坐标对齐
|
||||
function _gpsToGcj(coords) {
|
||||
const lat = coords.latitude, lng = coords.longitude;
|
||||
if (typeof coordtransform !== "undefined" && coordtransform.wgs84togcj02) {
|
||||
try {
|
||||
const g = coordtransform.wgs84togcj02(lng, lat); // -> [lng, lat]
|
||||
return { lat: g[1], lng: g[0] };
|
||||
} catch (e) { /* 落到下面原值兜底 */ }
|
||||
}
|
||||
return { lat: lat, lng: lng };
|
||||
}
|
||||
|
||||
// 航向角:0=正北,90=正东
|
||||
function _bearing(from, to) {
|
||||
const p1 = from.lat * Math.PI / 180, p2 = to.lat * Math.PI / 180;
|
||||
const dl = (to.lng - from.lng) * Math.PI / 180;
|
||||
const y = Math.sin(dl) * Math.cos(p2);
|
||||
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
|
||||
return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
|
||||
}
|
||||
|
||||
// 当前位置在折线上的最近点(投影到线段上,不是只找最近顶点)
|
||||
// 返回 {index, meters, point};point 为线段上的插值点
|
||||
function _projectOnRoute(ptsBD, point) {
|
||||
if (!ptsBD || ptsBD.length === 0) return { index: 0, meters: Infinity, point: point };
|
||||
if (ptsBD.length === 1) {
|
||||
return { index: 0, meters: _haversineM(point.lat, point.lng, ptsBD[0].lat, ptsBD[0].lng),
|
||||
point: ptsBD[0] };
|
||||
}
|
||||
const cosLat = Math.cos(point.lat * Math.PI / 180);
|
||||
const toXY = (p) => [
|
||||
(p.lng - point.lng) * 111320 * cosLat,
|
||||
(p.lat - point.lat) * 110540
|
||||
];
|
||||
let bestI = 0, bestM = Infinity, bestT = 0;
|
||||
for (let i = 0; i < ptsBD.length - 1; i++) {
|
||||
const a = toXY(ptsBD[i]), b = toXY(ptsBD[i + 1]);
|
||||
const dx = b[0] - a[0], dy = b[1] - a[1];
|
||||
const seg2 = dx * dx + dy * dy;
|
||||
// 查询点是原点 (0,0),投影参数 t 落在 [0,1]
|
||||
const t = seg2 === 0 ? 0 : Math.max(0, Math.min(1, -(a[0] * dx + a[1] * dy) / seg2));
|
||||
const cx = a[0] + t * dx, cy = a[1] + t * dy;
|
||||
const d = Math.hypot(cx, cy);
|
||||
if (d < bestM) { bestM = d; bestI = i; bestT = t; }
|
||||
}
|
||||
const a = ptsBD[bestI], b = ptsBD[bestI + 1];
|
||||
const p = new BMapGL.Point(a.lng + bestT * (b.lng - a.lng),
|
||||
a.lat + bestT * (b.lat - a.lat));
|
||||
return { index: bestI, meters: bestM, point: p };
|
||||
}
|
||||
|
||||
function _navBanner(show) {
|
||||
const el = document.getElementById("nav-banner");
|
||||
if (el) el.hidden = !show;
|
||||
}
|
||||
|
||||
function _navPill(show) {
|
||||
const el = document.getElementById("nav-resume");
|
||||
if (el) el.hidden = !show;
|
||||
}
|
||||
|
||||
function _navBtnText(text) {
|
||||
const el = document.getElementById("bike-nav-btn-text");
|
||||
if (el) el.textContent = text;
|
||||
// 「导航」和「结束」宽度不同,换字后重新量一次是否还放得下
|
||||
if (typeof _fitCardActions === "function") _fitCardActions();
|
||||
}
|
||||
|
||||
function _clearNavLayers() {
|
||||
if (!_nav) return;
|
||||
(_nav.walking || []).forEach(ov => { try { map.removeOverlay(ov); } catch (e) {} });
|
||||
(_nav.remaining || []).forEach(ov => { try { map.removeOverlay(ov); } catch (e) {} });
|
||||
if (_nav.endMarker) { try { map.removeOverlay(_nav.endMarker); } catch (e) {} }
|
||||
_nav.walking = []; _nav.remaining = []; _nav.endMarker = null;
|
||||
}
|
||||
|
||||
// 按进度把折线切成「已走(灰)」与「剩余(蓝)」
|
||||
function _redrawRoute(fromIndex) {
|
||||
if (!_nav || !_nav.ptsBD || !_nav.ptsBD.length) return;
|
||||
_clearNavLayers();
|
||||
const pts = _nav.ptsBD;
|
||||
const cut = Math.max(0, Math.min(fromIndex, pts.length - 1));
|
||||
|
||||
if (cut > 0) {
|
||||
const walked = new BMapGL.Polyline(pts.slice(0, cut + 1), {
|
||||
strokeColor: "#9E9E9E", strokeWeight: 6, strokeOpacity: 0.85,
|
||||
strokeStyle: "solid"
|
||||
});
|
||||
map.addOverlay(walked);
|
||||
_nav.walking.push(walked);
|
||||
}
|
||||
if (cut < pts.length - 1) {
|
||||
const rest = pts.slice(cut);
|
||||
const casing = new BMapGL.Polyline(rest, {
|
||||
strokeColor: "#FFFFFF", strokeWeight: 11, strokeOpacity: 0.95,
|
||||
strokeStyle: "solid"
|
||||
});
|
||||
const line = new BMapGL.Polyline(rest, {
|
||||
strokeColor: "#0A84FF", strokeWeight: 6, strokeOpacity: 1,
|
||||
strokeStyle: "solid"
|
||||
});
|
||||
map.addOverlay(casing);
|
||||
map.addOverlay(line);
|
||||
_nav.remaining.push(casing, line);
|
||||
}
|
||||
if (!_nav.endMarker) {
|
||||
_nav.endMarker = new BMapGL.Marker(pts[pts.length - 1], { icon: _destIcon() });
|
||||
map.addOverlay(_nav.endMarker);
|
||||
}
|
||||
}
|
||||
|
||||
// 跟随:把当前位置压到屏幕下方,并让行进方向朝上
|
||||
// 部分环境(例如 WebGL 软件渲染)setHeading 不生效,探测一次后退化为「正北朝上」
|
||||
let _headingSupported = null;
|
||||
let _headingAnim = null;
|
||||
|
||||
// 文档化的旋转方式:ViewAnimation 关键帧里的 heading
|
||||
// (setHeading 是没写进文档的私有方法,见 docs/baidu-map-gl-cheatsheet.md 坑 1)
|
||||
function _rotateByAnimation(deg) {
|
||||
try {
|
||||
if (typeof BMapGL.ViewAnimation !== "function") return false;
|
||||
const from = (typeof map.getHeading === "function" ? map.getHeading() : 0) || 0;
|
||||
if (_headingAnim && map.cancelViewAnimation) {
|
||||
try { map.cancelViewAnimation(_headingAnim); } catch (e) {}
|
||||
}
|
||||
_headingAnim = new BMapGL.ViewAnimation([
|
||||
{ heading: from, percentage: 0 },
|
||||
{ heading: deg, percentage: 1 }
|
||||
], { duration: 260 });
|
||||
map.startViewAnimation(_headingAnim);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function _applyHeading(deg) {
|
||||
if (_headingSupported === false) return;
|
||||
try {
|
||||
if (typeof map.setHeading !== "function") { _headingSupported = false; return; }
|
||||
map.setHeading(deg);
|
||||
if (_headingSupported === null) {
|
||||
const got = typeof map.getHeading === "function" ? map.getHeading() : undefined;
|
||||
// 调了 45 度结果还是 0,说明这个环境不支持地图旋转
|
||||
_headingSupported = (typeof got === "number" && Math.abs(got) > 0.5);
|
||||
if (!_headingSupported) {
|
||||
console.info("[导航] 当前环境不支持 setHeading,尝试 ViewAnimation 旋转");
|
||||
// 关键:有些 WebGL 环境调完 setHeading 会留下坏的相机状态,
|
||||
// 表现为整张底图变黑。这里复位并把视野重新设一次,把瓦片拉回来。
|
||||
try { if (map.resetHeading) map.resetHeading(); } catch (e) {}
|
||||
try {
|
||||
const c = map.getCenter ? map.getCenter() : null;
|
||||
if (c) map.setCenter(c);
|
||||
} catch (e) {}
|
||||
// 文档化兜底:ViewAnimation 关键帧旋转
|
||||
if (_rotateByAnimation(deg)) {
|
||||
_headingSupported = true;
|
||||
console.info("[导航] ViewAnimation 旋转可用");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) { _headingSupported = false; }
|
||||
}
|
||||
|
||||
// 迁就百度的一个坑:setCenter 会把刚设置的 heading 抹回 0,
|
||||
// 必须在它的回调里再 setHeading(官方 setCenter 支持 callback,动画结束后触发)。
|
||||
// 另一个坑:BMapGL 的 heading 是**逆时针**角度,要让行进方向朝上必须传 -方位角。
|
||||
//(实测方位角 145° 时:setHeading(145) 前方在左上;setHeading(-145) 前方正上方)
|
||||
function _centerOnUser(point, headingDeg) {
|
||||
const h = window.innerHeight || 800;
|
||||
const offsetY = Math.round(h * NAV_BOTTOM_RATIO);
|
||||
const mapHeading = (typeof headingDeg === "number") ? -headingDeg : null;
|
||||
_markProgrammaticMove();
|
||||
try {
|
||||
map.setCenter(point, {
|
||||
noAnimation: true,
|
||||
callback: function () {
|
||||
if (mapHeading !== null) _applyHeading(mapHeading);
|
||||
try {
|
||||
// 把「我」推到屏幕下方:地图整体上移
|
||||
if (map.panBy) map.panBy(0, offsetY);
|
||||
} catch (e) {}
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
// 老版本 setCenter 不支持 options,退回手动顺序
|
||||
try {
|
||||
map.setCenter(point);
|
||||
if (mapHeading !== null) _applyHeading(mapHeading);
|
||||
if (map.panBy) map.panBy(0, offsetY);
|
||||
} catch (e2) { /* 忽略 */ }
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 罗盘 + 导航箭头 ==========
|
||||
// 手机朝向(罗盘):iOS 用 webkitCompassHeading,安卓用 360 - alpha
|
||||
let _compassHeading = null;
|
||||
let _compassBound = false;
|
||||
|
||||
function _bindCompass() {
|
||||
if (_compassBound) return;
|
||||
_compassBound = true;
|
||||
const onOrient = (e) => {
|
||||
let h = null;
|
||||
if (typeof e.webkitCompassHeading === "number") {
|
||||
h = e.webkitCompassHeading; // iOS:已经是「相对正北的顺时针角度」
|
||||
} else if (typeof e.alpha === "number") {
|
||||
h = (360 - e.alpha) % 360; // 安卓:alpha 是逆时针
|
||||
}
|
||||
if (h !== null && Number.isFinite(h)) _compassHeading = h;
|
||||
};
|
||||
window.addEventListener("deviceorientationabsolute", onOrient, true);
|
||||
window.addEventListener("deviceorientation", onOrient, true);
|
||||
}
|
||||
|
||||
// iOS 13+ 必须由用户手势触发权限申请;导航按钮的点击正好是手势
|
||||
async function _ensureCompassPermission() {
|
||||
const D = window.DeviceOrientationEvent;
|
||||
try {
|
||||
if (D && typeof D.requestPermission === "function") {
|
||||
const res = await D.requestPermission();
|
||||
if (res !== "granted") {
|
||||
console.info("[导航] 未获得方向传感器权限,箭头改用行进方向");
|
||||
}
|
||||
}
|
||||
} catch (e) { /* 用户拒绝或非 iOS */ }
|
||||
_bindCompass();
|
||||
}
|
||||
|
||||
// 导航箭头图标(向上指,旋转由 Marker.setRotation 控制)
|
||||
function _navArrowIcon() {
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72" viewBox="0 0 72 72">'
|
||||
+ '<circle cx="36" cy="36" r="30" fill="#0A84FF" fill-opacity="0.16"/>'
|
||||
+ '<path d="M36 10 L52 52 L36 43 L20 52 Z" fill="#0A84FF" stroke="#FFFFFF"'
|
||||
+ ' stroke-width="3" stroke-linejoin="round"/></svg>';
|
||||
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
|
||||
return new BMapGL.Icon(url, new BMapGL.Size(36, 36),
|
||||
{ anchor: new BMapGL.Size(18, 18) });
|
||||
}
|
||||
|
||||
// 转弯/掉头/直行的图标(画在导航条文字左边,不再画到地图上)
|
||||
function _turnKind(turnType) {
|
||||
const t = String(turnType || "");
|
||||
if (t.indexOf("掉头") >= 0) return "uturn";
|
||||
if (t.indexOf("左") >= 0) return "left";
|
||||
if (t.indexOf("右") >= 0) return "right";
|
||||
return "straight";
|
||||
}
|
||||
|
||||
function _turnSvg(kind) {
|
||||
const paths = {
|
||||
straight: '<path d="M24 42 L24 12" /><path d="M14 22 L24 10 L34 22" />',
|
||||
left: '<path d="M34 42 L34 22 L16 22" /><path d="M24 12 L12 22 L24 32" />',
|
||||
right: '<path d="M14 42 L14 22 L32 22" /><path d="M30 12 L42 22 L30 32" />',
|
||||
uturn: '<path d="M18 42 L18 18 A8 8 0 0 1 34 18 L34 26" /><path d="M26 20 L34 10 L42 20" />'
|
||||
};
|
||||
const body = paths[kind] || paths.straight;
|
||||
return '<svg viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="4.5"'
|
||||
+ ' stroke-linecap="round" stroke-linejoin="round">' + body + '</svg>';
|
||||
}
|
||||
|
||||
function _setTurnIcon(kind) {
|
||||
const el = document.getElementById("nav-banner-turn");
|
||||
if (!el) return;
|
||||
if (el.__kind === kind) return; // 同一个图标不重复写 DOM
|
||||
el.__kind = kind;
|
||||
el.innerHTML = _turnSvg(kind);
|
||||
}
|
||||
|
||||
// 目的地图标(SVG 定位针,底端对准坐标点)
|
||||
function _destIcon() {
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="76" viewBox="0 0 32 38">'
|
||||
+ '<path d="M16 36C16 36 30 22.5 30 14A14 14 0 1 0 2 14C2 22.5 16 36 16 36Z"'
|
||||
+ ' fill="#FF3B30" stroke="#FFFFFF" stroke-width="2.4"/>'
|
||||
+ '<circle cx="16" cy="14" r="5" fill="#FFFFFF"/></svg>';
|
||||
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
|
||||
return new BMapGL.Icon(url, new BMapGL.Size(30, 36), { anchor: new BMapGL.Size(15, 36) });
|
||||
}
|
||||
|
||||
function _placeNavArrow(point) {
|
||||
if (!_nav) return;
|
||||
if (!_nav.arrow) {
|
||||
_nav.arrow = new BMapGL.Marker(point, { icon: _navArrowIcon() });
|
||||
map.addOverlay(_nav.arrow);
|
||||
// 导航时用箭头代替原来的蓝点
|
||||
try { if (typeof autoLocationMarker !== "undefined" && autoLocationMarker) autoLocationMarker.hide(); } catch (e) {}
|
||||
return;
|
||||
}
|
||||
try { _nav.arrow.setPosition(point); } catch (e) {}
|
||||
}
|
||||
|
||||
function _rotateNavArrow(deg) {
|
||||
if (!_nav || !_nav.arrow) return;
|
||||
try { if (typeof _nav.arrow.setRotation === "function") _nav.arrow.setRotation(deg); } catch (e) {}
|
||||
}
|
||||
|
||||
function _clearNavArrow() {
|
||||
if (_nav && _nav.arrow) {
|
||||
try { map.removeOverlay(_nav.arrow); } catch (e) {}
|
||||
_nav.arrow = null;
|
||||
}
|
||||
try { if (typeof autoLocationMarker !== "undefined" && autoLocationMarker) autoLocationMarker.show(); } catch (e) {}
|
||||
}
|
||||
|
||||
function _navTick(position) {
|
||||
if (!_nav || _nav.follow === false) return; // 拖动查看时不抢镜头
|
||||
const gcj = _gpsToGcj(position); // WGS84 -> GCJ02
|
||||
const c = offsetCoord(gcj.lat, gcj.lng); // GCJ02 -> BD09
|
||||
const me = new BMapGL.Point(c.lng, c.lat);
|
||||
|
||||
const proj = _projectOnRoute(_nav.ptsBD, me);
|
||||
const now = Date.now();
|
||||
if (proj.meters > NAV_DEVIATE_M && !_nav.recomputing
|
||||
&& now - (_nav.lastRecomputeAt || 0) > NAV_RECOMPUTE_COOLDOWN_MS) {
|
||||
_nav.recomputing = true;
|
||||
_nav.lastRecomputeAt = now;
|
||||
_recomputeRoute(gcj).finally(() => { if (_nav) _nav.recomputing = false; });
|
||||
return; // 本帧不更新进度,等新路线
|
||||
}
|
||||
if (proj.index !== _nav.idx) {
|
||||
_nav.idx = proj.index;
|
||||
_redrawRoute(_nav.idx);
|
||||
}
|
||||
// 箭头位置:偏差在吸附范围内就贴到路线上,否则用真实位置
|
||||
const anchor = (proj.meters <= NAV_SNAP_M && proj.point) ? proj.point : me;
|
||||
// 朝向:沿路线往后看几个点算切线,比"我→下一个点"稳得多(GPS 抖动不会乱转)
|
||||
const aheadIdx = Math.min(proj.index + 3, _nav.ptsBD.length - 1);
|
||||
const travelHeading = _bearing(_nav.ptsBD[proj.index], _nav.ptsBD[aheadIdx]);
|
||||
_placeNavArrow(anchor);
|
||||
// 地图始终按「行进方向」朝上(不跟手机朝向)
|
||||
const mapDeg = (_headingSupported === false) ? 0 : travelHeading;
|
||||
// 箭头指手机朝向;没有罗盘权限就让它跟着行进方向(朝前)
|
||||
const arrowDeg = (typeof _compassHeading === "number")
|
||||
? (_compassHeading - mapDeg)
|
||||
: 0;
|
||||
_rotateNavArrow(arrowDeg);
|
||||
_centerOnUser(anchor, travelHeading);
|
||||
|
||||
// 剩余距离/时间(按进度线性折算,仅用于展示)
|
||||
const total = _nav.ptsBD.length - 1;
|
||||
const ratio = total > 0 ? Math.max(0, 1 - _nav.idx / total) : 0;
|
||||
const leftM = Math.round((_nav.distance || 0) * ratio);
|
||||
const leftS = Math.round((_nav.duration || 0) * ratio);
|
||||
const travelled = (_nav.distance || 0) * (total > 0 ? _nav.idx / total : 0);
|
||||
|
||||
// 第一行:当前指引「前方 120 米 右前方转弯」
|
||||
const actEl = document.getElementById("nav-banner-action");
|
||||
if (actEl) {
|
||||
const guide = _navGuidance(travelled);
|
||||
if (guide.text) actEl.textContent = guide.text;
|
||||
_setTurnIcon(guide.kind);
|
||||
}
|
||||
// 第二行:剩余距离与时间
|
||||
const bannerText = document.getElementById("nav-banner-text");
|
||||
if (bannerText) {
|
||||
bannerText.textContent = leftM < 1000
|
||||
? "剩余 " + leftM + " 米 · 约 " + Math.max(1, Math.round(leftS / 60)) + " 分钟"
|
||||
: "剩余 " + (leftM / 1000).toFixed(1) + " 公里 · 约 " +
|
||||
Math.max(1, Math.round(leftS / 60)) + " 分钟";
|
||||
}
|
||||
// 到达判定用「到终点的真实距离」,避免 GPS 抖动跳点就结束导航
|
||||
const dest = _nav.ptsBD[_nav.ptsBD.length - 1];
|
||||
const toDest = _haversineM(me.lat, me.lng, dest.lat, dest.lng);
|
||||
if (toDest < 25) {
|
||||
showToast("已到达车辆附近");
|
||||
stopNavigation();
|
||||
}
|
||||
}
|
||||
|
||||
// 当前该播报哪一段:按「已走里程」在分段累计距离里定位
|
||||
// 返回 { text: 文案, kind: straight|left|right|uturn },kind 用来画导航条左边的图标
|
||||
function _navGuidance(travelled) {
|
||||
if (!_nav || !_nav.stepEnds || !_nav.stepEnds.length) {
|
||||
return { text: "", kind: "straight" };
|
||||
}
|
||||
const ends = _nav.stepEnds;
|
||||
const steps = _nav.steps || [];
|
||||
let i = ends.findIndex(e => e > travelled);
|
||||
const isLast = (i === -1) || (i >= ends.length - 1);
|
||||
if (i === -1) i = ends.length - 1;
|
||||
const left = Math.max(0, Math.round(ends[i] - travelled));
|
||||
if (isLast) {
|
||||
return {
|
||||
text: left > 5 ? "前方 " + left + " 米 到达目的地" : "即将到达目的地",
|
||||
kind: "straight"
|
||||
};
|
||||
}
|
||||
const step = steps[i] || {};
|
||||
// 优先用转向名(右前方转弯/左转…),没有就用指引文本的最后一小段
|
||||
let action = step.turn || "";
|
||||
if (!action && step.text) {
|
||||
const parts = step.text.split(/[,,]/);
|
||||
action = parts[parts.length - 1] || step.text;
|
||||
}
|
||||
if (!action) action = "继续前行";
|
||||
return { text: "前方 " + left + " 米 " + action, kind: _turnKind(step.turn) };
|
||||
}
|
||||
|
||||
async function _recomputeRoute(gcj) { // gcj = {lat, lng}(GCJ02)
|
||||
if (!_nav || !_nav.destLat) return;
|
||||
try {
|
||||
const data = await _requestNavRoute(gcj.lat, gcj.lng,
|
||||
_nav.destLat, _nav.destLng);
|
||||
if (!data) return;
|
||||
_applyRoute(data);
|
||||
showToast("已重新规划路线");
|
||||
} catch (e) {
|
||||
console.warn("[导航] 重算失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function _requestNavRoute(originLat, originLng, destLat, destLng) {
|
||||
const url = "/api/nav_route?mode=walking"
|
||||
+ "&origin_lat=" + originLat + "&origin_lng=" + originLng
|
||||
+ "&dest_lat=" + destLat + "&dest_lng=" + destLng;
|
||||
const resp = await fetch(url, { headers: { "Authorization": "Bearer " + authToken } });
|
||||
const json = await resp.json();
|
||||
const d = json && json.data;
|
||||
if (json.rtn_code !== 0 || !d || !d.points || !d.points.length) {
|
||||
const msg = (json && json.message) || "没有拿到路线";
|
||||
const err = new Error(msg);
|
||||
// 后端已挡掉超远距离;这里再认一次文案,前端可静默处理
|
||||
if (json && (json.error_kind === "too_far" || /太远|200Km/i.test(msg))) {
|
||||
err.tooFar = true;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
// 用接口结果重建导航状态(首次与重算共用)
|
||||
function _applyRoute(d) {
|
||||
_nav.ptsGcj = d.points;
|
||||
_nav.ptsBD = d.points.map(pt => {
|
||||
const c = offsetCoord(pt[1], pt[0]);
|
||||
return new BMapGL.Point(c.lng, c.lat);
|
||||
});
|
||||
_nav.distance = d.distance;
|
||||
_nav.duration = d.duration;
|
||||
_nav.idx = 0;
|
||||
_nav.recomputing = false;
|
||||
// 分段指引:把 steps 的累计距离算出来,tick 里按「已走里程」定位当前段
|
||||
_nav.steps = (d.steps || []).map(s => ({
|
||||
distance: s.distance || 0,
|
||||
turn: s.turn_type || "",
|
||||
text: String(s.instruction || "").replace(/<[^>]+>/g, "")
|
||||
}));
|
||||
let acc = 0;
|
||||
_nav.stepEnds = _nav.steps.map(s => (acc += s.distance));
|
||||
_redrawRoute(0);
|
||||
}
|
||||
|
||||
function stopNavigation() {
|
||||
_navEpoch++; // 让还在 await 的 startNavigation 作废
|
||||
if (_nav && _nav.watchId !== null && navigator.geolocation) {
|
||||
navigator.geolocation.clearWatch(_nav.watchId);
|
||||
}
|
||||
if (_nav && _nav.timer) clearTimeout(_nav.timer);
|
||||
_clearNavLayers();
|
||||
_clearNavArrow();
|
||||
_nav = null;
|
||||
_navBanner(false);
|
||||
_navPill(false);
|
||||
_navBtnText("导航");
|
||||
try { if (map.resetHeading) map.resetHeading(); } catch (e) {}
|
||||
_headingSupported = null;
|
||||
}
|
||||
|
||||
function toggleNavigation() {
|
||||
const bike = selectedBike;
|
||||
if (!bike) return;
|
||||
if (_nav && String(_nav.destCode) === String(bike.code)) {
|
||||
stopNavigation();
|
||||
return;
|
||||
}
|
||||
startNavigation(bike);
|
||||
}
|
||||
|
||||
// 拖动地图后:显示「返回导航」,超时自动回正。
|
||||
// 注意:移动端 dragend 经常不触发,所以计时器从 dragstart 就开始,
|
||||
// 并且在 dragging/moving 里不断续期——手指一离开就重新倒计时。
|
||||
let _navSelfMoveUntil = 0; // 我们自己调 setCenter/panBy 的时间窗,避免误判成用户拖动
|
||||
function _markProgrammaticMove() { _navSelfMoveUntil = Date.now() + 250; }
|
||||
|
||||
function _scheduleResume() {
|
||||
if (!_nav) return;
|
||||
if (_nav.timer) clearTimeout(_nav.timer);
|
||||
_nav.timer = setTimeout(() => {
|
||||
if (_nav && _nav.follow === false) resumeNavigation();
|
||||
}, NAV_FREE_TIMEOUT);
|
||||
}
|
||||
|
||||
function _onMapDragStart() {
|
||||
if (!_nav) return;
|
||||
if (Date.now() < _navSelfMoveUntil) return; // 我们自己挪的,不算用户操作
|
||||
_nav.follow = false;
|
||||
_navPill(true);
|
||||
_scheduleResume();
|
||||
}
|
||||
|
||||
function _onMapDragging() {
|
||||
if (!_nav || _nav.follow !== false) return;
|
||||
_scheduleResume(); // 还在拖,续期
|
||||
}
|
||||
|
||||
function _onMapDragEnd() {
|
||||
if (!_nav || _nav.follow !== false) return;
|
||||
_scheduleResume();
|
||||
}
|
||||
|
||||
function resumeNavigation() {
|
||||
if (!_nav) return;
|
||||
_nav.follow = true;
|
||||
_navPill(false);
|
||||
if (_nav.timer) { clearTimeout(_nav.timer); _nav.timer = null; }
|
||||
// 回到行进方向并重新居中(用路线切线,别用"我→下一点")
|
||||
const i = Math.min(_nav.idx, _nav.ptsBD.length - 1);
|
||||
const j = Math.min(i + 3, _nav.ptsBD.length - 1);
|
||||
const heading = _bearing(_nav.ptsBD[i], _nav.ptsBD[j]);
|
||||
const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker)
|
||||
? autoLocationMarker.getPosition() : null;
|
||||
const anchor = me || _nav.ptsBD[i];
|
||||
_placeNavArrow(anchor);
|
||||
_centerOnUser(anchor, heading);
|
||||
}
|
||||
|
||||
async function startNavigation(bike) {
|
||||
if (_navLoading) return;
|
||||
const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker)
|
||||
? autoLocationMarker.getPosition() : null;
|
||||
if (!me) { showToast("请先开启定位,才能规划路线"); return; }
|
||||
if (!bike || !bike.latitude || !bike.longitude) {
|
||||
showToast("这辆车没有坐标,无法导航"); return;
|
||||
}
|
||||
// 兜底:太远就不导航(卡片上「导航」按钮本身已隐藏,正常点不到这里)。
|
||||
// 百度步行路线有 200km 上限,超了会返回 status=2 的英文报错,不要把它抛给用户。
|
||||
try {
|
||||
const dest = offsetCoord(bike.latitude, bike.longitude); // GCJ02 -> BD09
|
||||
const straight = calcDistance(me.lat, me.lng, dest.lat, dest.lng);
|
||||
if (Number.isFinite(straight) && straight >= MAX_WALK_DISTANCE_M) return;
|
||||
} catch (e) { /* 距离算不出来就照常尝试 */ }
|
||||
|
||||
if (_nav) stopNavigation();
|
||||
const epoch = ++_navEpoch;
|
||||
_navLoading = true;
|
||||
_navBanner(true);
|
||||
const bannerText = document.getElementById("nav-banner-text");
|
||||
if (bannerText) bannerText.textContent = "正在规划路线…";
|
||||
|
||||
try {
|
||||
let gcj = null;
|
||||
if (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02) {
|
||||
gcj = coordtransform.bd09togcj02(me.lng, me.lat);
|
||||
}
|
||||
if (!gcj) throw new Error("坐标转换不可用");
|
||||
|
||||
const d = await _requestNavRoute(gcj[1], gcj[0], bike.latitude, bike.longitude);
|
||||
|
||||
// 路线回来时卡片已经被关掉了:直接放弃,不要把导航又"It's on"起来
|
||||
if (epoch !== _navEpoch) {
|
||||
_navBanner(false);
|
||||
_navBtnText("导航");
|
||||
return;
|
||||
}
|
||||
|
||||
_nav = {
|
||||
destCode: bike.code, destLat: bike.latitude, destLng: bike.longitude,
|
||||
follow: true, timer: null, watchId: null,
|
||||
walking: [], remaining: [], endMarker: null, idx: 0, recomputing: false
|
||||
};
|
||||
_applyRoute(d);
|
||||
_navBtnText("结束");
|
||||
|
||||
// 首次定位:压到屏幕下方 + 朝行进方向
|
||||
const start = _nav.ptsBD[0];
|
||||
const next = _nav.ptsBD[Math.min(1, _nav.ptsBD.length - 1)];
|
||||
_placeNavArrow(start);
|
||||
_rotateNavArrow(_bearing(start, next));
|
||||
_centerOnUser(start, _bearing(start, next));
|
||||
// 罗盘权限要在用户手势里申请(导航按钮的点击就是手势)
|
||||
_ensureCompassPermission();
|
||||
const actEl0 = document.getElementById("nav-banner-action");
|
||||
const g0 = _navGuidance(0);
|
||||
if (actEl0) actEl0.textContent = g0.text || "沿路线前行";
|
||||
_setTurnIcon(g0.kind);
|
||||
if (bannerText) {
|
||||
bannerText.textContent = d.distance < 1000
|
||||
? "剩余 " + Math.round(d.distance) + " 米 · 约 " +
|
||||
Math.max(1, Math.round(d.duration / 60)) + " 分钟"
|
||||
: "剩余 " + (d.distance / 1000).toFixed(1) + " 公里 · 约 " +
|
||||
Math.max(1, Math.round(d.duration / 60)) + " 分钟";
|
||||
}
|
||||
|
||||
// 收起卡片:导航要占满屏幕(关卡片不会停止导航)
|
||||
try { closeCard(); } catch (e) {}
|
||||
|
||||
// 持续跟随
|
||||
if (navigator.geolocation) {
|
||||
_nav.watchId = navigator.geolocation.watchPosition(
|
||||
pos => _navTick(pos.coords),
|
||||
err => console.warn("[导航] 定位失败", err.message),
|
||||
{ enableHighAccuracy: true, maximumAge: 3000, timeout: 10000 });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[导航] 失败", err);
|
||||
_navBanner(false);
|
||||
if (err && err.tooFar) {
|
||||
// 距离太远:静默退出,不弹报错(卡片上的「导航」按钮本来也已隐藏)
|
||||
_navBtnText("导航");
|
||||
_nav = null;
|
||||
return;
|
||||
}
|
||||
showToast("导航失败:" + (err && err.message ? err.message : "请稍后再试"));
|
||||
if (_nav && !_nav.ptsBD) _nav = null;
|
||||
} finally {
|
||||
_navLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 地图拖动事件(只注册一次)
|
||||
(function _bindNavMapEvents() {
|
||||
const bind = () => {
|
||||
// navigation.js 在 map.js 之前执行,此时 `let map` 还在 TDZ,
|
||||
// 直接读会抛 ReferenceError,所以统一延后到下一轮宏任务再绑。
|
||||
if (typeof map === "undefined" || !map || !map.addEventListener || map.__navBound) return;
|
||||
map.__navBound = true;
|
||||
map.addEventListener("dragstart", _onMapDragStart);
|
||||
map.addEventListener("dragging", _onMapDragging);
|
||||
map.addEventListener("dragend", _onMapDragEnd);
|
||||
};
|
||||
setTimeout(bind, 0);
|
||||
})();
|
||||
@@ -1,3 +1,7 @@
|
||||
/* 共享电动车:申请/接受/权限/解绑/共享开锁还车/横幅与申请弹窗。
|
||||
* 从 static/js/map.js 拆出。 */
|
||||
|
||||
|
||||
// ================= 共享电动车 =================
|
||||
function shareApi(url, method, body) {
|
||||
const opts = { method: method || "GET", headers: {} };
|
||||
@@ -6,7 +10,7 @@
|
||||
opts.headers["Content-Type"] = "application/json";
|
||||
opts.body = JSON.stringify(body);
|
||||
}
|
||||
return apiFetch(url, opts).then(r => r.json());
|
||||
return fetch(url, opts).then(r => r.json());
|
||||
}
|
||||
|
||||
// ===== 私密备注(昵称) 工具 =====
|
||||
@@ -246,7 +250,8 @@
|
||||
try {
|
||||
const data = await shareApi("/api/share/active");
|
||||
if (data.rtn_code !== 0) return;
|
||||
shareActiveList = data.data || [];
|
||||
// 接口异常时 data.data 可能是对象/字符串,不是数组 → forEach 会抛错并每秒刷屏
|
||||
shareActiveList = Array.isArray(data.data) ? data.data : [];
|
||||
shareActiveList.forEach(it => { it._countdownDeadline = performance.now() + Math.max(0, Number(it.remaining_seconds) || 0) * 1000; });
|
||||
let html = "";
|
||||
shareActiveList.forEach((it, idx) => {
|
||||
@@ -285,6 +290,7 @@
|
||||
document.getElementById("share-return-modal").classList.add("show");
|
||||
}
|
||||
function updateShareCountdowns() {
|
||||
if (!Array.isArray(shareActiveList)) return; // 接口异常时不刷屏
|
||||
shareActiveList.forEach((it, idx) => {
|
||||
const el = document.getElementById('share-countdown-' + idx);
|
||||
if (!el) return;
|
||||
@@ -331,15 +337,3 @@
|
||||
if (btn) { btn.disabled = false; btn.textContent = "确认还车"; }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 初始化(登录后/页面加载) ----------
|
||||
function shareAfterLogin() {
|
||||
refreshShareBanners();
|
||||
setTimeout(() => checkPendingShareRequests(), 800);
|
||||
}
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (authToken) shareAfterLogin();
|
||||
setInterval(() => { if (authToken) { checkAuthStatus(); checkOrderStatus(); refreshShareBanners(); } }, 20000);
|
||||
setInterval(() => { if (authToken) checkPendingShareRequests(); }, 30000);
|
||||
setTimeout(maybeAutoShowVersion, 1200);
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
/* 车辆订阅:停车点提醒与定时用车(规则的增删改查)。
|
||||
* 从 static/js/map.js 拆出。 */
|
||||
|
||||
|
||||
// ========== 订阅提醒(我的 → 车辆订阅) ==========
|
||||
let subscribeLocations = [];
|
||||
const SUB_WEEKDAYS = { 0: "每天", 1: "周一", 2: "周二", 3: "周三", 4: "周四", 5: "周五", 6: "周六", 7: "周日" };
|
||||
async function openSubscribeModal() {
|
||||
closeAllModals();
|
||||
SettingsPages.open("subscribe-modal");
|
||||
await loadSubscribeLocations();
|
||||
loadSubscribeRules();
|
||||
}
|
||||
function closeSubscribeModal() {
|
||||
SettingsPages.back();
|
||||
}
|
||||
async function loadSubscribeLocations() {
|
||||
const sel = document.getElementById("sub-location");
|
||||
sel.innerHTML = '<option value="">加载中...</option>';
|
||||
try {
|
||||
const resp = await fetch("/api/campus/locations");
|
||||
const data = await resp.json();
|
||||
// 订阅只针对「停车点」(楼/兴趣点只用于起终点归属)
|
||||
subscribeLocations = ((data.rtn_code === 0 ? data.data : []) || [])
|
||||
.filter(l => l.kind === "parking");
|
||||
} catch (err) {
|
||||
subscribeLocations = [];
|
||||
}
|
||||
sel.innerHTML = subscribeLocations.length
|
||||
? subscribeLocations.map(l => `<option value="${l.id}">${escHtml(l.name)}</option>`).join("")
|
||||
: '<option value="">(管理员尚未配置停车点)</option>';
|
||||
}
|
||||
function subRuleRowHtml(r) {
|
||||
const loc = subscribeLocations.find(l => l.id === r.location_id);
|
||||
const locName = loc ? loc.name : (r.location_name || "停车点已删除");
|
||||
const hh = String(Math.floor(r.minute_of_day / 60)).padStart(2, "0");
|
||||
const mm = String(r.minute_of_day % 60).padStart(2, "0");
|
||||
const kindText = (r.kind_labels && r.kind_labels.length)
|
||||
? r.kind_labels.join("/") : "全部车型";
|
||||
const eMin = r.min_electric != null ? r.min_electric : 0;
|
||||
const eMax = r.max_electric != null ? r.max_electric : 100;
|
||||
const sortLabel = r.sort_by_label || r.sort_by || "";
|
||||
const tags = [];
|
||||
if (r.auto_unlock) {
|
||||
tags.push(`自动开锁 · ${kindText} · 电量${eMin}-${eMax}% · ${sortLabel} · 重试${r.retry_times || 3}次`);
|
||||
}
|
||||
return `
|
||||
<div class="device-item" style="display:block;padding:9px 12px;border-bottom:1px solid var(--bg-tertiary,#ececf1);">
|
||||
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;">
|
||||
<div style="font-size:13px;line-height:1.6;min-width:0;">
|
||||
<b>${escHtml(locName)}</b>
|
||||
<span style="color:var(--text-secondary);"> · ${SUB_WEEKDAYS[r.weekday] || "每周"} ${hh}:${mm}</span>
|
||||
<div style="font-size:11.5px;color:var(--text-secondary);">${r.enabled ? "已启用" : "已停用"}${r.notify_enabled ? " · 邮件提醒" : ""}</div>
|
||||
${tags.length ? `<div style="font-size:11.5px;color:#005bbf;">${escHtml(tags[0])}</div>` : ""}
|
||||
</div>
|
||||
<div style="display:flex;gap:6px;flex:0 0 auto;">
|
||||
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#ececf1;" onclick="toggleSubscribeRule(${r.id}, ${r.enabled ? 0 : 1})">${r.enabled ? "停用" : "启用"}</button>
|
||||
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#fce4ec;color:#c62828;" onclick="deleteSubscribeRule(${r.id})">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
// 订阅表单「更多筛选」折叠开关(高级调优项默认收起)
|
||||
function toggleSubAdvanced() {
|
||||
const box = document.getElementById("sub-advanced");
|
||||
if (!box) return;
|
||||
const show = box.style.display === "none";
|
||||
box.style.display = show ? "block" : "none";
|
||||
}
|
||||
async function loadSubscribeRules() {
|
||||
const box = document.getElementById("subscribe-list");
|
||||
box.innerHTML = '<div class="device-loading">加载中...</div>';
|
||||
try {
|
||||
const resp = await fetch("/api/subscribe/rules", {
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code !== 0) {
|
||||
box.innerHTML = `<div class="device-loading">${escHtml(data.message || "加载失败")}</div>`;
|
||||
return;
|
||||
}
|
||||
const rules = data.data || [];
|
||||
box.innerHTML = rules.length
|
||||
? rules.map(subRuleRowHtml).join("")
|
||||
: '<div class="device-loading">暂无规则,在下方添加</div>';
|
||||
} catch (err) {
|
||||
box.innerHTML = '<div class="device-loading">网络错误,请重试</div>';
|
||||
}
|
||||
}
|
||||
async function addSubscribeRule() {
|
||||
const locationId = Number(document.getElementById("sub-location").value || 0);
|
||||
const weekday = Number(document.getElementById("sub-weekday").value);
|
||||
const time = document.getElementById("sub-time").value;
|
||||
const notify = document.getElementById("sub-notify").checked;
|
||||
const auto = document.getElementById("sub-auto").checked;
|
||||
const kinds = [...document.querySelectorAll(".sub-kind:checked")].map(el => el.value);
|
||||
const minE = Number(document.getElementById("sub-min-e").value || 0);
|
||||
const maxE = Number(document.getElementById("sub-max-e").value || 100);
|
||||
const sortBy = document.getElementById("sub-sort").value;
|
||||
const retry = Number(document.getElementById("sub-retry").value || 3);
|
||||
|
||||
if (!locationId) { showToast("请先选择停车点(需要管理员先配置停车点)"); return; }
|
||||
if (!/^\d{2}:\d{2}$/.test(time)) { showToast("请选择时间"); return; }
|
||||
if (!kinds.length) { showToast("至少选择一个车型"); return; }
|
||||
if (!(minE >= 0 && maxE <= 100 && minE <= maxE)) { showToast("电量区间需在 0-100 且下限≤上限"); return; }
|
||||
if (auto) {
|
||||
const ok = await appConfirm(
|
||||
"开启自动开锁后,命中规则时系统会用你的账号直接开锁车辆。\n\n" +
|
||||
`筛选:${kinds.map(k => ({small:"小车",big:"大车",red:"红车"}[k])).join("/")},` +
|
||||
`电量 ${minE}%-${maxE}%,${document.getElementById("sub-sort").selectedOptions[0].textContent};` +
|
||||
`被他人抢先时最多重试 ${retry} 次。`,
|
||||
{ title: "开启自动开锁", okText: "确认添加" });
|
||||
if (!ok) return;
|
||||
}
|
||||
try {
|
||||
const resp = await fetch("/api/subscribe/rules", {
|
||||
method: "POST",
|
||||
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
location_id: locationId, weekday, time,
|
||||
notify_enabled: notify, auto_unlock: auto,
|
||||
kinds, min_electric: minE, max_electric: maxE,
|
||||
sort_by: sortBy, retry_times: retry
|
||||
})
|
||||
});
|
||||
const data = await resp.json();
|
||||
showToast(data.message || (data.rtn_code === 0 ? "已添加" : "添加失败"));
|
||||
if (data.rtn_code === 0) loadSubscribeRules();
|
||||
} catch (err) {
|
||||
showToast("网络错误,请重试");
|
||||
}
|
||||
}
|
||||
async function toggleSubscribeRule(ruleId, enable) {
|
||||
try {
|
||||
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
||||
method: "PUT",
|
||||
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ enabled: !!enable })
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code === 0) loadSubscribeRules();
|
||||
else showToast(data.message || "操作失败");
|
||||
} catch (err) { showToast("网络错误"); }
|
||||
}
|
||||
async function deleteSubscribeRule(ruleId) {
|
||||
try {
|
||||
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
||||
method: "DELETE",
|
||||
headers: { "Authorization": `Bearer ${authToken}` }
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.rtn_code === 0) loadSubscribeRules();
|
||||
else showToast(data.message || "删除失败");
|
||||
} catch (err) { showToast("网络错误"); }
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/* Modal visibility, keyboard containment and focus restoration. */
|
||||
(function () {
|
||||
'use strict';
|
||||
const selector = '.auth-modal,.bell-modal,.return-modal,.qr-modal,.token-expired-modal,.return-confirm-modal,.unlock-confirm-modal,.lost-modal,#bike-card';
|
||||
const focusable = 'button:not([disabled]),a[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex="0"]';
|
||||
const previous = new WeakMap();
|
||||
function containBackground() {
|
||||
const open = [...document.querySelectorAll(selector)].filter(el => el.classList.contains('show'));
|
||||
const modal = open.at(-1), settings = document.getElementById('settings-page');
|
||||
const active = modal || (settings && !settings.hidden ? settings : null);
|
||||
for (const child of document.body.children) {
|
||||
if (['SCRIPT','STYLE','LINK'].includes(child.tagName)) continue;
|
||||
if (active) child.inert = !(child === active || child.contains(active) || (modal?.id === 'bike-card' && child.matches('.card-overlay.show')));
|
||||
else if (!child.matches(selector)) child.inert = false;
|
||||
}
|
||||
}
|
||||
function sync(el) {
|
||||
const open = el.classList.contains('show');
|
||||
const activeElement = document.activeElement, hadFocus = el.contains(activeElement);
|
||||
el.inert = !open;
|
||||
el.setAttribute('aria-hidden', String(!open));
|
||||
if (!el.hasAttribute('role')) el.setAttribute('role', 'dialog');
|
||||
el.setAttribute('aria-modal', 'true');
|
||||
if (!el.hasAttribute('aria-label') && !el.hasAttribute('aria-labelledby')) {
|
||||
const title = el.querySelector('.auth-header,.unlock-confirm-title,.return-confirm-title,.bike-card-title,.qr-header');
|
||||
el.setAttribute('aria-label', title?.textContent.trim().slice(0, 60) || '操作窗口');
|
||||
}
|
||||
if (open) {
|
||||
previous.set(el, activeElement);
|
||||
containBackground();
|
||||
queueMicrotask(() => {
|
||||
if (el.classList.contains('show')) [...el.querySelectorAll(focusable)].find(node => node.getClientRects().length)?.focus({ preventScroll: true });
|
||||
});
|
||||
} else if (hadFocus) {
|
||||
containBackground();
|
||||
const target = previous.get(el);
|
||||
if (target?.isConnected) target.focus({ preventScroll: true });
|
||||
else document.getElementById('auth-btn')?.focus({ preventScroll: true });
|
||||
}
|
||||
containBackground();
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.querySelectorAll(selector).forEach(el => {
|
||||
sync(el);
|
||||
new MutationObserver(records => { if (records.some(r => r.attributeName === 'class')) sync(el); }).observe(el, { attributes: true, attributeFilter: ['class'] });
|
||||
});
|
||||
const settings = document.getElementById('settings-page');
|
||||
if (settings) new MutationObserver(containBackground).observe(settings, { attributes:true, attributeFilter:['hidden'] });
|
||||
containBackground();
|
||||
document.addEventListener('keydown', event => {
|
||||
const dialogs = [...document.querySelectorAll(selector)].filter(el => el.classList.contains('show'));
|
||||
const el = dialogs.at(-1);
|
||||
if (!el) return;
|
||||
if (event.key === 'Escape') {
|
||||
const close = el.querySelector('.auth-close,.bike-card-close,.qr-close,#app-confirm-cancel,.unlock-confirm-btn.cancel,.return-confirm-btn.cancel,.return-confirm-cancel,[data-dialog-close]');
|
||||
if (close) { event.preventDefault(); close.click(); }
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab') return;
|
||||
const items = [...el.querySelectorAll(focusable)].filter(n => n.getClientRects().length);
|
||||
if (!items.length) { event.preventDefault(); return; }
|
||||
const first = items[0], last = items.at(-1);
|
||||
if (event.shiftKey && (document.activeElement === first || !el.contains(document.activeElement))) { event.preventDefault(); last.focus({ preventScroll: true }); }
|
||||
else if (!event.shiftKey && (document.activeElement === last || !el.contains(document.activeElement))) { event.preventDefault(); first.focus({ preventScroll: true }); }
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -1,19 +0,0 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
const key = 'xbniu_theme', media = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
let preference = 'system';
|
||||
try { preference = localStorage.getItem(key) || 'system'; } catch (_) {}
|
||||
function apply(value, save) {
|
||||
preference = ['light', 'dark', 'system'].includes(value) ? value : 'system';
|
||||
document.documentElement.dataset.theme = preference === 'system' ? (media.matches ? 'dark' : 'light') : preference;
|
||||
document.documentElement.style.colorScheme = document.documentElement.dataset.theme;
|
||||
if (save) { try { localStorage.setItem(key, preference); } catch (_) {} }
|
||||
document.querySelectorAll('[data-theme-choice]').forEach(el => el.setAttribute('aria-pressed', String(el.dataset.themeChoice === preference)));
|
||||
window.dispatchEvent(new Event('xbniu-theme-change'));
|
||||
}
|
||||
window.UIPreferences = { set: value => apply(value, true), isDark: () => document.documentElement.dataset.theme === 'dark', get: () => preference };
|
||||
apply(preference, false);
|
||||
media.addEventListener('change', () => { if (preference === 'system') apply(preference, false); });
|
||||
window.addEventListener('storage', e => { if (e.key === key) apply(e.newValue || 'system', false); });
|
||||
document.addEventListener('DOMContentLoaded', () => apply(preference, false));
|
||||
})();
|
||||
+145
-31
@@ -23,6 +23,7 @@ from db import get_db
|
||||
from email_utils import send_email
|
||||
|
||||
CHECK_INTERVAL = 30 # 调度精度:30 秒扫一次规则
|
||||
CATCHUP_WINDOW_MIN = 5 # 补发窗口:超过这么久就不再补(避免晚上补发早上的提醒)
|
||||
SCAN_FRESH_MINUTES = 20 # 采集点新鲜度
|
||||
MAX_RULES_PER_USER = 5
|
||||
|
||||
@@ -184,7 +185,65 @@ def latest_bike_points():
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def stat_location(loc):
|
||||
def refresh_bike_points(user_id=None):
|
||||
"""判定前拉一次最新地图(**只用 type=3 电动车**,别把单车混进候选)。
|
||||
|
||||
取数顺序:共享快照(60 秒,省上游) → 失败才用用户凭据直连一次。
|
||||
`type=1` 是共享单车,它的车牌号段也会被判成「小车」,混进来会导致
|
||||
「自动开锁开了一辆单车」和「附近有 12 辆其实 8 辆是单车」。
|
||||
|
||||
字段名用 `electric_quantity`(上游真实字段);写成 `electric` 会永远是
|
||||
None,电量筛选就全部落空(≥50% 的规则会报「附近暂无符合条件的车辆」)。
|
||||
"""
|
||||
from wechat import request_with_user_auth, request_api
|
||||
|
||||
def _fetch(use_snapshot_only=False):
|
||||
try:
|
||||
res = request_api("GET", "/project/map", params={"type": "3"})
|
||||
if isinstance(res, dict) and res.get("rtn_code") == 0:
|
||||
return res
|
||||
except Exception as exc:
|
||||
print(f"[订阅提醒] 快照读地图失败: {exc}")
|
||||
if use_snapshot_only or not user_id:
|
||||
return None
|
||||
try:
|
||||
res = request_with_user_auth(user_id, "GET", "/project/map",
|
||||
params={"type": "3"}, _silent=True)
|
||||
return res if isinstance(res, dict) and res.get("rtn_code") == 0 else None
|
||||
except Exception as exc:
|
||||
print(f"[订阅提醒] 用户凭据刷新地图失败: {exc}")
|
||||
return None
|
||||
|
||||
res = _fetch()
|
||||
if res is None:
|
||||
time.sleep(0.6) # 上游 503/抖动:等半秒再试一次
|
||||
res = _fetch()
|
||||
if res is None:
|
||||
return None
|
||||
|
||||
rows = []
|
||||
for st in ((res.get("data") or {}).get("bicycleStation") or []):
|
||||
lat, lng = st.get("latitude"), st.get("longitude")
|
||||
if lat is None or lng is None:
|
||||
continue
|
||||
electric = st.get("electric_quantity")
|
||||
if electric is None:
|
||||
electric = st.get("electricQuantity")
|
||||
if electric is None:
|
||||
electric = st.get("electric")
|
||||
rows.append({
|
||||
"bike_code": str(st.get("code") or ""),
|
||||
"latitude": lat,
|
||||
"longitude": lng,
|
||||
"state": st.get("state"),
|
||||
"status": st.get("status"),
|
||||
"electric": electric,
|
||||
"bike_type": "3",
|
||||
})
|
||||
return rows or None
|
||||
|
||||
|
||||
def stat_location(loc, user_id=None, fresh=True):
|
||||
"""统计某个停车点附近的车辆。返回 None 表示该地点没有可用判定(缺坐标)。"""
|
||||
if loc is None:
|
||||
return None
|
||||
@@ -193,7 +252,11 @@ def stat_location(loc):
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
points = latest_bike_points()
|
||||
points = None
|
||||
if fresh:
|
||||
points = refresh_bike_points(user_id)
|
||||
if not points:
|
||||
points = latest_bike_points()
|
||||
return bikes_near_parking(points, loc)
|
||||
|
||||
|
||||
@@ -231,6 +294,31 @@ def _live_coord(user_id: int, code: str, btype=None):
|
||||
return None
|
||||
|
||||
|
||||
def _discard_pending_order(user_id: int, order_id, code: str,
|
||||
lat=None, lng=None) -> bool:
|
||||
"""下单成功但开锁失败:把这张半成品订单关掉。
|
||||
|
||||
不清理的话,下一次重试会再叠一张新订单 —— 上游会同时挂着几张
|
||||
没人骑的订单,用户还可能被算未支付。
|
||||
"""
|
||||
from wechat import request_with_user_auth
|
||||
data = {"order_id": order_id}
|
||||
if lat is not None and lng is not None:
|
||||
data.update({"latitude": lat, "longitude": lng, "code": code})
|
||||
for path in ("/record/return", "/record/orderClose"):
|
||||
try:
|
||||
res = request_with_user_auth(user_id, "POST", path, data=data, _silent=True)
|
||||
except Exception as exc:
|
||||
print(f"[订阅开锁] 清理半成品订单 {order_id} 调 {path} 异常: {exc}")
|
||||
continue
|
||||
if isinstance(res, dict) and res.get("rtn_code") == 0:
|
||||
print(f"[订阅开锁] 半成品订单 {order_id} 已通过 {path} 关闭")
|
||||
return True
|
||||
msg = (res or {}).get("message") if isinstance(res, dict) else None
|
||||
print(f"[订阅开锁] 清理半成品订单 {order_id} 失败({path}): {msg}")
|
||||
return False
|
||||
|
||||
|
||||
def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
|
||||
"""真实自动开锁:扫码 → 创建订单 → 开锁(全部使用订阅人自己的凭据)。
|
||||
|
||||
@@ -300,8 +388,15 @@ def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
|
||||
opened = request_with_user_auth(user_id, "POST", "/record/qrOrder",
|
||||
data={"order_id": order_id}, _silent=True)
|
||||
if opened.get("rtn_code") != 0:
|
||||
# 半成品订单必须撤销,否则下一次重试会再叠一张
|
||||
cleaned = _discard_pending_order(user_id, order_id, code, lat, lng)
|
||||
msg = opened.get("message") or "开锁指令失败"
|
||||
if cleaned:
|
||||
msg += "(已撤销本次下单)"
|
||||
else:
|
||||
msg += "(本次下单可能残留在上游,请稍后在订单页检查)"
|
||||
return {"success": False, "occupied": False, "order_id": str(order_id),
|
||||
"message": opened.get("message") or "开锁指令失败"}
|
||||
"message": msg}
|
||||
|
||||
# 4) 本地落单 + 计时器 + 起点位置(与手动开锁一致,source='subscribe')
|
||||
try:
|
||||
@@ -414,29 +509,20 @@ def _user_email(user_id):
|
||||
return get_user_alert_email(user_id)
|
||||
|
||||
|
||||
def record_rule_result(rule_id, status, message):
|
||||
conn = get_db()
|
||||
conn.execute("UPDATE subscribe_rules SET last_run_at=datetime('now','+8 hours'), last_run_status=?, last_run_message=? WHERE id=?",
|
||||
(status, str(message)[:500], rule_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def fire_rule(rule: dict):
|
||||
"""执行一条规则:按筛选条件统计候选车辆;需要时自动开锁并邮件汇报。"""
|
||||
from db import get_user_alert_email
|
||||
locs = load_locations()
|
||||
loc = next((l for l in locs if l["id"] == rule["location_id"]), None)
|
||||
to_email = get_user_alert_email(rule["user_id"])
|
||||
if rule.get("notify_enabled") and not to_email:
|
||||
record_rule_result(rule["id"], "failed", "未配置提醒邮箱")
|
||||
if not to_email:
|
||||
return False
|
||||
if loc is None:
|
||||
record_rule_result(rule["id"], "failed", "订阅停车点已删除")
|
||||
return False
|
||||
|
||||
flt = rule_filters(rule)
|
||||
points = latest_bike_points()
|
||||
# 先刷新地图再看有几辆:订阅最怕“看到的是别人已经骑走的数据”
|
||||
points = refresh_bike_points(rule.get("user_id")) or latest_bike_points()
|
||||
stat = bikes_near_parking(points, loc)
|
||||
# 候选:只含「符合车型/电量筛选」的空闲可用车,已按排序规则排好
|
||||
candidates = parking_candidates(
|
||||
@@ -508,21 +594,36 @@ def fire_rule(rule: dict):
|
||||
|
||||
plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details)
|
||||
html_body = _render_html(title, lead, details)
|
||||
delivered = send_email(to_email, f"【小白超人】{title}", plain, html_body) if rule.get("notify_enabled") else True
|
||||
status = "failed" if (unlock_result and not unlock_result.get("success")) or not delivered else "success" if candidates else "no_match"
|
||||
message = title + (";邮件发送失败,请检查提醒邮箱和服务配置" if not delivered else "")
|
||||
record_rule_result(rule["id"], status, message)
|
||||
return status != "failed"
|
||||
return send_email(to_email, f"【小白超人】{title}", plain, html_body)
|
||||
|
||||
# ========== 调度 ==========
|
||||
|
||||
def _scheduler_loop():
|
||||
"""固定节拍扫描:按单调时钟对齐,不用「干完活再睡 30 秒」,
|
||||
否则发信/自动开锁一慢,节拍就整体漂移。"""
|
||||
next_at = time.monotonic()
|
||||
while True:
|
||||
try:
|
||||
_tick()
|
||||
except Exception as e:
|
||||
print(f"[订阅提醒] 调度异常: {e}")
|
||||
time.sleep(CHECK_INTERVAL)
|
||||
next_at += CHECK_INTERVAL
|
||||
delay = next_at - time.monotonic()
|
||||
if delay <= 0:
|
||||
# 落后太多(比如机器卡了一下)就重新对齐,不追帧
|
||||
next_at = time.monotonic() + CHECK_INTERVAL
|
||||
continue
|
||||
time.sleep(delay)
|
||||
|
||||
|
||||
def _fire_rule_async(rule: dict):
|
||||
"""单条规则在独立线程里执行,避免串行 fire 把整轮节拍拖过一分钟。"""
|
||||
try:
|
||||
ok = fire_rule(rule)
|
||||
except Exception as e:
|
||||
ok = False
|
||||
print(f"[订阅提醒] 规则 {rule['id']} 发送失败: {e}")
|
||||
print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule.get('user_id')}, 发送={ok})")
|
||||
|
||||
|
||||
def _tick():
|
||||
@@ -533,11 +634,31 @@ def _tick():
|
||||
minute_of_day = now.hour * 60 + now.minute
|
||||
|
||||
conn = get_db()
|
||||
|
||||
# 补发要有下界:7:50 的规则、服务 22:00 才启动,不该在晚上补发早上的提醒。
|
||||
# 超过 CATCHUP_WINDOW_MIN 的直接记成「今天已处理」,不发信。
|
||||
window_start = max(0, minute_of_day - CATCHUP_WINDOW_MIN)
|
||||
stale = conn.execute("""
|
||||
SELECT id FROM subscribe_rules
|
||||
WHERE enabled = 1 AND weekday IN (0, ?) AND minute_of_day < ?
|
||||
AND last_fired_on != ?
|
||||
""", (weekday, window_start, today)).fetchall()
|
||||
if stale:
|
||||
for r in stale:
|
||||
conn.execute("UPDATE subscribe_rules SET last_fired_on = ? WHERE id = ?",
|
||||
(today, r["id"]))
|
||||
conn.commit()
|
||||
print(f"[订阅提醒] {len(stale)} 条规则已过补发窗口(>{CATCHUP_WINDOW_MIN} 分钟),"
|
||||
f"今天不再补发")
|
||||
|
||||
# `<=` 而不是 `=`:只要今天还没发过,到点或过点(窗口内)都补一次。
|
||||
# 用 `=` 的时候,一轮跑超过一分钟就会漏掉那一分钟,当天不再补。
|
||||
rules = conn.execute("""
|
||||
SELECT * FROM subscribe_rules
|
||||
WHERE enabled = 1 AND weekday IN (0, ?) AND minute_of_day = ?
|
||||
WHERE enabled = 1 AND weekday IN (0, ?)
|
||||
AND minute_of_day <= ? AND minute_of_day >= ?
|
||||
AND last_fired_on != ?
|
||||
""", (weekday, minute_of_day, today)).fetchall()
|
||||
""", (weekday, minute_of_day, window_start, today)).fetchall()
|
||||
if not rules:
|
||||
conn.close()
|
||||
return
|
||||
@@ -551,14 +672,7 @@ def _tick():
|
||||
rule = dict(r)
|
||||
if not rule.get("notify_enabled") and not rule.get("auto_unlock"):
|
||||
continue
|
||||
try:
|
||||
record_rule_result(rule["id"], "running", "正在检查符合条件的车辆")
|
||||
ok = fire_rule(rule)
|
||||
except Exception as e:
|
||||
ok = False
|
||||
record_rule_result(rule["id"], "failed", "执行失败,请检查凭证有效期和网络后重试")
|
||||
print(f"[订阅提醒] 规则 {rule['id']} 执行失败: {type(e).__name__}")
|
||||
print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule['user_id']}, 发送={ok})")
|
||||
threading.Thread(target=_fire_rule_async, args=(rule,), daemon=True).start()
|
||||
|
||||
|
||||
def start_subscribe_scheduler():
|
||||
|
||||
+1095
-928
File diff suppressed because it is too large
Load Diff
+1473
-1469
File diff suppressed because it is too large
Load Diff
+1035
-1022
File diff suppressed because it is too large
Load Diff
+259
-259
@@ -1,263 +1,263 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>全车寻铃进度</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: #1a1a2e;
|
||||
color: #eee;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
.container {
|
||||
background: #16213e;
|
||||
border-radius: 16px;
|
||||
padding: 32px;
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
|
||||
}
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
.header h1 {
|
||||
font-size: 22px;
|
||||
margin-bottom: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.header p {
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 12px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.stat {
|
||||
background: #0f3460;
|
||||
border-radius: 12px;
|
||||
padding: 16px 12px;
|
||||
text-align: center;
|
||||
}
|
||||
.stat-value {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
color: #e94560;
|
||||
}
|
||||
.stat-value.success { color: #4ade80; }
|
||||
.stat-value.failed { color: #f87171; }
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.progress-bar {
|
||||
background: #0f3460;
|
||||
border-radius: 10px;
|
||||
height: 20px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #e94560, #ff6b6b);
|
||||
border-radius: 10px;
|
||||
transition: width 0.2s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding-right: 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
min-width: 40px;
|
||||
}
|
||||
.progress-fill.done { background: linear-gradient(90deg, #4ade80, #22c55e); }
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
.btn {
|
||||
flex: 1;
|
||||
padding: 14px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-cancel {
|
||||
background: #e94560;
|
||||
color: white;
|
||||
}
|
||||
.btn-cancel:hover { background: #d63850; }
|
||||
.btn-close {
|
||||
background: #333;
|
||||
color: #ccc;
|
||||
}
|
||||
.btn-close:hover { background: #444; }
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.log {
|
||||
margin-top: 20px;
|
||||
background: #0a0a1a;
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
max-height: 120px;
|
||||
overflow-y: auto;
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
}
|
||||
.log-entry { margin-bottom: 4px; }
|
||||
.log-entry.success { color: #4ade80; }
|
||||
.log-entry.failed { color: #f87171; }
|
||||
</style>
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>全车寻铃进度</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: #1a1a2e;
|
||||
color: #eee;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
.container {
|
||||
background: #16213e;
|
||||
border-radius: 16px;
|
||||
padding: 32px;
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
|
||||
}
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
.header h1 {
|
||||
font-size: 22px;
|
||||
margin-bottom: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.header p {
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
}
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 12px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.stat {
|
||||
background: #0f3460;
|
||||
border-radius: 12px;
|
||||
padding: 16px 12px;
|
||||
text-align: center;
|
||||
}
|
||||
.stat-value {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
color: #e94560;
|
||||
}
|
||||
.stat-value.success { color: #4ade80; }
|
||||
.stat-value.failed { color: #f87171; }
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.progress-bar {
|
||||
background: #0f3460;
|
||||
border-radius: 10px;
|
||||
height: 20px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #e94560, #ff6b6b);
|
||||
border-radius: 10px;
|
||||
transition: width 0.2s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding-right: 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
min-width: 40px;
|
||||
}
|
||||
.progress-fill.done { background: linear-gradient(90deg, #4ade80, #22c55e); }
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
.btn {
|
||||
flex: 1;
|
||||
padding: 14px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-cancel {
|
||||
background: #e94560;
|
||||
color: white;
|
||||
}
|
||||
.btn-cancel:hover { background: #d63850; }
|
||||
.btn-close {
|
||||
background: #333;
|
||||
color: #ccc;
|
||||
}
|
||||
.btn-close:hover { background: #444; }
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.log {
|
||||
margin-top: 20px;
|
||||
background: #0a0a1a;
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
max-height: 120px;
|
||||
overflow-y: auto;
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
}
|
||||
.log-entry { margin-bottom: 4px; }
|
||||
.log-entry.success { color: #4ade80; }
|
||||
.log-entry.failed { color: #f87171; }
|
||||
</style>
|
||||
<link rel="stylesheet" href="/static/css/ui-system.css">
|
||||
<script defer src="/static/js/ui-motion.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>
|
||||
<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
全车寻铃
|
||||
</h1>
|
||||
<p id="status-text">正在连接...</p>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat">
|
||||
<div class="stat-value" id="done-count">0</div>
|
||||
<div class="stat-label">已完成</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value success" id="success-count">0</div>
|
||||
<div class="stat-label">成功</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value failed" id="failed-count">0</div>
|
||||
<div class="stat-label">失败</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill" id="progress-fill" style="width: 0%">
|
||||
<span id="progress-text">0%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn btn-cancel" id="cancel-btn" onclick="cancelTask()">取消任务</button>
|
||||
<button class="btn btn-close" onclick="closeWindow()">关闭</button>
|
||||
</div>
|
||||
|
||||
<div class="log" id="log"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const taskId = params.get('task_id');
|
||||
const total = parseInt(params.get('total') || '0');
|
||||
|
||||
document.getElementById('status-text').textContent = `共 ${total} 辆车`;
|
||||
|
||||
let cancelled = false;
|
||||
let completed = false;
|
||||
|
||||
function addLog(msg, type = '') {
|
||||
const log = document.getElementById('log');
|
||||
const entry = document.createElement('div');
|
||||
entry.className = 'log-entry ' + type;
|
||||
entry.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
|
||||
log.appendChild(entry);
|
||||
log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function updateUI(data) {
|
||||
const { status, done, total, success, failed } = data;
|
||||
|
||||
document.getElementById('done-count').textContent = done;
|
||||
document.getElementById('success-count').textContent = success;
|
||||
document.getElementById('failed-count').textContent = failed;
|
||||
|
||||
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
|
||||
const fill = document.getElementById('progress-fill');
|
||||
fill.style.width = pct + '%';
|
||||
document.getElementById('progress-text').textContent = pct + '%';
|
||||
|
||||
if (pct >= 100 || status === 'completed' || status === 'cancelled') {
|
||||
fill.classList.add('done');
|
||||
document.getElementById('cancel-btn').disabled = true;
|
||||
completed = true;
|
||||
}
|
||||
|
||||
if (status === 'cancelled') {
|
||||
document.getElementById('status-text').textContent = '❌ 已取消';
|
||||
addLog('任务已取消', '');
|
||||
} else if (status === 'completed') {
|
||||
document.getElementById('status-text').textContent = '✅ 全部完成';
|
||||
addLog(`完成!成功:${success} 失败:${failed}`, '');
|
||||
}
|
||||
}
|
||||
|
||||
function cancelTask() {
|
||||
if (cancelled || completed) return;
|
||||
cancelled = true;
|
||||
document.getElementById('cancel-btn').disabled = true;
|
||||
document.getElementById('cancel-btn').textContent = '取消中...';
|
||||
fetch(`/api/ring_cancel/${taskId}`, { method: 'POST' })
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
addLog(d.message || '取消请求已发送', '');
|
||||
})
|
||||
.catch(() => addLog('取消请求失败', 'failed'));
|
||||
}
|
||||
|
||||
function closeWindow() {
|
||||
if (!completed && !cancelled) {
|
||||
if (!confirm('任务还在运行,确定要关闭吗?')) return;
|
||||
}
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>
|
||||
<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
全车寻铃
|
||||
</h1>
|
||||
<p id="status-text">正在连接...</p>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat">
|
||||
<div class="stat-value" id="done-count">0</div>
|
||||
<div class="stat-label">已完成</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value success" id="success-count">0</div>
|
||||
<div class="stat-label">成功</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value failed" id="failed-count">0</div>
|
||||
<div class="stat-label">失败</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill" id="progress-fill" style="width: 0%">
|
||||
<span id="progress-text">0%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn btn-cancel" id="cancel-btn" onclick="cancelTask()">取消任务</button>
|
||||
<button class="btn btn-close" onclick="closeWindow()">关闭</button>
|
||||
</div>
|
||||
|
||||
<div class="log" id="log"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const taskId = params.get('task_id');
|
||||
const total = parseInt(params.get('total') || '0');
|
||||
|
||||
document.getElementById('status-text').textContent = `共 ${total} 辆车`;
|
||||
|
||||
let cancelled = false;
|
||||
let completed = false;
|
||||
|
||||
function addLog(msg, type = '') {
|
||||
const log = document.getElementById('log');
|
||||
const entry = document.createElement('div');
|
||||
entry.className = 'log-entry ' + type;
|
||||
entry.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
|
||||
log.appendChild(entry);
|
||||
log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function updateUI(data) {
|
||||
const { status, done, total, success, failed } = data;
|
||||
|
||||
document.getElementById('done-count').textContent = done;
|
||||
document.getElementById('success-count').textContent = success;
|
||||
document.getElementById('failed-count').textContent = failed;
|
||||
|
||||
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
|
||||
const fill = document.getElementById('progress-fill');
|
||||
fill.style.width = pct + '%';
|
||||
document.getElementById('progress-text').textContent = pct + '%';
|
||||
|
||||
if (pct >= 100 || status === 'completed' || status === 'cancelled') {
|
||||
fill.classList.add('done');
|
||||
document.getElementById('cancel-btn').disabled = true;
|
||||
completed = true;
|
||||
}
|
||||
|
||||
if (status === 'cancelled') {
|
||||
document.getElementById('status-text').textContent = '❌ 已取消';
|
||||
addLog('任务已取消', '');
|
||||
} else if (status === 'completed') {
|
||||
document.getElementById('status-text').textContent = '✅ 全部完成';
|
||||
addLog(`完成!成功:${success} 失败:${failed}`, '');
|
||||
}
|
||||
}
|
||||
|
||||
function cancelTask() {
|
||||
if (cancelled || completed) return;
|
||||
cancelled = true;
|
||||
document.getElementById('cancel-btn').disabled = true;
|
||||
document.getElementById('cancel-btn').textContent = '取消中...';
|
||||
fetch(`/api/ring_cancel/${taskId}`, { method: 'POST' })
|
||||
.then(r => r.json())
|
||||
.then(d => {
|
||||
addLog(d.message || '取消请求已发送', '');
|
||||
})
|
||||
.catch(() => addLog('取消请求失败', 'failed'));
|
||||
}
|
||||
|
||||
function closeWindow() {
|
||||
if (!completed && !cancelled) {
|
||||
if (!confirm('任务还在运行,确定要关闭吗?')) return;
|
||||
}
|
||||
uiCloseWindow();
|
||||
}
|
||||
|
||||
// SSE 连接
|
||||
const es = new EventSource(`/api/ring_progress/${taskId}`);
|
||||
|
||||
es.onmessage = (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data);
|
||||
if (data.type === 'progress') {
|
||||
updateUI(data);
|
||||
} else if (data.type === 'done') {
|
||||
es.close();
|
||||
} else if (data.type === 'error') {
|
||||
addLog(data.message, 'failed');
|
||||
es.close();
|
||||
}
|
||||
} catch (err) {}
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
addLog('连接断开', 'failed');
|
||||
es.close();
|
||||
};
|
||||
|
||||
addLog('开始监听进度...', '');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
|
||||
// SSE 连接
|
||||
const es = new EventSource(`/api/ring_progress/${taskId}`);
|
||||
|
||||
es.onmessage = (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data);
|
||||
if (data.type === 'progress') {
|
||||
updateUI(data);
|
||||
} else if (data.type === 'done') {
|
||||
es.close();
|
||||
} else if (data.type === 'error') {
|
||||
addLog(data.message, 'failed');
|
||||
es.close();
|
||||
}
|
||||
} catch (err) {}
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
addLog('连接断开', 'failed');
|
||||
es.close();
|
||||
};
|
||||
|
||||
addLog('开始监听进度...', '');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+34
-34
@@ -1,34 +1,34 @@
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
# 测试各接口
|
||||
tests = [
|
||||
('/record/order', {'code': '51287', 'start_longitude': 116.98, 'start_latitude': 36.67}),
|
||||
('/record/checkLocation', {'longitude': 116.98, 'latitude': 36.67, 'bicycleCode': '51287'}),
|
||||
('/record/return', {'order_id': 15899504, 'longitude': 116.98, 'latitude': 36.67}),
|
||||
]
|
||||
|
||||
for path, body in tests:
|
||||
resp = requests.post(f'https://bike.sdlongren.com{path}', headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(path)
|
||||
print(' rtn_code:', data.get('rtn_code'))
|
||||
print(' code:', data.get('code'))
|
||||
print(' message:', data.get('message'))
|
||||
print(' data:', str(data.get('data'))[:200])
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
# 测试各接口
|
||||
tests = [
|
||||
('/record/order', {'code': '51287', 'start_longitude': 116.98, 'start_latitude': 36.67}),
|
||||
('/record/checkLocation', {'longitude': 116.98, 'latitude': 36.67, 'bicycleCode': '51287'}),
|
||||
('/record/return', {'order_id': 15899504, 'longitude': 116.98, 'latitude': 36.67}),
|
||||
]
|
||||
|
||||
for path, body in tests:
|
||||
resp = requests.post(f'https://bike.sdlongren.com{path}', headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(path)
|
||||
print(' rtn_code:', data.get('rtn_code'))
|
||||
print(' code:', data.get('code'))
|
||||
print(' message:', data.get('message'))
|
||||
print(' data:', str(data.get('data'))[:200])
|
||||
|
||||
+46
-46
@@ -1,46 +1,46 @@
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
tests = [
|
||||
# GET /user/packages - 我的卡包列表
|
||||
('GET', '/user/packages', None),
|
||||
# GET /packages/mapp - 推荐卡包列表
|
||||
('GET', '/packages/mapp', None),
|
||||
# GET /bus_packages/user_packages - 我的公交卡包
|
||||
('GET', '/bus_packages/user_packages', None),
|
||||
]
|
||||
|
||||
for method, path, body in tests:
|
||||
url = f'https://bike.sdlongren.com{path}'
|
||||
if method == 'GET':
|
||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||
else:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(f'=== {method} {path} ===')
|
||||
print(' rtn_code:', data.get('rtn_code'), 'code:', data.get('code'))
|
||||
print(' message:', data.get('message'))
|
||||
if data.get('data'):
|
||||
print(' data keys:', list(data.get('data', {}).keys()))
|
||||
d = data['data']
|
||||
# 打印卡包信息
|
||||
for k in ['bike_packages', 'packageList', 'package', 'packages', 'memberPackageCount', 'memberPackage']:
|
||||
if k in d:
|
||||
print(f' {k}:', str(d[k])[:300])
|
||||
print()
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
tests = [
|
||||
# GET /user/packages - 我的卡包列表
|
||||
('GET', '/user/packages', None),
|
||||
# GET /packages/mapp - 推荐卡包列表
|
||||
('GET', '/packages/mapp', None),
|
||||
# GET /bus_packages/user_packages - 我的公交卡包
|
||||
('GET', '/bus_packages/user_packages', None),
|
||||
]
|
||||
|
||||
for method, path, body in tests:
|
||||
url = f'https://bike.sdlongren.com{path}'
|
||||
if method == 'GET':
|
||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||
else:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(f'=== {method} {path} ===')
|
||||
print(' rtn_code:', data.get('rtn_code'), 'code:', data.get('code'))
|
||||
print(' message:', data.get('message'))
|
||||
if data.get('data'):
|
||||
print(' data keys:', list(data.get('data', {}).keys()))
|
||||
d = data['data']
|
||||
# 打印卡包信息
|
||||
for k in ['bike_packages', 'packageList', 'package', 'packages', 'memberPackageCount', 'memberPackage']:
|
||||
if k in d:
|
||||
print(f' {k}:', str(d[k])[:300])
|
||||
print()
|
||||
|
||||
+45
-45
@@ -1,45 +1,45 @@
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
tests = [
|
||||
# GET /user/packages - 从JS逆向得到的"我的卡包"
|
||||
('GET', '/user/packages', None),
|
||||
# 看看/user/info 里的 package 和 memberPackageCount
|
||||
('GET', '/user/info', None),
|
||||
# 可能的变体路径
|
||||
('GET', '/user/package', None),
|
||||
('GET', '/user/memberPackage', None),
|
||||
('GET', '/user/myPackage', None),
|
||||
('GET', '/packages/user', None),
|
||||
('GET', '/packages/my', None),
|
||||
]
|
||||
|
||||
for method, path, body in tests:
|
||||
url = f'https://bike.sdlongren.com{path}'
|
||||
if method == 'GET':
|
||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||
else:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(f'=== {method} {path} === rtn_code={data.get("rtn_code")} code={data.get("code")}')
|
||||
if data.get('rtn_code') == 0 and data.get('data'):
|
||||
for k, v in data['data'].items():
|
||||
if 'package' in k.lower() or 'card' in k.lower() or 'member' in k.lower() or 'count' in k.lower():
|
||||
print(f' {k}: {str(v)[:200]}')
|
||||
print()
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
tests = [
|
||||
# GET /user/packages - 从JS逆向得到的"我的卡包"
|
||||
('GET', '/user/packages', None),
|
||||
# 看看/user/info 里的 package 和 memberPackageCount
|
||||
('GET', '/user/info', None),
|
||||
# 可能的变体路径
|
||||
('GET', '/user/package', None),
|
||||
('GET', '/user/memberPackage', None),
|
||||
('GET', '/user/myPackage', None),
|
||||
('GET', '/packages/user', None),
|
||||
('GET', '/packages/my', None),
|
||||
]
|
||||
|
||||
for method, path, body in tests:
|
||||
url = f'https://bike.sdlongren.com{path}'
|
||||
if method == 'GET':
|
||||
resp = requests.get(url, headers=headers, timeout=10, verify=False)
|
||||
else:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print(f'=== {method} {path} === rtn_code={data.get("rtn_code")} code={data.get("code")}')
|
||||
if data.get('rtn_code') == 0 and data.get('data'):
|
||||
for k, v in data['data'].items():
|
||||
if 'package' in k.lower() or 'card' in k.lower() or 'member' in k.lower() or 'count' in k.lower():
|
||||
print(f' {k}: {str(v)[:200]}')
|
||||
print()
|
||||
|
||||
+41
-41
@@ -1,41 +1,41 @@
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
# 获取推荐卡包的完整字段
|
||||
resp = requests.get('https://bike.sdlongren.com/packages/mapp', headers=headers, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print('=== 推荐卡包完整字段 ===')
|
||||
if data.get('rtn_code') == 0 and data.get('data', {}).get('bike_packages'):
|
||||
pkg = data['data']['bike_packages'][0]
|
||||
print(json.dumps(pkg, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
print('所有字段:', list(pkg.keys()))
|
||||
|
||||
# /user/info 里的 package 字段完整内容
|
||||
resp2 = requests.get('https://bike.sdlongren.com/user/info', headers=headers, timeout=10, verify=False)
|
||||
data2 = resp2.json()
|
||||
print('=== user/info 中的 package 字段 ===')
|
||||
pkg_data = data2.get('data', {}).get('package', {})
|
||||
print(json.dumps(pkg_data, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
print('package 所有字段:', list(pkg_data.keys()))
|
||||
|
||||
# memberPackageCount
|
||||
print('memberPackageCount:', data2['data'].get('memberPackageCount'))
|
||||
print('spec_count:', data2['data'].get('spec_count'))
|
||||
import requests, time, json
|
||||
|
||||
token_id = '1291378'
|
||||
wx_signature = '8aab9d16b538ed83b02974937e90a0d70388020b'
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
headers = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-signature': wx_signature,
|
||||
'hsf-x-timestamp': timestamp,
|
||||
'hsf-x-tokenid': token_id,
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
# 获取推荐卡包的完整字段
|
||||
resp = requests.get('https://bike.sdlongren.com/packages/mapp', headers=headers, timeout=10, verify=False)
|
||||
data = resp.json()
|
||||
print('=== 推荐卡包完整字段 ===')
|
||||
if data.get('rtn_code') == 0 and data.get('data', {}).get('bike_packages'):
|
||||
pkg = data['data']['bike_packages'][0]
|
||||
print(json.dumps(pkg, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
print('所有字段:', list(pkg.keys()))
|
||||
|
||||
# /user/info 里的 package 字段完整内容
|
||||
resp2 = requests.get('https://bike.sdlongren.com/user/info', headers=headers, timeout=10, verify=False)
|
||||
data2 = resp2.json()
|
||||
print('=== user/info 中的 package 字段 ===')
|
||||
pkg_data = data2.get('data', {}).get('package', {})
|
||||
print(json.dumps(pkg_data, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
print('package 所有字段:', list(pkg_data.keys()))
|
||||
|
||||
# memberPackageCount
|
||||
print('memberPackageCount:', data2['data'].get('memberPackageCount'))
|
||||
print('spec_count:', data2['data'].get('spec_count'))
|
||||
|
||||
+43
-43
@@ -1,43 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""测试API坐标"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
import hashlib
|
||||
import urllib3
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
HEADERS = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-tokenid': '1291378',
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
ts = str(int(time.time()))
|
||||
raw = f"1291378GET/project/map{ts}"
|
||||
sig = hashlib.sha256(raw.encode()).hexdigest()[:40]
|
||||
HEADERS['hsf-x-timestamp'] = ts
|
||||
HEADERS['hsf-x-signature'] = sig
|
||||
|
||||
resp = requests.get('https://bike.sdlongren.com/project/map?type=3', headers=HEADERS, verify=False)
|
||||
data = resp.json()
|
||||
|
||||
# 打印返回的学校中心坐标和前3辆车的坐标
|
||||
if data.get('rtn_code') == 0 and data.get('data'):
|
||||
d = data['data']
|
||||
print('=== 学校中心坐标 ===')
|
||||
print(f'centerLatitude: {d.get("centerLatitude")}')
|
||||
print(f'centerLongitude: {d.get("centerLongitude")}')
|
||||
print()
|
||||
print('=== 前3辆车坐标 ===')
|
||||
for i, bike in enumerate(d.get('bicycleStation', [])[:3]):
|
||||
print(f'{i+1}. code={bike.get("code")}, lat={bike.get("latitude")}, lng={bike.get("longitude")}')
|
||||
else:
|
||||
print('请求失败:', data)
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""测试API坐标"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
import hashlib
|
||||
import urllib3
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
HEADERS = {
|
||||
'Host': 'bike.sdlongren.com',
|
||||
'hsf-x-tokenid': '1291378',
|
||||
'xweb_xhr': '1',
|
||||
'platform': 'xiaobai',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c38)XWEB/8518',
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'referer': 'https://servicewechat.com/wx10426ca961518f43/98/page-frame.html',
|
||||
}
|
||||
|
||||
ts = str(int(time.time()))
|
||||
raw = f"1291378GET/project/map{ts}"
|
||||
sig = hashlib.sha256(raw.encode()).hexdigest()[:40]
|
||||
HEADERS['hsf-x-timestamp'] = ts
|
||||
HEADERS['hsf-x-signature'] = sig
|
||||
|
||||
resp = requests.get('https://bike.sdlongren.com/project/map?type=3', headers=HEADERS, verify=False)
|
||||
data = resp.json()
|
||||
|
||||
# 打印返回的学校中心坐标和前3辆车的坐标
|
||||
if data.get('rtn_code') == 0 and data.get('data'):
|
||||
d = data['data']
|
||||
print('=== 学校中心坐标 ===')
|
||||
print(f'centerLatitude: {d.get("centerLatitude")}')
|
||||
print(f'centerLongitude: {d.get("centerLongitude")}')
|
||||
print()
|
||||
print('=== 前3辆车坐标 ===')
|
||||
for i, bike in enumerate(d.get('bicycleStation', [])[:3]):
|
||||
print(f'{i+1}. code={bike.get("code")}, lat={bike.get("latitude")}, lng={bike.get("longitude")}')
|
||||
else:
|
||||
print('请求失败:', data)
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const modules = ['map.js', 'map-account.js', 'map-orders.js', 'map-history.js', 'map-subscriptions.js', 'map-rental.js', 'map-utils.js', 'map-sharing.js', 'map-boot.js'];
|
||||
module.exports = modules.map(name => fs.readFileSync(path.join(__dirname, '../static/js', name), 'utf8')).join('\n');
|
||||
@@ -0,0 +1,139 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""管理员订单列表:已骑行分钟数。"""
|
||||
import datetime as dt
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from routes import admin as admin_routes
|
||||
|
||||
|
||||
class RidingMinutesTests(unittest.TestCase):
|
||||
def test_finished_order_uses_returned_at(self):
|
||||
rental = {"start_time": "2026-01-01 09:00:00",
|
||||
"returned_at": "2026-01-01 09:23:30"}
|
||||
self.assertEqual(23, admin_routes._riding_minutes(rental))
|
||||
|
||||
def test_active_order_uses_now(self):
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
start = dt.datetime.now(tz).replace(tzinfo=None) - dt.timedelta(minutes=7)
|
||||
rental = {"start_time": start.strftime("%Y-%m-%d %H:%M:%S"), "returned_at": None}
|
||||
self.assertIn(admin_routes._riding_minutes(rental), (6, 7))
|
||||
|
||||
def test_bad_timestamps_do_not_break_the_list(self):
|
||||
self.assertEqual(0, admin_routes._riding_minutes({"start_time": None}))
|
||||
self.assertEqual(0, admin_routes._riding_minutes({"start_time": "not-a-date"}))
|
||||
|
||||
|
||||
class AdminReturnTests(unittest.TestCase):
|
||||
"""管理端代还车必须复用「换点重试」链路,并回填实际还车时间。"""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.db_path = Path(self.tmp.name) / "admin.db"
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
conn.executescript("""
|
||||
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
|
||||
CREATE TABLE rentals (
|
||||
id INTEGER PRIMARY KEY, order_id TEXT, bike_code TEXT, email TEXT,
|
||||
user_id INTEGER, source TEXT, expired INTEGER DEFAULT 0,
|
||||
start_time TEXT, end_time TEXT, returned_at TEXT,
|
||||
end_latitude REAL, end_longitude REAL, end_label TEXT
|
||||
);
|
||||
INSERT INTO users (id, email) VALUES (7, 'rider@example.test');
|
||||
INSERT INTO rentals (id, order_id, bike_code, email, user_id, source,
|
||||
expired, start_time, end_time)
|
||||
VALUES (101, '9001', '50001', 'rider@example.test', 7, 'unlock',
|
||||
0, '2026-01-01 09:00:00', '2026-01-01 09:19:00');
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def _get_db(self):
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
def test_admin_return_uses_candidate_chain_and_records_returned_at(self):
|
||||
app = Flask(__name__)
|
||||
app.secret_key = "test"
|
||||
app.register_blueprint(admin_routes.bp)
|
||||
client = app.test_client()
|
||||
with client.session_transaction() as sess:
|
||||
sess["admin_logged_in"] = True
|
||||
|
||||
with patch.object(admin_routes, "get_db", self._get_db), \
|
||||
patch.object(admin_routes, "request_with_user_auth", return_value={
|
||||
"rtn_code": 0, "data": {"latitude": 36.53, "longitude": 116.78}}), \
|
||||
patch("routes.rental._try_return_candidates",
|
||||
return_value=({"rtn_code": 0}, (36.53, 116.78),
|
||||
["你上报的位置", "附近停车区"])) as chain, \
|
||||
patch("routes.rental._record_rental_end") as record_end, \
|
||||
patch("timer._try_card_pay_auto", return_value={}):
|
||||
resp = client.post("/api/admin/return", json={"rental_id": 101, "user_id": 7})
|
||||
|
||||
body = resp.get_json()
|
||||
self.assertEqual(0, body["rtn_code"])
|
||||
chain.assert_called_once()
|
||||
record_end.assert_called_once() # 回填 returned_at + 终点
|
||||
self.assertIn("used_nearest", body)
|
||||
|
||||
def test_admin_return_falls_back_to_rental_id_when_order_id_matches_nothing(self):
|
||||
"""order_id 是脏字符串、回填命中 0 行时,仍要按 rental_id 把单子收掉。"""
|
||||
app = Flask(__name__)
|
||||
app.secret_key = "test"
|
||||
app.register_blueprint(admin_routes.bp)
|
||||
client = app.test_client()
|
||||
with client.session_transaction() as sess:
|
||||
sess["admin_logged_in"] = True
|
||||
|
||||
with patch.object(admin_routes, "get_db", self._get_db), \
|
||||
patch.object(admin_routes, "request_with_user_auth", return_value={
|
||||
"rtn_code": 0, "data": {"latitude": 36.53, "longitude": 116.78}}), \
|
||||
patch("routes.rental._try_return_candidates",
|
||||
return_value=({"rtn_code": 0}, (36.53, 116.78), ["你上报的位置"])), \
|
||||
patch("routes.rental._record_rental_end", return_value=0), \
|
||||
patch("timer._try_card_pay_auto", return_value={}):
|
||||
resp = client.post("/api/admin/return", json={"rental_id": 101, "user_id": 7})
|
||||
|
||||
self.assertEqual(0, resp.get_json()["rtn_code"])
|
||||
conn = self._get_db()
|
||||
row = conn.execute("SELECT expired, returned_at FROM rentals WHERE id = 101").fetchone()
|
||||
conn.close()
|
||||
self.assertEqual(1, row["expired"])
|
||||
self.assertTrue(row["returned_at"]) # 兜底也写了实际还车时间
|
||||
|
||||
def test_admin_return_reports_success_when_local_write_fails(self):
|
||||
"""上游成功、本地写库失败:仍返回成功 + 提示稍后同步,别让管理员重复点。"""
|
||||
app = Flask(__name__)
|
||||
app.secret_key = "test"
|
||||
app.register_blueprint(admin_routes.bp)
|
||||
client = app.test_client()
|
||||
with client.session_transaction() as sess:
|
||||
sess["admin_logged_in"] = True
|
||||
|
||||
with patch.object(admin_routes, "get_db", self._get_db), \
|
||||
patch.object(admin_routes, "request_with_user_auth", return_value={
|
||||
"rtn_code": 0, "data": {"latitude": 36.53, "longitude": 116.78}}), \
|
||||
patch("routes.rental._try_return_candidates",
|
||||
return_value=({"rtn_code": 0}, (36.53, 116.78), ["你上报的位置"])), \
|
||||
patch("routes.rental._record_rental_end",
|
||||
side_effect=RuntimeError("database is locked")), \
|
||||
patch("timer._try_card_pay_auto", return_value={}):
|
||||
resp = client.post("/api/admin/return", json={"rental_id": 101, "user_id": 7})
|
||||
|
||||
body = resp.get_json()
|
||||
self.assertEqual(0, body["rtn_code"])
|
||||
self.assertFalse(body["local_synced"])
|
||||
self.assertIn("本地记录稍后同步", body["message"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,27 +0,0 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const vm = require('node:vm');
|
||||
const fs = require('node:fs');
|
||||
const source = fs.readFileSync(require('node:path').join(__dirname,'../static/js/api-client.js'),'utf8');
|
||||
|
||||
test('submission lock prevents duplicates while preserving the next editor state', async () => {
|
||||
const context={window:{},AbortController,Promise,setTimeout,clearTimeout};
|
||||
vm.createContext(context);vm.runInContext(source,context);
|
||||
let resolve, count=0;
|
||||
const button={textContent:'保存修改',disabled:false,setAttribute(){},removeAttribute(){}};
|
||||
const work=()=>{count++; return new Promise(done=>{resolve=()=>{button.textContent='添加规则';done('saved');};});};
|
||||
const first=context.window.AppAPI.run('save-rule',button,work);
|
||||
const second=context.window.AppAPI.run('save-rule',button,work);
|
||||
await Promise.resolve();assert.equal(count,1);assert.equal(button.disabled,true);
|
||||
resolve();assert.deepEqual(await Promise.all([first,second]),['saved','saved']);
|
||||
assert.equal(button.disabled,false);assert.equal(button.textContent,'添加规则');
|
||||
});
|
||||
test('request deadline aborts once and never retries a mutation', async () => {
|
||||
let deadline, calls=0;
|
||||
const context={window:{},AbortController,Promise,setTimeout:fn=>{deadline=fn;return 1;},clearTimeout(){},fetch:(_,options)=>{
|
||||
calls++;return new Promise((_,reject)=>options.signal.addEventListener('abort',()=>{const e=new Error();e.name='AbortError';reject(e);}));
|
||||
}};
|
||||
vm.createContext(context);vm.runInContext(source,context);
|
||||
const result=context.window.AppAPI.fetch('/api/order/unlock',{method:'POST'});
|
||||
deadline();await assert.rejects(result,/请求超时/);assert.equal(calls,1);
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const BikeData = require('../static/js/bike-data.js');
|
||||
|
||||
test('missing, empty, invalid and zero batteries remain distinct', () => {
|
||||
for (const value of [null, undefined, '', ' ', true, 'NaN', Infinity, -1, 101]) {
|
||||
assert.equal(BikeData.electric({electric_quantity:value}), null);
|
||||
}
|
||||
assert.equal(BikeData.electric({electric_quantity:0,electricQuantity:90}), 0);
|
||||
assert.equal(BikeData.electric({electric_quantity:'45'}), 45);
|
||||
});
|
||||
test('occupancy and faults take priority; low charge is consistent for strings and numbers', () => {
|
||||
assert.equal(BikeData.state({state:'1',status:'1',electric_quantity:10}), 'inuse');
|
||||
assert.equal(BikeData.state({state:4,status:0,electric_quantity:10}), 'locked');
|
||||
assert.equal(BikeData.state({state:2,status:0,electric_quantity:10}), 'reserved');
|
||||
assert.equal(BikeData.state({state:1,status:0,electric_quantity:10}), 'lowbattery');
|
||||
assert.equal(BikeData.labels[BikeData.state({state:1,status:0,electric_quantity:10})], '低电量');
|
||||
assert.equal(BikeData.state({state:99,status:0}), 'unknown');
|
||||
});
|
||||
test('plate validation supports actual five and eight digit formats only', () => {
|
||||
for (const value of ['50301','51201','30000193']) assert.equal(BikeData.validCode(value), true);
|
||||
for (const value of ['1234','123456','30000193e0','-51201','51 201','12345']) assert.equal(BikeData.validCode(value), false);
|
||||
assert.equal(BikeData.kind({code:'51001'}), 'small');
|
||||
assert.equal(BikeData.kind({code:'51101'}), 'big');
|
||||
assert.equal(BikeData.kind({code:'30000193'}), 'red');
|
||||
});
|
||||
test('filtering preserves unknown batteries only when no minimum is requested', () => {
|
||||
const bike={state:1,status:0,code:'51201'};
|
||||
assert.equal(BikeData.matches(bike,{onlyAvailable:true,minElectric:0,kind:'big'}),true);
|
||||
assert.equal(BikeData.matches(bike,{onlyAvailable:true,minElectric:20,kind:'big'}),false);
|
||||
assert.equal(BikeData.matches({...bike,electric_quantity:25},{onlyAvailable:true,minElectric:20,kind:'big'}),true);
|
||||
assert.equal(BikeData.matches({...bike,status:1,electric_quantity:80},{onlyAvailable:true,minElectric:20}),false);
|
||||
assert.ok(BikeData.distance({lat:36.53,lng:116.78},{lat:36.531,lng:116.78}) > 110);
|
||||
assert.equal(BikeData.distance(null,{lat:36.53,lng:116.78}),null);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""凭据告警的误报回归。
|
||||
|
||||
线上事故:部署后全站收到「微信凭据已过期」邮件,实际 token 没过期。
|
||||
根因:只填 token_id、没有 access_token 的用户,请求只能用假签名,
|
||||
上游一律回 102001;告警把 102001 当成「凭据过期」于是全员误报。
|
||||
"""
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import alerts
|
||||
|
||||
|
||||
class CredentialAlertTests(unittest.TestCase):
|
||||
def test_token_only_user_never_triggers_expiry_mail(self):
|
||||
"""没有 access_token → 假签名必被拒 → 不能发「已过期」邮件。"""
|
||||
sent = []
|
||||
|
||||
class FakeConn:
|
||||
def execute(self, sql, params=()):
|
||||
class Cur:
|
||||
def fetchall(_self):
|
||||
return [{"id": 1, "email": "a@b.c", "token_id": "1356419",
|
||||
"alert_email": None}]
|
||||
return Cur()
|
||||
def close(self):
|
||||
pass
|
||||
def commit(self):
|
||||
pass
|
||||
|
||||
with patch.object(alerts, "get_db", return_value=FakeConn()), \
|
||||
patch("wechat.request_with_user_auth",
|
||||
return_value={"rtn_code": 102001, "token_invalid": True}), \
|
||||
patch.object(alerts, "_send_alert",
|
||||
side_effect=lambda *a, **k: sent.append(a) or True), \
|
||||
patch.object(alerts, "get_alert_emails", return_value=["admin@example.test"]):
|
||||
count = alerts.check_user_credentials_alive()
|
||||
|
||||
self.assertEqual(0, count)
|
||||
self.assertEqual([], sent, "只填 token_id 的用户不该收到失效邮件")
|
||||
|
||||
def test_legacy_default_token_is_ignored_everywhere(self):
|
||||
self.assertTrue(alerts._is_legacy_default_token("1291378"))
|
||||
self.assertFalse(alerts._is_legacy_default_token("1356419"))
|
||||
self.assertFalse(alerts._is_legacy_default_token(None))
|
||||
self.assertFalse(alerts._is_legacy_default_token(""))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -60,8 +60,8 @@ check("freshness stale 为数字", isinstance(d["stale_seconds"], int))
|
||||
r = client.get("/api/history/stats?days=1").get_json()["data"]
|
||||
check("stats days=1 回显", r["days"] == 1)
|
||||
check("stats 24桶", "00" in r["hourly_distribution"] and "23" in r["hourly_distribution"])
|
||||
expected_states = {"available", "used", "locked", "reserved", "low", "unknown"}
|
||||
check("stats 桶含6状态", set(r["hourly_distribution"]["08"].keys()) == expected_states)
|
||||
expected_states = {"available", "used", "locked", "reserved", "low"}
|
||||
check("stats 桶含5状态", set(r["hourly_distribution"]["08"].keys()) == expected_states)
|
||||
|
||||
# ---- stats days=30 ----
|
||||
r = client.get("/api/history/stats?days=30").get_json()["data"]
|
||||
@@ -100,13 +100,13 @@ check("days=0 收敛1", r["days"] == 1)
|
||||
Path(handle.name).unlink(missing_ok=True)
|
||||
print(f"RESULT: {{'FAIL' if failures else 'ALL PASS'}} ({{len(failures)}} failures)")
|
||||
sys.exit(1 if failures else 0)
|
||||
'''.replace("{root}", str(ROOT).replace("\\", "\\\\")).replace("{{", "{").replace("}}", "}")
|
||||
'''.replace("{root}", str(ROOT).replace("\\", "\\\\"))
|
||||
|
||||
|
||||
def test_history_30d_contract():
|
||||
r = subprocess.run([sys.executable, "-c", CHILD],
|
||||
capture_output=True, text=True, timeout=180,
|
||||
cwd=str(ROOT))
|
||||
cwd=str(ROOT), encoding="utf-8", errors="replace")
|
||||
out = (r.stdout or "") + (r.stderr or "")
|
||||
print(out[-4000:] if len(out) > 4000 else out)
|
||||
assert r.returncode == 0, "子进程契约验证失败(见上方输出)"
|
||||
assert r.returncode == 0, "子进程契约验证失败(见上方输出)"
|
||||
@@ -3,7 +3,7 @@ const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const source = require('./frontend-source.cjs');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../static/js/map.js'), 'utf8');
|
||||
const loadingCode = source.slice(source.indexOf(' let mapRequest = null;'), source.indexOf(' // ========== 手动刷新'));
|
||||
const badgeCode = source.slice(source.indexOf(' function mapSnapshotNow()'), source.indexOf(' function showToast(msg)'));
|
||||
|
||||
@@ -29,7 +29,6 @@ function environment() {
|
||||
clearTimeout: id => timers.delete(id),
|
||||
renderMap: result => renders.push(result), setupClusterListener() {}, showLoginGate() {},
|
||||
showToast: message => notices.push(message), friendlyError: error => error.message,
|
||||
apiFetch: (...args) => context.fetch(...args),
|
||||
fetch: () => { context.fetchCount++; return new Promise(done => { resolve = done; }); }, fetchCount: 0
|
||||
};
|
||||
vm.createContext(context); vm.runInContext(loadingCode + badgeCode, context);
|
||||
|
||||
@@ -40,17 +40,20 @@ class OrderControlTests(unittest.TestCase):
|
||||
})
|
||||
|
||||
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([
|
||||
((7, "POST", "/record/checkLocation"), {
|
||||
"data": {"longitude": 116.981, "latitude": 36.671,
|
||||
"data": {"longitude": exp_lng, "latitude": exp_lat,
|
||||
"bicycleCode": "50001"}
|
||||
}),
|
||||
((7, "POST", "/project/coordinate"), {
|
||||
"data": {"order_id": "9001", "code": "50001"}
|
||||
}),
|
||||
((7, "POST", "/record/close"), {
|
||||
"data": {"order_id": "9001", "end_longitude": 116.981,
|
||||
"end_latitude": 36.671}
|
||||
"data": {"order_id": "9001", "end_longitude": exp_lng,
|
||||
"end_latitude": exp_lat}
|
||||
}),
|
||||
], [(call.args, call.kwargs) for call in upstream.call_args_list])
|
||||
|
||||
|
||||
@@ -3,7 +3,11 @@ const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const source = require('./frontend-source.cjs');
|
||||
// map.js 已拆分为多个模块(navigation/share/subscribe/map),按 HTML 里的顺序加载
|
||||
const MODULES = ['navigation.js', 'share.js', 'subscribe.js', 'map.js'];
|
||||
const source = MODULES.map(name =>
|
||||
fs.readFileSync(path.join(__dirname, '../static/js', name), 'utf8')
|
||||
).join('\n;\n');
|
||||
|
||||
async function environment({ dependencies = true } = {}) {
|
||||
const elements = new Map(), requests = [], notices = [], events = {};
|
||||
@@ -162,3 +166,56 @@ test('countdown accounts for background throttling instead of decrementing only
|
||||
assert.equal(e.element('order-countdown').textContent, '本轮剩余 9:55');
|
||||
assert.match(e.element('order-final-time').textContent, /第 1\/1 轮/);
|
||||
});
|
||||
|
||||
// 回归:拆分模块时曾把「寻车 / 丢失模式 / 车牌查询」整段定义切走,
|
||||
// 只剩调用处 → 点按钮直接 ReferenceError。这里钉住关键入口必须存在。
|
||||
test('find-bike, plate lookup and lost-mode entry points are all defined', async () => {
|
||||
const e = await environment();
|
||||
const must = ['findBike', '_doFindBikeRequest', 'scanCode',
|
||||
'showLostModal', 'closeLostModal', 'enableLostMode', 'disableLostMode',
|
||||
'_onPageUnload', '_onVisibilityChange', 'findCurrentOrderBike'];
|
||||
const missing = must.filter(name => vm.runInContext(`typeof ${name}`, e.context) !== 'function');
|
||||
assert.deepEqual(missing, []);
|
||||
});
|
||||
|
||||
// 回归:寻车必须真的打到 /api/find_bike,而不是被 try/catch 吞掉
|
||||
test('findBike posts to the find_bike endpoint and reports success', async () => {
|
||||
const e = await environment();
|
||||
const calls = [];
|
||||
e.context.fetch = async (url, options) => {
|
||||
calls.push({ url: String(url), options });
|
||||
return { json: async () => ({ rtn_code: 0 }) };
|
||||
};
|
||||
vm.runInContext(`selectedBike = { code: '51241' }; _findClickCount = 0; findBike();`, e.context);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(calls.length, 1);
|
||||
assert.match(calls[0].url, /\/api\/find_bike/);
|
||||
assert.match(JSON.stringify(calls[0].options.body), /51241/);
|
||||
});
|
||||
|
||||
// 回归:自己账号开锁成功时,closeUnlockConfirm 会清空 unlockPendingCode,
|
||||
// 本地 activeRental / localStorage 绝不能把车牌写成 null。
|
||||
test('self unlock keeps the bike code after the confirm dialog clears the pending code', async () => {
|
||||
const e = await environment();
|
||||
const store = {};
|
||||
e.context.localStorage.setItem = (key, value) => { store[key] = value; };
|
||||
e.context.fetch = async (url) => {
|
||||
if (url === '/api/order/unlock') {
|
||||
return { json: async () => ({ rtn_code: 0, order_id: '9001',
|
||||
data: { remaining: 1140, end_time: '2026-01-01 00:19:00' } }) };
|
||||
}
|
||||
return { json: async () => ({ rtn_code: 0, data: {} }) };
|
||||
};
|
||||
vm.runInContext(`
|
||||
unlockPendingCode = '51241';
|
||||
unlockPendingPosition = { lat: 36.5, lng: 116.7 };
|
||||
unlockChoice = { mode: 'self' };
|
||||
`, e.context);
|
||||
|
||||
await vm.runInContext('doUnlockBike()', e.context);
|
||||
|
||||
// closeUnlockConfirm 已经执行过,全局变量确实被清空了
|
||||
assert.equal(vm.runInContext('unlockPendingCode', e.context), null);
|
||||
const stored = JSON.parse(store.xbniu_rental_key || '{}');
|
||||
assert.equal(stored.bike_code, '51241');
|
||||
});
|
||||
|
||||
+402
-13
@@ -145,6 +145,7 @@ class OrderSyncTests(unittest.TestCase):
|
||||
with patch.object(timer, "get_db", self._get_db), \
|
||||
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||
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, "start_rental_timer"):
|
||||
result = timer._check_user_order(7)
|
||||
@@ -167,6 +168,7 @@ class OrderSyncTests(unittest.TestCase):
|
||||
{"rtn_code": 500, "message": "return rejected"},
|
||||
]
|
||||
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._time, "sleep"), \
|
||||
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
||||
@@ -184,6 +186,7 @@ class OrderSyncTests(unittest.TestCase):
|
||||
{"rtn_code": 0, "message": "ok"},
|
||||
]
|
||||
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, "_try_card_pay_auto", return_value={"success": True}), \
|
||||
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
||||
@@ -206,6 +209,7 @@ class OrderSyncTests(unittest.TestCase):
|
||||
"rental_rounds": 2, "protect_card": True,
|
||||
}
|
||||
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, "get_user_rental_settings", return_value=settings), \
|
||||
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,
|
||||
}
|
||||
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, "get_user_rental_settings", return_value=settings), \
|
||||
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
||||
@@ -424,17 +429,25 @@ class OrderSyncTests(unittest.TestCase):
|
||||
app.secret_key = "test"
|
||||
app.register_blueprint(rental_routes.bp)
|
||||
client = app.test_client()
|
||||
responses = [
|
||||
{"rtn_code": 0, "parkNoShow": False},
|
||||
{"rtn_code": -1, "message": "response timeout"},
|
||||
{"rtn_code": 0, "data": {"nonDealOrder": None}},
|
||||
]
|
||||
|
||||
# 新版还车链路:先发用户坐标,失败才换候选点重试(不再有 checkLocation 预检)。
|
||||
# 这里让 /record/return 一直超时,靠订单状态确认判成功。
|
||||
calls = []
|
||||
|
||||
def fake_auth(user_id, method, path, **kwargs):
|
||||
calls.append(path)
|
||||
if path == "/record/return":
|
||||
return {"rtn_code": -1, "message": "response timeout"}
|
||||
if path == "/user/info":
|
||||
return {"rtn_code": 0, "data": {"nonDealOrder": None}}
|
||||
return {"rtn_code": 0, "data": {}}
|
||||
|
||||
with patch.object(rental_routes, "get_db", self._get_db), \
|
||||
patch.object(rental_routes, "get_current_user", return_value={
|
||||
"id": 7, "email": "rider@example.test"
|
||||
}), \
|
||||
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||
patch.object(rental_routes, "request_with_user_auth", side_effect=responses), \
|
||||
patch.object(rental_routes, "request_with_user_auth", side_effect=fake_auth), \
|
||||
patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \
|
||||
patch.object(rental_routes, "_cancel_rental_timers"):
|
||||
response = client.post("/api/order/return", json={
|
||||
@@ -445,6 +458,8 @@ class OrderSyncTests(unittest.TestCase):
|
||||
self.assertEqual(0, data["rtn_code"])
|
||||
self.assertIn("订单状态确认", data["message"])
|
||||
self.assertEqual(1, self._expired(101))
|
||||
self.assertNotIn("/record/checkLocation", calls) # 位置不再当准入条件
|
||||
self.assertGreaterEqual(calls.count("/record/return"), 1)
|
||||
|
||||
def test_manual_timer_finish_requires_owner_and_rejects_real_orders(self):
|
||||
app = Flask(__name__)
|
||||
@@ -474,23 +489,27 @@ class OrderSyncTests(unittest.TestCase):
|
||||
active = {"rtn_code": 0, "data": {"nonDealOrder": {
|
||||
"order_id": "9001", "status": 2
|
||||
}}}
|
||||
responses = [
|
||||
{"rtn_code": 0, "parkNoShow": False},
|
||||
{"rtn_code": 500, "message": "return rejected"},
|
||||
active, active, active, active,
|
||||
]
|
||||
|
||||
# 所有候选点都被上游拒绝,且订单状态一直是骑行中 → 保持 active,不能假装成功
|
||||
def fake_auth(user_id, method, path, **kwargs):
|
||||
if path == "/record/return":
|
||||
return {"rtn_code": 500, "message": "return rejected"}
|
||||
if path == "/user/info":
|
||||
return active
|
||||
return {"rtn_code": 0, "data": {}}
|
||||
|
||||
with patch.object(rental_routes, "get_db", self._get_db), \
|
||||
patch.object(rental_routes, "get_current_user", return_value={
|
||||
"id": 7, "email": "rider@example.test"
|
||||
}), \
|
||||
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||
patch.object(rental_routes, "request_with_user_auth", side_effect=responses), \
|
||||
patch.object(rental_routes, "request_with_user_auth", side_effect=fake_auth), \
|
||||
patch.object(rental_routes.time, "sleep"):
|
||||
response = client.post("/api/order/return", json={
|
||||
"order_id": "9001", "code": "50001",
|
||||
"latitude": 36.67, "longitude": 116.98,
|
||||
})
|
||||
self.assertEqual(500, response.get_json()["rtn_code"])
|
||||
self.assertNotEqual(0, response.get_json()["rtn_code"])
|
||||
self.assertEqual(0, self._expired(101))
|
||||
|
||||
def test_silent_zero_minute_event_runs_auto_return_without_email(self):
|
||||
@@ -516,6 +535,376 @@ class OrderSyncTests(unittest.TestCase):
|
||||
auto_return.assert_called_once_with(101, 7)
|
||||
notify.assert_not_called()
|
||||
|
||||
def test_auto_return_failure_keeps_notified_zero_and_schedules_retry(self):
|
||||
"""上游还车失败时不能把 notified_0 置位,否则这一单再也不会重试。"""
|
||||
class ImmediateTimer:
|
||||
def __init__(self, delay, callback):
|
||||
self.callback = callback
|
||||
def start(self):
|
||||
self.callback()
|
||||
def cancel(self):
|
||||
pass
|
||||
|
||||
with patch.object(timer, "get_db", self._get_db), \
|
||||
patch.object(timer.threading, "Timer", ImmediateTimer), \
|
||||
patch.object(timer, "auto_return_bike", return_value={
|
||||
"attempted": True, "success": False, "message": "upstream boom"
|
||||
}), \
|
||||
patch.object(timer, "_schedule_reminder") as reschedule, \
|
||||
patch.object(timer, "send_rental_notification"):
|
||||
timer._schedule_reminder(
|
||||
101, 0, "0", "rider@example.test", "50001", 7,
|
||||
send_notification=False, auto_return_enabled=True,
|
||||
auto_return_configured=True,
|
||||
)
|
||||
|
||||
conn = self._get_db()
|
||||
row = conn.execute("SELECT notified_0 FROM rentals WHERE id = 101").fetchone()
|
||||
conn.close()
|
||||
self.assertEqual(0, row["notified_0"]) # 保持未置位
|
||||
reschedule.assert_called_once()
|
||||
self.assertEqual("0", reschedule.call_args.args[2]) # 安排了短周期重试
|
||||
self.assertEqual(0, self._expired(101))
|
||||
|
||||
def test_restart_recovers_rental_that_expired_while_process_was_down(self):
|
||||
"""重启时 end_time 已过:必须补一次自动还车,而不是当它不存在。"""
|
||||
class ImmediateThread:
|
||||
def __init__(self, target=None, args=(), **kwargs):
|
||||
self.target, self.args = target, args
|
||||
def start(self):
|
||||
if self.target:
|
||||
self.target(*self.args)
|
||||
|
||||
conn = self._get_db()
|
||||
conn.execute("""
|
||||
INSERT INTO rentals
|
||||
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||
VALUES (104, '9004', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||
'2026-01-01 09:19:00', '50004', 'rider@example.test')
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
with patch.object(timer, "get_db", self._get_db), \
|
||||
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||
patch.object(timer, "_time") as fake_time, \
|
||||
patch.object(timer, "auto_return_bike", return_value={
|
||||
"success": True, "message": "ok"
|
||||
}) as auto_return, \
|
||||
patch.object(timer, "start_rental_timer"):
|
||||
fake_time.sleep = lambda *_: None
|
||||
timer.restore_active_timers()
|
||||
|
||||
auto_return.assert_called_once()
|
||||
self.assertEqual(104, auto_return.call_args.args[0])
|
||||
|
||||
def test_checker_recovers_rental_past_end_time_instead_of_returning(self):
|
||||
"""巡检看到 expired=0 但 end_time 已过:补还车,不能直接 return。"""
|
||||
class ImmediateThread:
|
||||
def __init__(self, target=None, args=(), **kwargs):
|
||||
self.target, self.args = target, args
|
||||
def start(self):
|
||||
if self.target:
|
||||
self.target(*self.args)
|
||||
|
||||
conn = self._get_db()
|
||||
conn.execute("""
|
||||
INSERT INTO rentals
|
||||
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||
VALUES (105, '9005', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||
'2026-01-01 09:19:00', '50005', 'rider@example.test')
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
active = {"rtn_code": 0, "data": {"nonDealOrder": {
|
||||
"order_id": "9005", "status": 2, "code": "50005"
|
||||
}}}
|
||||
with patch.object(timer, "get_db", self._get_db), \
|
||||
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||
patch.object(timer, "threading", wraps=timer.threading), \
|
||||
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||
patch.object(timer, "sweep_overdue_rentals", return_value=0), \
|
||||
patch.object(timer, "request_with_user_auth", return_value=active), \
|
||||
patch.object(timer, "auto_return_bike", return_value={
|
||||
"success": True, "message": "ok"
|
||||
}) as auto_return:
|
||||
result = timer._check_user_order(7)
|
||||
|
||||
self.assertTrue(result.get("recovered"))
|
||||
auto_return.assert_called_once()
|
||||
self.assertEqual(105, auto_return.call_args.args[0])
|
||||
|
||||
def test_restart_skips_reminder_rows_but_recovers_subscribe_rows(self):
|
||||
"""reminder 没有上游订单号,补还车只会白打三次上游;subscribe 必须补。"""
|
||||
class ImmediateThread:
|
||||
def __init__(self, target=None, args=(), **kwargs):
|
||||
self.target, self.args = target, args
|
||||
def start(self):
|
||||
if self.target:
|
||||
self.target(*self.args)
|
||||
|
||||
conn = self._get_db()
|
||||
conn.execute("""
|
||||
INSERT INTO rentals
|
||||
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||
VALUES (106, NULL, 7, 'reminder', 0, '2026-01-01 09:00:00',
|
||||
'2026-01-01 09:19:00', '50006', 'rider@example.test')
|
||||
""")
|
||||
conn.execute("""
|
||||
INSERT INTO rentals
|
||||
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||
VALUES (107, '9007', 7, 'subscribe', 0, '2026-01-01 09:00:00',
|
||||
'2026-01-01 09:19:00', '50007', 'rider@example.test')
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
with patch.object(timer, "get_db", self._get_db), \
|
||||
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||
patch.object(timer, "_time") as fake_time, \
|
||||
patch.object(timer, "auto_return_bike", return_value={
|
||||
"success": True, "message": "ok"
|
||||
}) as auto_return, \
|
||||
patch.object(timer, "start_rental_timer"):
|
||||
fake_time.sleep = lambda *_: None
|
||||
timer.restore_active_timers()
|
||||
|
||||
recovered_ids = [c.args[0] for c in auto_return.call_args_list]
|
||||
self.assertIn(107, recovered_ids) # subscribe 要补
|
||||
self.assertNotIn(106, recovered_ids) # reminder 不补
|
||||
|
||||
def test_return_succeeds_even_when_local_write_fails(self):
|
||||
"""上游还车成功、本地写库抛异常:不能报「还车失败」(否则用户会再点一次撞 204010)。"""
|
||||
app = Flask(__name__)
|
||||
app.secret_key = "test"
|
||||
app.register_blueprint(rental_routes.bp)
|
||||
client = app.test_client()
|
||||
|
||||
def fake_auth(user_id, method, path, **kwargs):
|
||||
if path == "/record/return":
|
||||
return {"rtn_code": 0, "message": "ok"}
|
||||
return {"rtn_code": 0, "data": {}}
|
||||
|
||||
with patch.object(rental_routes, "get_db", self._get_db), \
|
||||
patch.object(rental_routes, "get_current_user", return_value={
|
||||
"id": 7, "email": "rider@example.test"}), \
|
||||
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||
patch.object(rental_routes, "request_with_user_auth", side_effect=fake_auth), \
|
||||
patch.object(rental_routes, "_record_rental_end",
|
||||
side_effect=RuntimeError("database is locked")), \
|
||||
patch.object(rental_routes, "_record_raw_coords",
|
||||
side_effect=RuntimeError("database is locked")), \
|
||||
patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \
|
||||
patch.object(rental_routes, "_cancel_rental_timers"):
|
||||
resp = client.post("/api/order/return", json={
|
||||
"order_id": "9001", "code": "50001",
|
||||
"latitude": 36.67, "longitude": 116.98,
|
||||
})
|
||||
|
||||
body = resp.get_json()
|
||||
self.assertEqual(0, body["rtn_code"])
|
||||
self.assertFalse(body["local_synced"])
|
||||
self.assertIn("本地记录稍后同步", body["message"])
|
||||
|
||||
def test_retry_success_sends_final_notice(self):
|
||||
"""重试后终于还上,要再发一封收尾,别让用户去点旧邮件里的还车按钮。"""
|
||||
class ImmediateTimer:
|
||||
def __init__(self, delay, callback):
|
||||
self.callback = callback
|
||||
def start(self):
|
||||
self.callback()
|
||||
def cancel(self):
|
||||
pass
|
||||
|
||||
timer._auto_return_retries[101] = 2
|
||||
try:
|
||||
with patch.object(timer, "get_db", self._get_db), \
|
||||
patch.object(timer.threading, "Timer", ImmediateTimer), \
|
||||
patch.object(timer, "auto_return_bike", return_value={
|
||||
"attempted": True, "success": True, "message": "ok"
|
||||
}), \
|
||||
patch.object(timer, "_notify_auto_return_recovered") as recovered, \
|
||||
patch.object(timer, "send_rental_notification"):
|
||||
timer._schedule_reminder(
|
||||
101, 0, "0", "rider@example.test", "50001", 7,
|
||||
send_notification=False, auto_return_enabled=True,
|
||||
auto_return_configured=True,
|
||||
)
|
||||
finally:
|
||||
timer._auto_return_retries.pop(101, None)
|
||||
|
||||
recovered.assert_called_once_with(101)
|
||||
|
||||
def test_retry_exhausted_alerts_admin_instead_of_silent_print(self):
|
||||
timer._auto_return_retries[101] = timer.AUTO_RETURN_MAX_RETRIES
|
||||
try:
|
||||
with patch.object(timer, "_alert_auto_return_exhausted") as alert:
|
||||
timer._schedule_auto_return_retry(101, "rider@example.test", "50001",
|
||||
7, "upstream boom")
|
||||
finally:
|
||||
timer._auto_return_retries.pop(101, None)
|
||||
alert.assert_called_once()
|
||||
|
||||
def test_checker_throttles_repeated_recovery_attempts(self):
|
||||
"""彻底还不上时,巡检不能每分钟重打上游(5 分钟一次)。"""
|
||||
class ImmediateThread:
|
||||
def __init__(self, target=None, args=(), **kwargs):
|
||||
self.target, self.args = target, args
|
||||
def start(self):
|
||||
if self.target:
|
||||
self.target(*self.args)
|
||||
|
||||
conn = self._get_db()
|
||||
conn.execute("""
|
||||
INSERT INTO rentals
|
||||
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||
VALUES (108, '9008', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||
'2026-01-01 09:19:00', '50008', 'rider@example.test')
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
active = {"rtn_code": 0, "data": {"nonDealOrder": {
|
||||
"order_id": "9008", "status": 2, "code": "50008"
|
||||
}}}
|
||||
timer._recover_last_at.clear()
|
||||
try:
|
||||
with patch.object(timer, "get_db", self._get_db), \
|
||||
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||
patch.object(timer, "sweep_overdue_rentals", return_value=0), \
|
||||
patch.object(timer, "request_with_user_auth", return_value=active), \
|
||||
patch.object(timer, "auto_return_bike", return_value={
|
||||
"success": False, "message": "boom"
|
||||
}) as auto_return:
|
||||
first = timer._check_user_order(7)
|
||||
second = timer._check_user_order(7)
|
||||
finally:
|
||||
timer._recover_last_at.clear()
|
||||
|
||||
self.assertTrue(first.get("recovered"))
|
||||
self.assertTrue(second.get("recovering")) # 第二次被节流
|
||||
self.assertEqual(1, auto_return.call_count) # 只补了一次
|
||||
|
||||
def test_recovery_skips_return_when_user_already_returned_in_miniprogram(self):
|
||||
"""用户在小程序里还了车:上游查不到这单 → 只做本地收尾,不再打 /record/return。"""
|
||||
conn = self._get_db()
|
||||
conn.execute("""
|
||||
INSERT INTO rentals
|
||||
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||
VALUES (120, '9020', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||
'2026-01-01 09:19:00', '50020', 'rider@example.test')
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
with patch.object(timer, "get_db", self._get_db), \
|
||||
patch.object(timer, "_upstream_ride_active", return_value=False), \
|
||||
patch.object(timer, "auto_return_bike") as auto_return:
|
||||
result = timer._run_recovery(120, 7, "9020")
|
||||
|
||||
auto_return.assert_not_called() # 关键:不再制造 204010
|
||||
self.assertTrue(result.get("skipped"))
|
||||
conn = self._get_db()
|
||||
try:
|
||||
row = conn.execute("SELECT expired FROM rentals WHERE id = 120").fetchone()
|
||||
self.assertEqual(1, row["expired"])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def test_recovery_still_returns_when_upstream_order_is_active(self):
|
||||
conn = self._get_db()
|
||||
conn.execute("""
|
||||
INSERT INTO rentals
|
||||
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||
VALUES (121, '9021', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||
'2026-01-01 09:19:00', '50021', 'rider@example.test')
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
with patch.object(timer, "_upstream_ride_active", return_value=True), \
|
||||
patch.object(timer, "auto_return_bike", return_value={
|
||||
"success": True, "message": "ok"
|
||||
}) as auto_return:
|
||||
result = timer._run_recovery(121, 7, "9021")
|
||||
|
||||
auto_return.assert_called_once_with(121, 7)
|
||||
self.assertTrue(result.get("success"))
|
||||
|
||||
def test_sweep_queues_overdue_rentals_and_is_throttled(self):
|
||||
"""兜底扫描:超期未还的单要排队补还车,且 10 分钟内不重复扫。"""
|
||||
class ImmediateThread:
|
||||
def __init__(self, target=None, args=(), **kwargs):
|
||||
self.target, self.args = target, args
|
||||
def start(self):
|
||||
if self.target:
|
||||
self.target(*self.args)
|
||||
|
||||
conn = self._get_db()
|
||||
conn.execute("""
|
||||
INSERT INTO rentals
|
||||
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||
VALUES (111, '9011', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||
'2026-01-01 09:19:00', '50011', 'rider@example.test')
|
||||
""")
|
||||
conn.execute("""
|
||||
INSERT INTO rentals
|
||||
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||
VALUES (112, NULL, 7, 'reminder', 0, '2026-01-01 09:00:00',
|
||||
'2026-01-01 09:19:00', '50012', 'rider@example.test')
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
timer._recover_last_at.clear()
|
||||
timer._sweep_last_at[0] = 0
|
||||
try:
|
||||
with patch.object(timer, "get_db", self._get_db), \
|
||||
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||
patch.object(timer, "auto_return_bike", return_value={
|
||||
"success": True, "message": "ok"
|
||||
}) as auto_return:
|
||||
first = timer.sweep_overdue_rentals(force=True)
|
||||
second = timer.sweep_overdue_rentals() # 10 分钟内不再扫
|
||||
finally:
|
||||
timer._recover_last_at.clear()
|
||||
timer._sweep_last_at[0] = 0
|
||||
|
||||
self.assertEqual(1, first) # 只有 unlock 那单
|
||||
self.assertEqual(0, second) # 被节流
|
||||
recovered_ids = [c.args[0] for c in auto_return.call_args_list]
|
||||
self.assertIn(111, recovered_ids)
|
||||
self.assertNotIn(112, recovered_ids) # reminder 不补
|
||||
|
||||
conn = self._get_db()
|
||||
try:
|
||||
row = conn.execute("SELECT expired FROM rentals WHERE id = 112").fetchone()
|
||||
self.assertEqual(1, row["expired"]) # 本地提醒单就地关闭
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def test_recovery_success_clears_throttle_record(self):
|
||||
"""补还车成功后要清掉节流记录,别在进程里留失败痕迹。"""
|
||||
timer._recover_last_at[109] = timer._time.time()
|
||||
try:
|
||||
with patch.object(timer, "auto_return_bike", return_value={
|
||||
"success": True, "message": "ok"
|
||||
}):
|
||||
timer._run_recovery(109, 7)
|
||||
self.assertNotIn(109, timer._recover_last_at)
|
||||
|
||||
timer._recover_last_at[110] = timer._time.time()
|
||||
with patch.object(timer, "auto_return_bike", return_value={
|
||||
"success": False, "message": "boom"
|
||||
}):
|
||||
timer._run_recovery(110, 7)
|
||||
self.assertIn(110, timer._recover_last_at) # 失败保留,供节流判断
|
||||
finally:
|
||||
timer._recover_last_at.pop(109, None)
|
||||
timer._recover_last_at.pop(110, None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -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()
|
||||
@@ -1,69 +0,0 @@
|
||||
"""Preview/live routing and authenticated editor/pagination contracts in a subprocess."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def test_preview_and_live_feature_contract():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
env = {**os.environ, "XBNIU_PREVIEW": "1", "XBNIU_DB_PATH": str(Path(directory) / "preview.db"), "PYTHONDONTWRITEBYTECODE": "1"}
|
||||
script = r'''
|
||||
from unittest.mock import patch
|
||||
import db
|
||||
db.init_db()
|
||||
import app
|
||||
from preview_data import seed_preview
|
||||
seed_preview()
|
||||
c=app.app.test_client()
|
||||
assert c.get('/healthz').json == {'status':'ok','mode':'preview'}
|
||||
login=c.post('/api/auth/login',json={'email':'demo@preview.local','password':'preview123'}).json
|
||||
h={'Authorization':'Bearer '+login['data']['token']}
|
||||
with patch('wechat.request_with_user_auth',side_effect=AssertionError('Demo called upstream')):
|
||||
bikes=c.get('/api/map?type=3',headers=h).json['data']['bicycleStation']
|
||||
assert len(bikes)==28
|
||||
assert c.post('/api/order/unlock',headers=h,json={'code':'51201'}).json['rtn_code']==0
|
||||
assert c.get('/api/order/status',headers=h).json['has_order']
|
||||
assert c.post('/api/order/return',headers=h,json={}).json['rtn_code']==0
|
||||
assert not c.get('/api/order/status',headers=h).json['has_order']
|
||||
assert c.post('/api/auth/save_token',headers=h,json={'token_id':'real'}).status_code==403
|
||||
page1=c.get('/api/user/orders?limit=20',headers=h).json
|
||||
page2=c.get('/api/user/orders?limit=20&offset=20',headers=h).json
|
||||
assert page1['total']==68 and page1['has_more'] and len(page1['data'])==20
|
||||
assert not ({x['id'] for x in page1['data']} & {x['id'] for x in page2['data']})
|
||||
assert all(x['shared'] for x in c.get('/api/user/orders?source=shared',headers=h).json['data'])
|
||||
assert c.get('/api/user/orders?from=2026-11-05&to=2026-11-01',headers=h).status_code==400
|
||||
rules=c.get('/api/subscribe/rules',headers=h).json['data'];rule=rules[0]
|
||||
parking=c.get('/api/campus/locations',headers=h).json['data']
|
||||
location=next(p for p in parking if p['kind']=='parking' and p['id']!=rule['location_id'])
|
||||
updated=c.put('/api/subscribe/rules/'+str(rule['id']),headers=h,json={'location_id':location['id'],'time':'12:34','weekday':3,'min_electric':40,'auto_unlock':False,'notify_enabled':True})
|
||||
assert updated.json['rtn_code']==0,updated.json
|
||||
saved=c.get('/api/subscribe/rules',headers=h).json['data'][0]
|
||||
assert saved['minute_of_day']==754 and saved['location_id']==location['id'] and saved['min_electric']==40
|
||||
assert saved['last_run_status']=='success'
|
||||
assert c.put('/api/subscribe/rules/'+str(rule['id']),headers=h,json={'min_electric':90,'max_electric':20}).status_code==400
|
||||
session=c.post('/api/preview/session').json
|
||||
live={'Authorization':'Bearer '+session['data']['token']}
|
||||
assert not c.get('/api/user/orders',headers=live).json['data']
|
||||
assert not c.get('/api/subscribe/rules',headers=live).json['data']
|
||||
with patch('wechat.request_with_user_auth',return_value={'rtn_code':0,'data':{'bicycleStation':[]}}) as upstream:
|
||||
assert c.get('/api/map?type=3',headers=live).json['rtn_code']==0
|
||||
assert c.get('/api/map?type=3',headers=live).json['rtn_code']==0
|
||||
assert upstream.call_count==1, 'live map cache should coalesce requests'
|
||||
assert upstream.call_args.args[0] != 1, 'live requests must use private test account credentials'
|
||||
assert c.put('/api/subscribe/rules/'+str(rule['id']),headers=live,json={'enabled':False}).json['rtn_code']==404
|
||||
with patch('wechat.request_with_user_auth',return_value={'rtn_code':0,'data':{'order_id':'REAL-TEST'}}) as upstream:
|
||||
assert c.post('/api/bicycle',headers=live,json={'code':'51201'}).json['rtn_code']==0
|
||||
assert upstream.call_count==1
|
||||
with patch('email_utils.smtplib.SMTP',side_effect=AssertionError('Demo SMTP')):
|
||||
from email_utils import send_email
|
||||
assert send_email('demo@preview.local','test','body') is True
|
||||
from bike_data import classify,battery
|
||||
assert classify(1,0,10)=='low' and classify(1,1,10)=='used' and classify(4,0,10)=='locked'
|
||||
assert battery(None) is None and battery(0)==0
|
||||
print('PASS: demo isolation, real test account routing, pagination, subscription ownership and full edits')
|
||||
'''
|
||||
result = subprocess.run([sys.executable, "-X", "utf8", "-c", script], cwd=root, env=env, capture_output=True, text=True, timeout=60)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
@@ -4,8 +4,10 @@ import unittest
|
||||
|
||||
class RingAllFrontendAuthTests(unittest.TestCase):
|
||||
def test_ring_all_request_sends_session_token(self):
|
||||
source = (Path(__file__).resolve().parents[1] / "static/js/map-account.js").read_text(encoding="utf-8")
|
||||
request_block = source.split('apiFetch("/api/ring_all"', 1)[1].split(");", 1)[0]
|
||||
source = (
|
||||
Path(__file__).resolve().parents[1] / "static" / "js" / "map.js"
|
||||
).read_text(encoding="utf-8")
|
||||
request_block = source.split('fetch("/api/ring_all"', 1)[1].split(");", 1)[0]
|
||||
|
||||
self.assertIn('"Authorization": `Bearer ${authToken}`', request_block)
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""订阅调度与自动开锁的关键回归。
|
||||
|
||||
覆盖两件事:
|
||||
1) 整分钟漏触发后当天要能补(`minute_of_day <= 当前分钟`);
|
||||
2) 开锁失败时必须撤销刚下的半成品订单,避免重试叠加。
|
||||
"""
|
||||
import datetime as dt
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import subscribe
|
||||
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE subscribe_rules (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
location_id INTEGER,
|
||||
weekday INTEGER DEFAULT 0,
|
||||
minute_of_day INTEGER NOT NULL,
|
||||
enabled INTEGER DEFAULT 1,
|
||||
notify_enabled INTEGER DEFAULT 1,
|
||||
auto_unlock INTEGER DEFAULT 0,
|
||||
last_fired_on TEXT DEFAULT '',
|
||||
kinds TEXT DEFAULT 'small,big,red',
|
||||
min_electric INTEGER DEFAULT 0,
|
||||
max_electric INTEGER DEFAULT 100,
|
||||
sort_by TEXT DEFAULT 'electric_desc',
|
||||
retry_times INTEGER DEFAULT 3
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
class ImmediateThread:
|
||||
def __init__(self, target=None, args=(), kwargs=None, **rest):
|
||||
self.target = target
|
||||
self.args = args
|
||||
self.kwargs = kwargs or {}
|
||||
|
||||
def start(self):
|
||||
if self.target:
|
||||
self.target(*self.args, **self.kwargs)
|
||||
|
||||
|
||||
class SubscribeFlowTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.db_path = Path(self.tmp.name) / "sub.db"
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
conn.executescript(SCHEMA)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def _get_db(self):
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
def test_missed_minute_is_caught_up_later_same_day(self):
|
||||
"""7:50 的规则,8:10 才跑到,仍然要发,且当天只发一次。"""
|
||||
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
||||
conn = self._get_db()
|
||||
past_minute = max(0, now.hour * 60 + now.minute - 5)
|
||||
conn.execute("""
|
||||
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
||||
enabled, notify_enabled, last_fired_on)
|
||||
VALUES (7, 1, 0, ?, 1, 1, '')
|
||||
""", (past_minute,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
fired = []
|
||||
with patch.object(subscribe, "get_db", self._get_db), \
|
||||
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
||||
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
||||
subscribe._tick()
|
||||
|
||||
self.assertEqual(1, len(fired), "过点的规则应该补发一次")
|
||||
|
||||
# 同一天再扫一遍不应重复触发
|
||||
with patch.object(subscribe, "get_db", self._get_db), \
|
||||
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
||||
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
||||
subscribe._tick()
|
||||
self.assertEqual(1, len(fired), "当天已经发过就不该再发")
|
||||
|
||||
def test_future_minute_is_not_fired_early(self):
|
||||
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
||||
conn = self._get_db()
|
||||
future_minute = min(23 * 60 + 59, now.hour * 60 + now.minute + 30)
|
||||
conn.execute("""
|
||||
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
||||
enabled, notify_enabled, last_fired_on)
|
||||
VALUES (7, 1, 0, ?, 1, 1, '')
|
||||
""", (future_minute,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
fired = []
|
||||
with patch.object(subscribe, "get_db", self._get_db), \
|
||||
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
||||
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
||||
subscribe._tick()
|
||||
self.assertEqual([], fired)
|
||||
|
||||
def test_failed_unlock_discards_the_pending_order(self):
|
||||
"""下单成功但开锁失败:必须撤销那张单,否则重试会再叠一张。"""
|
||||
responses = {
|
||||
"/project/bicycle": {"rtn_code": 0, "data": {"status": 0, "code": "50001",
|
||||
"latitude": 36.53, "longitude": 116.78}},
|
||||
"/record/order": {"rtn_code": 0, "data": {"order_id": "777"}},
|
||||
"/record/qrOrder": {"rtn_code": 500, "message": "open failed"},
|
||||
"/record/return": {"rtn_code": 0, "message": "closed"},
|
||||
}
|
||||
|
||||
def fake_auth(user_id, method, path, **kwargs):
|
||||
return responses.get(path, {"rtn_code": 0, "data": {}})
|
||||
|
||||
with patch.object(subscribe, "_live_coord", return_value=(36.53, 116.78)), \
|
||||
patch.object(subscribe, "AUTO_UNLOCK_ENABLED", True), \
|
||||
patch("wechat.request_with_user_auth", side_effect=fake_auth), \
|
||||
patch.object(subscribe, "_discard_pending_order", return_value=True) as discard:
|
||||
result = subscribe._try_auto_unlock(7, "50001")
|
||||
|
||||
self.assertFalse(result["success"])
|
||||
discard.assert_called_once()
|
||||
self.assertEqual("777", str(discard.call_args.args[1]))
|
||||
self.assertIn("已撤销本次下单", result["message"])
|
||||
|
||||
def test_realtime_points_use_electric_quantity_and_only_electric_bikes(self):
|
||||
"""上游字段是 electric_quantity;写成 electric 会让电量筛选全部落空。
|
||||
并且只取 type=3(电动车),别把共享单车混进候选。"""
|
||||
payload = {"rtn_code": 0, "data": {"bicycleStation": [
|
||||
{"code": "51287", "latitude": 36.53, "longitude": 116.78,
|
||||
"electric_quantity": 66, "state": 1, "status": 0},
|
||||
]}}
|
||||
calls = []
|
||||
|
||||
def fake_api(method, path, params=None, data=None):
|
||||
calls.append(params)
|
||||
return payload
|
||||
|
||||
with patch("wechat.request_api", side_effect=fake_api):
|
||||
rows = subscribe.refresh_bike_points(7)
|
||||
|
||||
self.assertEqual(1, len(rows))
|
||||
self.assertEqual(66, rows[0]["electric"])
|
||||
self.assertEqual("51287", rows[0]["bike_code"])
|
||||
self.assertEqual("3", rows[0]["bike_type"])
|
||||
self.assertEqual(["3"], [c["type"] for c in calls])
|
||||
|
||||
def test_missed_minute_beyond_window_is_skipped_without_email(self):
|
||||
"""超过补发窗口(默认 5 分钟)的规则:只记今天已处理,不发信。"""
|
||||
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
||||
conn = self._get_db()
|
||||
old_minute = max(0, now.hour * 60 + now.minute - 30)
|
||||
conn.execute("""
|
||||
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
||||
enabled, notify_enabled, last_fired_on)
|
||||
VALUES (7, 1, 0, ?, 1, 1, '')
|
||||
""", (old_minute,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
fired = []
|
||||
with patch.object(subscribe, "get_db", self._get_db), \
|
||||
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
||||
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
||||
subscribe._tick()
|
||||
|
||||
self.assertEqual([], fired, "过窗口太久的规则不该补发")
|
||||
conn = self._get_db()
|
||||
row = conn.execute("SELECT last_fired_on FROM subscribe_rules").fetchone()
|
||||
conn.close()
|
||||
self.assertEqual(now.strftime("%Y-%m-%d"), row["last_fired_on"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""步行路线:百度轻量级路线规划 + 缓存 + 估算兜底。"""
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import walk_route
|
||||
|
||||
ORIGIN = (36.529440, 116.783740)
|
||||
DEST = (36.534240, 116.787190)
|
||||
|
||||
|
||||
class EstimateTests(unittest.TestCase):
|
||||
def test_straight_line_is_expanded_by_detour_factor(self):
|
||||
got = walk_route.estimate(*ORIGIN, *DEST)
|
||||
self.assertEqual("estimate", got["source"])
|
||||
# 直线约 615 米 -> 乘 1.3 绕行系数
|
||||
self.assertGreater(got["straight"], 550)
|
||||
self.assertLess(got["straight"], 700)
|
||||
self.assertAlmostEqual(got["distance"], got["straight"] * 1.3, delta=2)
|
||||
# 75 米/分钟
|
||||
self.assertAlmostEqual(got["duration"], got["distance"] / 75 * 60, delta=2)
|
||||
|
||||
def test_bad_input_never_raises(self):
|
||||
for args in ((None, None, None, None), ("a", "b", "c", "d")):
|
||||
self.assertEqual("none", walk_route.estimate(*args)["source"])
|
||||
|
||||
|
||||
class QueryAndSnTests(unittest.TestCase):
|
||||
PARAMS = {"ak": "X", "origin": "36.5,116.7", "destination": "36.4,116.6",
|
||||
"coord_type": "gcj02"}
|
||||
|
||||
def test_without_sk_no_sn(self):
|
||||
q = walk_route.build_query(self.PARAMS, "")
|
||||
self.assertNotIn("sn=", q)
|
||||
self.assertIn("coord_type=gcj02", q)
|
||||
|
||||
def test_two_sn_modes_differ_and_are_deterministic(self):
|
||||
a1 = walk_route.build_query(self.PARAMS, "SK", "official")
|
||||
a2 = walk_route.build_query(self.PARAMS, "SK", "official")
|
||||
b = walk_route.build_query(self.PARAMS, "SK", "simple")
|
||||
self.assertEqual(a1, a2)
|
||||
self.assertIn("sn=", a1)
|
||||
self.assertIn("sn=", b)
|
||||
self.assertNotEqual(a1.split("sn=")[1], b.split("sn=")[1])
|
||||
|
||||
def test_params_are_key_sorted(self):
|
||||
q = walk_route.build_query(self.PARAMS, "")
|
||||
keys = [part.split("=")[0] for part in q.split("&")]
|
||||
self.assertEqual(sorted(keys), keys)
|
||||
|
||||
|
||||
class GetWalkRouteTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.path = Path(self.tmp.name) / "walk_cache.db"
|
||||
self.patches = [
|
||||
patch.object(walk_route, "CACHE_PATH", self.path),
|
||||
patch.object(walk_route, "_cache_ready", [False]),
|
||||
patch.object(walk_route, "_last_call_at", [0.0]),
|
||||
patch.object(walk_route, "MIN_INTERVAL_SECONDS", 0.0),
|
||||
]
|
||||
for p in self.patches:
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def _ok(self):
|
||||
resp = Mock()
|
||||
resp.raise_for_status = Mock()
|
||||
resp.json = Mock(return_value={"status": 0, "result": {"routes": [
|
||||
{"distance": 820, "duration": 640}]}})
|
||||
return resp
|
||||
|
||||
def test_without_ak_returns_estimate_and_never_calls_bbox(self):
|
||||
with patch.object(walk_route, "get_ak", return_value=""), \
|
||||
patch("walk_route.requests.get") as http:
|
||||
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||
self.assertEqual("estimate", got["source"])
|
||||
http.assert_not_called()
|
||||
|
||||
def test_baidu_success_then_served_from_cache(self):
|
||||
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||
patch.object(walk_route, "get_sk", return_value=""), \
|
||||
patch("walk_route.requests.get", return_value=self._ok()) as http:
|
||||
first = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||
second = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||
self.assertEqual("baidu", first["source"])
|
||||
self.assertEqual(820, first["distance"])
|
||||
self.assertEqual(640, first["duration"])
|
||||
self.assertEqual("cache", second["source"])
|
||||
self.assertEqual(1, http.call_count) # 第二次没再打百度
|
||||
|
||||
def test_coord_type_is_gcj02(self):
|
||||
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||
patch.object(walk_route, "get_sk", return_value=""), \
|
||||
patch("walk_route.requests.get", return_value=self._ok()) as http:
|
||||
walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||
url = http.call_args[0][0]
|
||||
self.assertIn("coord_type=gcj02", url)
|
||||
self.assertIn("directionlite/v1/walking", url)
|
||||
|
||||
def test_sn_failure_retries_the_other_mode(self):
|
||||
bad = Mock()
|
||||
bad.raise_for_status = Mock()
|
||||
bad.json = Mock(return_value={"status": 211, "message": "APP SN校验失败"})
|
||||
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||
patch.object(walk_route, "get_sk", return_value="SK"), \
|
||||
patch.object(walk_route, "_SN_MODE", [None]), \
|
||||
patch("walk_route.requests.get", side_effect=[bad, self._ok()]) as http:
|
||||
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||
self.assertEqual("baidu", got["source"])
|
||||
self.assertEqual(2, http.call_count) # 官方算法失败后换了另一种
|
||||
|
||||
def test_app_disabled_falls_back_without_retry(self):
|
||||
bad = Mock()
|
||||
bad.raise_for_status = Mock()
|
||||
bad.json = Mock(return_value={"status": 240, "message": "APP 服务被禁用"})
|
||||
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||
patch.object(walk_route, "get_sk", return_value="SK"), \
|
||||
patch("walk_route.requests.get", return_value=bad) as http:
|
||||
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||
self.assertEqual("estimate", got["source"])
|
||||
self.assertEqual(1, http.call_count) # 240 不是 SN 问题,不重试
|
||||
|
||||
def test_network_error_falls_back(self):
|
||||
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||
patch.object(walk_route, "get_sk", return_value=""), \
|
||||
patch("walk_route.requests.get", side_effect=TimeoutError("boom")):
|
||||
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||
self.assertEqual("estimate", got["source"])
|
||||
self.assertGreater(got["distance"], 0)
|
||||
|
||||
|
||||
class CredentialStorageTests(unittest.TestCase):
|
||||
"""管理端回显:SK 不能明文吐给前端。"""
|
||||
|
||||
def test_masked_hides_sk(self):
|
||||
with patch.object(walk_route, "get_ak", return_value="AK123"), \
|
||||
patch.object(walk_route, "get_sk", return_value="SK-abcdef1234"):
|
||||
got = walk_route.masked_credentials()
|
||||
self.assertEqual("AK123", got["ak"])
|
||||
self.assertTrue(got["sk_set"])
|
||||
self.assertEqual("1234", got["sk_tail"])
|
||||
self.assertNotIn("SK-abcdef", str(got))
|
||||
|
||||
def test_masked_when_empty(self):
|
||||
with patch.object(walk_route, "get_ak", return_value=""), \
|
||||
patch.object(walk_route, "get_sk", return_value=""):
|
||||
got = walk_route.masked_credentials()
|
||||
self.assertFalse(got["enabled"])
|
||||
self.assertFalse(got["sk_set"])
|
||||
|
||||
|
||||
class DoublePrecisionCacheKeyTests(unittest.TestCase):
|
||||
def test_nearby_points_share_a_cache_key(self):
|
||||
a = walk_route._cache_key(36.529441, 116.783741, 36.534239, 116.787191)
|
||||
b = walk_route._cache_key(36.529444, 116.783744, 36.534241, 116.787194)
|
||||
self.assertEqual(a, b) # 10 米内视作同一对起终点
|
||||
|
||||
def test_far_points_differ(self):
|
||||
a = walk_route._cache_key(36.5294, 116.7837, 36.5342, 116.7872)
|
||||
b = walk_route._cache_key(36.5394, 116.7937, 36.5342, 116.7872)
|
||||
self.assertNotEqual(a, b)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -24,6 +24,10 @@ _checker_lock = threading.Lock()
|
||||
# 10 分钟轮询会让 5/3/2/1/0 分钟提醒继续发送,改为每分钟核对一次。
|
||||
ORDER_CHECK_INTERVAL = 60
|
||||
|
||||
# 自动还车用的停车区缓存:{user_id: (ts, parkeArea)},避免续租链反复拉地图
|
||||
_PARK_AREA_CACHE: dict = {}
|
||||
_PARK_AREA_TTL = 60
|
||||
|
||||
|
||||
def _get_remaining_seconds(rental: dict) -> int:
|
||||
"""计算距离过期的秒数"""
|
||||
@@ -34,6 +38,19 @@ def _get_remaining_seconds(rental: dict) -> int:
|
||||
return max(0, remaining)
|
||||
|
||||
|
||||
def _rental_end_time_passed(rental: dict) -> bool:
|
||||
"""end_time 是否已经过去(重启补还车 / 巡检补还车共用)。"""
|
||||
end_time = (rental or {}).get("end_time")
|
||||
if not end_time:
|
||||
return False
|
||||
try:
|
||||
end = dt.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
return end.replace(tzinfo=tz) <= dt.datetime.now(tz)
|
||||
|
||||
|
||||
def _extract_pay_methods(methods_result: dict):
|
||||
data = methods_result.get("data", {}) if isinstance(methods_result, dict) else {}
|
||||
if not isinstance(data, (list, dict)):
|
||||
@@ -370,8 +387,58 @@ def _renewal_lock(rental_id: int):
|
||||
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):
|
||||
"""自动还车(含重试:最多3次),返回明确的成败结果。"""
|
||||
"""自动还车(含重试:最多3次),返回明确的成败结果。
|
||||
|
||||
坐标链路(与手动还车同一套停车区规则):
|
||||
1. 取车辆坐标(`/project/bicycle`,上游 = GCJ02,不要再转);
|
||||
2. **发还车前**先用本地 parkeArea 多边形判定一次,不在停车区就先吸附到
|
||||
最近的合法点 —— 原来直接发原始坐标,parkNoShow 时三次重试注定全失败;
|
||||
3. 万一对齐后仍失败,第 2 次重试前再吸附一次(应对上游边界与本地不一致)。
|
||||
"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
||||
@@ -393,8 +460,18 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
||||
# 上游要求真实订单号;老记录可能只有本地自增 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
|
||||
last_error = None
|
||||
snap_attempted = aligned # 已经对齐过的话,重试前不必再对齐一次
|
||||
for attempt in range(1, 4):
|
||||
try:
|
||||
return_result = request_with_user_auth(
|
||||
@@ -411,6 +488,16 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
||||
except Exception as e:
|
||||
last_error = str(e)
|
||||
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:
|
||||
_time.sleep(5)
|
||||
|
||||
@@ -477,6 +564,265 @@ def _cancel_rental_timers(rental_id: int):
|
||||
del _active_timers[rental_id]
|
||||
|
||||
|
||||
# 只有这些来源才代表「真的有上游骑行订单」,才能走自动还车。
|
||||
# reminder 是前端自己开的计时提醒,没有上游订单;把本地自增 id 当订单号发出去
|
||||
# 必然 204010,白打三次上游还要 sleep 15 秒。
|
||||
AUTO_RETURN_SOURCES = ("unlock", "sync", "shared", "subscribe")
|
||||
|
||||
|
||||
# 巡检补还车的节流:彻底失败的单不能每分钟重打上游
|
||||
_recover_last_at: dict = {}
|
||||
RECOVER_INTERVAL_SECONDS = 300 # 5 分钟
|
||||
|
||||
|
||||
def _recover_throttled(rental_id: int) -> bool:
|
||||
"""5 分钟内已经补过就不再补,返回 True 表示这次要跳过。"""
|
||||
now = _time.time()
|
||||
last = _recover_last_at.get(rental_id, 0)
|
||||
if now - last < RECOVER_INTERVAL_SECONDS:
|
||||
return True
|
||||
_recover_last_at[rental_id] = now
|
||||
return False
|
||||
|
||||
|
||||
def _upstream_ride_active(user_id: int, order_id):
|
||||
"""上游这张单还在骑吗?True=在骑 / False=已结束 / None=查不到(别下结论)。
|
||||
|
||||
用户很可能直接在小程序里点了还车 —— 那种情况下本地还挂着 expired=0,
|
||||
但我们**不能**再发一次 /record/return(上游会报订单不存在,白白制造错误)。
|
||||
所以补还车前先看上游状态,上游说结束了就只做本地收尾。
|
||||
"""
|
||||
if not user_id or not order_id:
|
||||
return None
|
||||
try:
|
||||
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||||
except Exception as exc:
|
||||
print(f"[自动还车] 查询上游订单状态失败: {exc}")
|
||||
return None
|
||||
if not isinstance(info, dict) or info.get("rtn_code") != 0:
|
||||
return None
|
||||
non_deal = (info.get("data") or {}).get("nonDealOrder") or {}
|
||||
if not non_deal or not non_deal.get("order_id"):
|
||||
return False # 上游没有未完成订单 → 已经结束了
|
||||
if str(non_deal.get("order_id")) != str(order_id):
|
||||
return False # 上游挂的是另一张单 → 这张已经结束
|
||||
return str(non_deal.get("status")) == "2" # 2=骑行中
|
||||
|
||||
|
||||
def _run_recovery(rental_id: int, user_id: int, order_id=None):
|
||||
"""巡检/重启的补还车入口:成功后清掉节流记录,别让进程里留失败痕迹。
|
||||
|
||||
先问上游状态:上游说这单已结束(用户在小程序里还了),就只做本地收尾,
|
||||
不再打 /record/return。
|
||||
"""
|
||||
active = _upstream_ride_active(user_id, order_id) if order_id else None
|
||||
if active is False:
|
||||
_close_rental_locally(rental_id, "上游订单已结束(用户已在小程序还车)")
|
||||
_recover_last_at.pop(rental_id, None)
|
||||
return {"success": True, "skipped": True,
|
||||
"message": "上游订单已结束,仅做本地收尾"}
|
||||
try:
|
||||
result = auto_return_bike(rental_id, user_id) or {}
|
||||
if result.get("success"):
|
||||
_recover_last_at.pop(rental_id, None)
|
||||
return result
|
||||
except Exception as exc:
|
||||
print(f"[自动还车] 补还车异常 rental_id={rental_id}: {exc}")
|
||||
return {"success": False, "message": str(exc)}
|
||||
|
||||
|
||||
# 全局兜底扫描的节流(进程内一次/10 分钟,避免每个用户的巡检都全表扫)
|
||||
_sweep_last_at = [0.0]
|
||||
SWEEP_INTERVAL_SECONDS = 600
|
||||
|
||||
|
||||
def sweep_overdue_rentals(force: bool = False) -> int:
|
||||
"""兜底:捞「expired=0 且 end_time 已过」的单补还车,返回排队数量。
|
||||
|
||||
以前这件事只在 `restore_active_timers()` 里做一次;启动方式一变
|
||||
(WSGI / `flask run` / 直接 import),这些僵尸单就永远挂着,
|
||||
用户页面横幅一直显示「用车中」。现在巡检也会定期顺手扫一遍。
|
||||
"""
|
||||
now = _time.time()
|
||||
if not force and now - _sweep_last_at[0] < SWEEP_INTERVAL_SECONDS:
|
||||
return 0
|
||||
_sweep_last_at[0] = now
|
||||
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||||
conn = get_db()
|
||||
try:
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT * FROM rentals WHERE expired = 0 AND end_time < ?", (now_str,)
|
||||
).fetchall()]
|
||||
except Exception as exc:
|
||||
print(f"[计时系统] 扫描超期订单失败: {exc}")
|
||||
return 0
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
started = 0
|
||||
closed_local = 0
|
||||
for rental in rows:
|
||||
if not _should_auto_return(rental):
|
||||
# reminder 是纯本地计时提醒,没有上游订单:上游还不了,但也不能
|
||||
# 一直挂着 expired=0,否则用户页面横幅永远显示「用车中」。
|
||||
if str(rental.get("source") or "") == "reminder":
|
||||
_close_rental_locally(rental["id"], "本地提醒单到期")
|
||||
closed_local += 1
|
||||
continue
|
||||
if _recover_throttled(rental["id"]):
|
||||
continue
|
||||
threading.Thread(target=_run_recovery,
|
||||
args=(rental["id"], rental.get("user_id"), rental.get("order_id")),
|
||||
daemon=True).start()
|
||||
started += 1
|
||||
if started:
|
||||
print(f"[计时系统] 巡检兜底:{started} 单超期未还,已排队补还车")
|
||||
if closed_local:
|
||||
print(f"[计时系统] 巡检兜底:{closed_local} 条本地提醒单超期,已就地关闭")
|
||||
return started
|
||||
|
||||
|
||||
def _close_rental_locally(rental_id: int, reason: str = ""):
|
||||
"""只做本地收尾:标记结束 + 实际还车时间 + 取消计时器,**不碰上游**。
|
||||
|
||||
适用于两种情况:
|
||||
1. reminder 单(本来就没有上游订单);
|
||||
2. 用户已经在小程序里还车了(上游查不到这张单,再发 /record/return 只会 204010)。
|
||||
"""
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||||
conn = get_db()
|
||||
try:
|
||||
try:
|
||||
conn.execute(
|
||||
"UPDATE rentals SET expired = 1, returned_at = COALESCE(returned_at, ?) "
|
||||
"WHERE id = ? AND expired = 0", (now_str, rental_id))
|
||||
except Exception as exc:
|
||||
if "no such column" not in str(exc).lower():
|
||||
raise
|
||||
# 极简/旧 schema 没有 returned_at:只置 expired 也要把它关掉
|
||||
conn.execute("UPDATE rentals SET expired = 1 WHERE id = ? AND expired = 0",
|
||||
(rental_id,))
|
||||
conn.commit()
|
||||
except Exception as exc:
|
||||
print(f"[计时系统] 本地收尾 rental_id={rental_id} 失败: {exc}")
|
||||
finally:
|
||||
conn.close()
|
||||
try:
|
||||
_cancel_rental_timers(rental_id)
|
||||
except Exception:
|
||||
pass
|
||||
print(f"[计时系统] 本地收尾 rental_id={rental_id}"
|
||||
+ (f":{reason}" if reason else ""))
|
||||
|
||||
|
||||
def _should_auto_return(rental) -> bool:
|
||||
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
|
||||
if not rental:
|
||||
return False
|
||||
if str(rental.get("source") or "") not in AUTO_RETURN_SOURCES:
|
||||
return False
|
||||
return bool(rental.get("order_id"))
|
||||
|
||||
|
||||
def _mark_notified(rental_id: int, reminder_type: str, conn=None, cursor=None):
|
||||
"""把 notified_X 置位(缺列就跳过)。
|
||||
|
||||
调用方已经拿着连接/游标时直接复用,不再为一次 UPDATE 新开连接。
|
||||
"""
|
||||
col = f"notified_{reminder_type}"
|
||||
if cursor is not None and conn is not None:
|
||||
try:
|
||||
cols = [d[0] for d in cursor.description]
|
||||
if col in cols:
|
||||
conn.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
|
||||
conn.commit()
|
||||
except Exception as exc:
|
||||
print(f"[提醒] 置位 {col} 失败: {exc}")
|
||||
return
|
||||
|
||||
own_conn = get_db()
|
||||
try:
|
||||
cur = own_conn.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
||||
if col in [d[0] for d in cur.description]:
|
||||
own_conn.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
|
||||
own_conn.commit()
|
||||
except Exception as exc:
|
||||
print(f"[提醒] 置位 {col} 失败: {exc}")
|
||||
finally:
|
||||
own_conn.close()
|
||||
|
||||
|
||||
# 0 分钟自动还车失败后的重试计数(进程内即可:重启后 restore/巡检会自动补还)
|
||||
_auto_return_retries: dict = {}
|
||||
AUTO_RETURN_RETRY_DELAY = 30 # 秒
|
||||
AUTO_RETURN_MAX_RETRIES = 6
|
||||
|
||||
|
||||
def _notify_auto_return_recovered(rental_id: int):
|
||||
"""重试若干次后终于还车成功:再发一封「已还上」,别让用户去点邮件里的旧按钮。"""
|
||||
try:
|
||||
from email_utils import send_email
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT bike_code, email FROM rentals WHERE id = ?", (rental_id,)).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
return
|
||||
to_email = (row["email"] or "").strip()
|
||||
if not to_email:
|
||||
return
|
||||
titled = f"自动还车已成功(#{row['bike_code']})"
|
||||
body = (f"上次自动还车失败后系统已重试并成功,车辆 #{row['bike_code']} 已还车,"
|
||||
f"这单不会再计费。\n\n如果你刚才点了邮件里的「还车」按钮,"
|
||||
f"看到「订单已结束」是正常的 —— 不用再操作。")
|
||||
send_email(to_email, f"【小白超人】{titled}", body,
|
||||
f"<p>{body.replace(chr(10), '<br/>')}</p>")
|
||||
print(f"[自动还车] rental_id={rental_id} 重试成功,已发最终成功通知")
|
||||
except Exception as exc:
|
||||
print(f"[自动还车] 重试成功通知发送失败: {exc}")
|
||||
|
||||
|
||||
def _alert_auto_return_exhausted(rental_id: int, bike_code: str, message: str = ""):
|
||||
"""重试耗尽仍失败:给管理员发告警邮件,不能只留一行 print。"""
|
||||
try:
|
||||
from alerts import get_alert_emails
|
||||
from email_utils import send_email
|
||||
recipients = get_alert_emails()
|
||||
if not recipients:
|
||||
print(f"[自动还车] rental_id={rental_id} 重试耗尽且没有配置告警邮箱")
|
||||
return
|
||||
title = f"自动还车失败需人工处理(#{bike_code})"
|
||||
body = (f"rental_id={rental_id} 车辆 #{bike_code} 自动还车已重试 "
|
||||
f"{AUTO_RETURN_MAX_RETRIES} 次仍失败。\n"
|
||||
f"最后一次错误:{message or '(无)'}\n\n"
|
||||
f"这单还在上游计费,请到管理后台「代还车」处理。")
|
||||
for to in recipients:
|
||||
send_email(to, f"【小白超人·告警】{title}", body,
|
||||
f"<p>{body.replace(chr(10), '<br/>')}</p>")
|
||||
print(f"[自动还车] rental_id={rental_id} 重试耗尽,已发告警给 {len(recipients)} 个邮箱")
|
||||
except Exception as exc:
|
||||
print(f"[自动还车] 重试耗尽告警发送失败: {exc}")
|
||||
|
||||
|
||||
def _schedule_auto_return_retry(rental_id: int, email: str, bike_code: str, user_id,
|
||||
message: str = ""):
|
||||
"""自动还车失败:30 秒后再试,最多 6 次。notified_0 保持 0,让各处调度还能再次触发。"""
|
||||
n = _auto_return_retries.get(rental_id, 0)
|
||||
if n >= AUTO_RETURN_MAX_RETRIES:
|
||||
print(f"[自动还车] rental_id={rental_id} 已重试 {n} 次仍失败,转人工")
|
||||
_alert_auto_return_exhausted(rental_id, bike_code, message)
|
||||
return
|
||||
_auto_return_retries[rental_id] = n + 1
|
||||
print(f"[自动还车] rental_id={rental_id} 第 {n+1} 次重试将在 "
|
||||
f"{AUTO_RETURN_RETRY_DELAY}s 后执行")
|
||||
_schedule_reminder(rental_id, AUTO_RETURN_RETRY_DELAY, "0", email, bike_code,
|
||||
user_id, send_notification=False,
|
||||
auto_return_enabled=True, auto_return_configured=True)
|
||||
|
||||
|
||||
def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
|
||||
email: str, bike_code: str, user_id: int = None,
|
||||
send_notification: bool = True,
|
||||
@@ -492,28 +838,55 @@ def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
|
||||
conn.close()
|
||||
return
|
||||
col = f"notified_{reminder_type}"
|
||||
if col in [d[0] for d in cursor.description] and rental[col] == 0:
|
||||
cursor.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
|
||||
conn.commit()
|
||||
has_col = col in [d[0] for d in cursor.description]
|
||||
if not (has_col and rental[col] == 0):
|
||||
conn.close()
|
||||
return
|
||||
|
||||
# 5/3/2/1 分钟这类纯提醒:先置位再发,发失败也不重发
|
||||
if reminder_type != "0":
|
||||
_mark_notified(rental_id, reminder_type, conn=conn, cursor=cursor)
|
||||
conn.close()
|
||||
return_result = None
|
||||
if reminder_type == "0":
|
||||
if auto_return_enabled and user_id:
|
||||
try:
|
||||
return_result = auto_return_bike(rental_id, user_id)
|
||||
except Exception as e:
|
||||
print(f"[自动还车] 失败: {e}")
|
||||
return_result = {"attempted": True, "success": False, "message": str(e)}
|
||||
elif not auto_return_configured:
|
||||
return_result = {"attempted": False, "success": False,
|
||||
"message": "用户未开启自动还车"}
|
||||
else:
|
||||
return_result = {"attempted": False, "success": False,
|
||||
"message": "该提醒未绑定微信订单,无法自动还车"}
|
||||
if send_notification:
|
||||
send_rental_notification(rental_id, reminder_type, return_result)
|
||||
send_rental_notification(rental_id, reminder_type, None)
|
||||
return
|
||||
|
||||
# 0 分钟:先把车还了,成功了才置位。
|
||||
# 原来先置位再还车,上游三次重试一失败就再也不会重试,订单在上游继续计费。
|
||||
conn.close()
|
||||
return_result = None
|
||||
if auto_return_enabled and user_id:
|
||||
try:
|
||||
return_result = auto_return_bike(rental_id, user_id)
|
||||
except Exception as e:
|
||||
print(f"[自动还车] 失败: {e}")
|
||||
return_result = {"attempted": True, "success": False, "message": str(e)}
|
||||
elif not auto_return_configured:
|
||||
return_result = {"attempted": False, "success": False,
|
||||
"message": "用户未开启自动还车"}
|
||||
else:
|
||||
conn.close()
|
||||
return_result = {"attempted": False, "success": False,
|
||||
"message": "该提醒未绑定微信订单,无法自动还车"}
|
||||
|
||||
success = bool(return_result and return_result.get("success"))
|
||||
had_retries = _auto_return_retries.get(rental_id, 0)
|
||||
if success:
|
||||
_auto_return_retries.pop(rental_id, None)
|
||||
_mark_notified(rental_id, "0")
|
||||
if had_retries:
|
||||
# 之前发过「自动还车失败」,这次终于还上了,必须再发一封收尾,
|
||||
# 否则用户会去点旧邮件里的还车按钮(那时订单已结束)
|
||||
_notify_auto_return_recovered(rental_id)
|
||||
elif auto_return_enabled and user_id:
|
||||
# 失败:不置位,短周期重试;页面横幅会提示「自动还车失败,点我重试」
|
||||
_schedule_auto_return_retry(
|
||||
rental_id, email, bike_code, user_id,
|
||||
str((return_result or {}).get("message") or ""))
|
||||
else:
|
||||
_mark_notified(rental_id, "0") # 未绑定/未开启:一次性事件,直接置位
|
||||
|
||||
if send_notification:
|
||||
send_rental_notification(rental_id, reminder_type, return_result)
|
||||
|
||||
timer = threading.Timer(delay_seconds, fire)
|
||||
timer.daemon = True
|
||||
@@ -613,22 +986,61 @@ def reschedule_user_rental_timers(user_id: int, apply_duration: bool = False):
|
||||
|
||||
|
||||
def restore_active_timers():
|
||||
"""启动时恢复所有未过期的计时器"""
|
||||
"""启动时恢复计时器;**重启前就已越过到期时间**的单子立刻补一次自动还车。
|
||||
|
||||
以前这里只捞 `end_time > now`,服务重启时刚好跨过 19 分钟的那一单
|
||||
既不会恢复计时器、也不会补还车,于是永久失去「自动还车」,
|
||||
月卡还会按超时继续扣钱。现在把「已过期但没有 expired」的行单独捡出来补还。
|
||||
"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
now_beijing = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||||
cursor.execute("""
|
||||
SELECT * FROM rentals
|
||||
WHERE expired = 0 AND end_time > ?
|
||||
""", (now_beijing,))
|
||||
for rental in cursor.fetchall():
|
||||
remaining = _get_remaining_seconds(dict(rental))
|
||||
cursor.execute("SELECT * FROM rentals WHERE expired = 0")
|
||||
active_rows = [dict(r) for r in cursor.fetchall()]
|
||||
conn.close()
|
||||
|
||||
restored = 0
|
||||
overdue = []
|
||||
skipped = 0
|
||||
for rental in active_rows:
|
||||
remaining = _get_remaining_seconds(rental)
|
||||
if remaining > 0:
|
||||
start_rental_timer(rental["id"], rental["email"], rental["bike_code"],
|
||||
remaining / 60, rental["user_id"])
|
||||
conn.close()
|
||||
print(f"[计时系统] 已恢复 {len(_active_timers)} 个活跃计时器")
|
||||
restored += 1
|
||||
elif _should_auto_return(rental):
|
||||
overdue.append(rental)
|
||||
else:
|
||||
# reminder 之类没有真实上游订单的单子:不要拿本地 id 去猜订单号
|
||||
skipped += 1
|
||||
|
||||
print(f"[计时系统] 已恢复 {restored} 个活跃计时器")
|
||||
if skipped:
|
||||
print(f"[计时系统] {skipped} 个过期单没有上游订单(reminder 等),跳过补还车")
|
||||
|
||||
# 补还车放到后台线程,别把启动流程卡住
|
||||
for rental in overdue:
|
||||
print(f"[计时系统] rental_id={rental['id']} 在重启前已过期,补一次自动还车")
|
||||
threading.Thread(target=_recover_overdue_rental, args=(rental,),
|
||||
daemon=True).start()
|
||||
|
||||
|
||||
def _recover_overdue_rental(rental: dict):
|
||||
"""重启补还车:失败就交给巡检线程与告警,不在这里死磕。"""
|
||||
rental_id = rental.get("id")
|
||||
user_id = rental.get("user_id")
|
||||
if not _should_auto_return(rental):
|
||||
# 没有真实上游订单(reminder / 老记录),补还车必然 204010,别白打三次上游
|
||||
print(f"[计时系统] rental_id={rental_id} 没有上游订单号,跳过补还车")
|
||||
return
|
||||
try:
|
||||
_time.sleep(3) # 等调度线程和上游会话就绪
|
||||
if not user_id:
|
||||
print(f"[计时系统] rental_id={rental_id} 没有 user_id,跳过补还车")
|
||||
return
|
||||
result = _run_recovery(rental_id, user_id, rental.get("order_id"))
|
||||
print(f"[计时系统] 补还车结果 rental_id={rental_id}: {result.get('message')}")
|
||||
except Exception as exc:
|
||||
print(f"[计时系统] 补还车异常 rental_id={rental_id}: {exc}")
|
||||
|
||||
|
||||
# ========== 用户订单检测系统 ==========
|
||||
@@ -664,6 +1076,13 @@ def stop_user_order_checker(user_id: int):
|
||||
def _user_order_checker_loop(user_id: int, stop_event: threading.Event):
|
||||
"""用户订单检测线程主循环"""
|
||||
while not stop_event.is_set():
|
||||
# 兜底扫一遍超期未还的单(内部 10 分钟节流,不会每轮都全表扫)。
|
||||
# 放在循环里而不是 _check_user_order 里:启动路径一变 restore 不跑时,
|
||||
# 这些僵尸单就靠这里清;同时保持单测里的 _check_user_order 纯净。
|
||||
try:
|
||||
sweep_overdue_rentals()
|
||||
except Exception as exc:
|
||||
print(f"[订单检测] 超期订单兜底扫描失败: {exc}")
|
||||
try:
|
||||
_check_user_order(user_id)
|
||||
except Exception as e:
|
||||
@@ -695,7 +1114,7 @@ def _check_user_order(user_id: int):
|
||||
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||||
if info.get("rtn_code") != 0:
|
||||
if info.get("rtn_code") == 102001 or info.get("token_invalid"):
|
||||
# token_id 已被上游判定失效(通常是小程序重新登录踢掉了旧会话):
|
||||
# token_id 已被上游判定失效(凭据过期/被上游拒绝):
|
||||
# 停止轮询避免无效请求;用户在个人中心/管理端更新凭据时会自动重启线程
|
||||
print(f"[订单检测] 用户 {user_id} 凭据已失效,停止检测线程,等待更新凭据")
|
||||
stop_user_order_checker(user_id)
|
||||
@@ -722,12 +1141,31 @@ def _check_user_order(user_id: int):
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"SELECT id, source, expired, end_time FROM rentals WHERE order_id = ? AND user_id = ?",
|
||||
"SELECT id, order_id, source, expired, end_time FROM rentals "
|
||||
"WHERE order_id = ? AND user_id = ?",
|
||||
(order_id, user_id)
|
||||
)
|
||||
existing = cursor.fetchone()
|
||||
|
||||
if existing and existing["source"] in ("unlock", "sync", "shared") and existing["expired"] == 0:
|
||||
if existing and existing["expired"] == 0:
|
||||
rental = dict(existing)
|
||||
# 到期时间已经过了却还挂着(重启丢了计时器、或 0 点那次失败):
|
||||
# 巡检必须补一次自动还车,不能再无脑 return,否则这一单永远还不掉。
|
||||
# 只有「真的有上游订单」的来源才补(reminder 之类拿本地 id 当订单号必然失败)。
|
||||
if _should_auto_return(rental) and _rental_end_time_passed(rental):
|
||||
conn.close()
|
||||
if _recover_throttled(rental["id"]):
|
||||
# 彻底还不上(车被锁死/订单状态怪)时不能每分钟重打:
|
||||
# 5 分钟一次,避免每分钟 3~4 个上游请求 + 线程睡 15 秒的死循环
|
||||
return {"ok": True, "active": True, "order_id": order_id,
|
||||
"recovering": True}
|
||||
print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
|
||||
threading.Thread(
|
||||
target=lambda: _run_recovery(rental["id"], user_id, order_id),
|
||||
daemon=True
|
||||
).start()
|
||||
return {"ok": True, "active": True, "order_id": order_id,
|
||||
"recovered": True}
|
||||
conn.close()
|
||||
return {"ok": True, "active": True, "order_id": order_id}
|
||||
|
||||
@@ -809,26 +1247,6 @@ def _finish_active_wechat_rentals(user_id: int, reason: str):
|
||||
f"order_id={row['order_id']}, source={row['source']}, reason={reason}")
|
||||
|
||||
|
||||
def _cleanup_stale_rentals(user_id: int):
|
||||
"""用户无活跃订单时,清理本地残留的 active 记录"""
|
||||
import datetime as dt
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT id, order_id, source FROM rentals
|
||||
WHERE user_id = ? AND expired = 0 AND end_time < ?
|
||||
""", (user_id, now_str))
|
||||
for row in cursor.fetchall():
|
||||
rental_id = row["id"]
|
||||
_cancel_rental_timers(rental_id)
|
||||
_mark_returned(rental_id)
|
||||
print(f"[订单检测] 清理过期记录: rental_id={rental_id}, order_id={row['order_id']}, source={row['source']}")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def start_all_order_checkers():
|
||||
"""启动所有有凭据用户的订单检测线程。
|
||||
错峰启动:每个线程间隔 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
|
||||
+419
@@ -0,0 +1,419 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""百度「步行路线规划(轻量)」:真实道路距离 + 步行耗时。
|
||||
|
||||
为什么要它:卡片原来只会拿直线距离 ÷ 80 米/分钟估时间,绕楼绕围墙时明显偏乐观。
|
||||
百度轻量级路线规划接口(directionlite)直接给 `distance`(米)和 `duration`(秒),
|
||||
且支持 `coord_type=gcj02` —— 正好和上游车辆坐标同一套,不用转换。
|
||||
|
||||
配额与限流(2026-11 实测控制台:0.5 万次/天,3 QPS):
|
||||
- 结果按「起点+终点」四舍五入到 4 位小数(约 10 米)入库缓存 7 天;
|
||||
- 进程内做 3 QPS 节流(保守取 350ms 间隔);
|
||||
- 任何失败(没配 AK / 240 APP 服务被禁用 / 超时 / 配额耗尽)都退回本地估算,
|
||||
绝不让卡片空着。
|
||||
|
||||
配置(缺一即走估算):
|
||||
- 环境变量 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK
|
||||
- 或 server_config.json 里的 "baidu_route_ak" / "baidu_route_sk"
|
||||
注意:
|
||||
- 必须用**服务端**类型的 AK,且开通「步行路线规划(轻量)」;
|
||||
- 页面里那个浏览器端 AK 调这个接口会返回 {"status":240,"message":"APP 服务被禁用"}(已实测);
|
||||
- 若该 AK 在控制台开了「SN 校验」,请求必须带 sn(否则 211),所以需要配套的 SK,
|
||||
见 `_build_query()`。
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, quote_plus, urlencode
|
||||
|
||||
import requests
|
||||
|
||||
HOST = "https://api.map.baidu.com"
|
||||
PATH = "/directionlite/v1/walking"
|
||||
BASE_URL = HOST + PATH
|
||||
CACHE_PATH = Path(__file__).parent / "walk_cache.db"
|
||||
CACHE_TTL_SECONDS = 7 * 24 * 3600
|
||||
# 坐标精度:4 位小数 ≈ 11 米,够用且能显著提高缓存命中率
|
||||
COORD_PRECISION = 4
|
||||
# 3 QPS 配额,保守按 350ms 一次
|
||||
MIN_INTERVAL_SECONDS = 0.35
|
||||
REQUEST_TIMEOUT = 6
|
||||
|
||||
# 本地估算参数(百度不可用时兜底)
|
||||
DETOUR_FACTOR = 1.3 # 直线 -> 道路的经验绕行系数
|
||||
WALK_METERS_PER_MIN = 75.0 # 4.5 km/h
|
||||
|
||||
_lock = threading.Lock()
|
||||
_last_call_at = [0.0]
|
||||
_cache_ready = [False]
|
||||
|
||||
|
||||
# ========== 配置 ==========
|
||||
|
||||
def _server_config() -> dict:
|
||||
try:
|
||||
path = Path(__file__).parent / "server_config.json"
|
||||
if path.exists():
|
||||
return json.loads(path.read_text("utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def get_ak() -> str:
|
||||
"""服务端 AK:环境变量优先,其次 server_config.json 的 baidu_route_ak。"""
|
||||
env = (os.environ.get("BAIDU_ROUTE_AK") or "").strip()
|
||||
if env:
|
||||
return env
|
||||
return str(_server_config().get("baidu_route_ak") or "").strip()
|
||||
|
||||
|
||||
def get_sk() -> str:
|
||||
"""SN 校验用的 SK(私钥)。AK 未开 SN 校验时可以留空。"""
|
||||
env = (os.environ.get("BAIDU_ROUTE_SK") or "").strip()
|
||||
if env:
|
||||
return env
|
||||
return str(_server_config().get("baidu_route_sk") or "").strip()
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
return bool(get_ak())
|
||||
|
||||
|
||||
def save_credentials(ak: str, sk: str = None) -> bool:
|
||||
"""把 AK/SK 写进 server_config.json(管理端弹窗用)。
|
||||
|
||||
sk 传 None 表示保持原值不动;传 "" 表示清空。
|
||||
"""
|
||||
path = Path(__file__).parent / "server_config.json"
|
||||
try:
|
||||
cfg = {}
|
||||
if path.exists():
|
||||
cfg = json.loads(path.read_text("utf-8")) or {}
|
||||
cfg["baidu_route_ak"] = (ak or "").strip()
|
||||
if sk is not None:
|
||||
cfg["baidu_route_sk"] = (sk or "").strip()
|
||||
path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return True
|
||||
except Exception as exc:
|
||||
print(f"[步行路线] 保存 AK/SK 失败: {exc}")
|
||||
return False
|
||||
|
||||
|
||||
def masked_credentials() -> dict:
|
||||
"""给管理端回显用:AK 全量(管理员要看),SK 只回显尾 4 位。"""
|
||||
ak = get_ak()
|
||||
sk = get_sk()
|
||||
return {"ak": ak, "sk_set": bool(sk),
|
||||
"sk_tail": sk[-4:] if sk else "", "enabled": bool(ak)}
|
||||
|
||||
|
||||
def build_query(params: dict, sk: str = "", mode: str = "official",
|
||||
path: str = None) -> str:
|
||||
"""按百度 SN 规则拼查询串。
|
||||
|
||||
百度官方样例(geocoder/v2 那份)与社区常见写法算出的 sn 不一致,
|
||||
没有 SK 无法判定哪个对,所以两种都实现,由上层自动试:
|
||||
- official:quote("path?query", safe=...) -> 追加 SK -> quote_plus -> md5
|
||||
- simple :urlencode(按 key 升序, safe="") -> md5("path?query" + SK)
|
||||
"""
|
||||
api_path = path or PATH # SN 是绑路径的,换接口必须换路径
|
||||
items = sorted((k, v) for k, v in params.items() if k != "sn")
|
||||
if mode == "simple":
|
||||
query = urlencode(items, encoding="utf-8", safe="")
|
||||
if not sk:
|
||||
return query
|
||||
digest = hashlib.md5((api_path + "?" + query + sk).encode("utf-8")).hexdigest()
|
||||
return query + "&sn=" + digest
|
||||
|
||||
raw_query = "&".join(f"{k}={v}" for k, v in items)
|
||||
encoded = quote(api_path + "?" + raw_query, safe="/:=&?#+!$,;'@()*[]")
|
||||
query = encoded[len(api_path) + 1:]
|
||||
if not sk:
|
||||
return query
|
||||
digest = hashlib.md5(quote_plus(encoded + sk).encode("utf-8")).hexdigest()
|
||||
return query + "&sn=" + digest
|
||||
|
||||
|
||||
# 记住哪种 SN 算法能通,避免每次先撞一次 211
|
||||
_SN_MODE = [None]
|
||||
|
||||
|
||||
def _sn_modes():
|
||||
if _SN_MODE[0]:
|
||||
other = "simple" if _SN_MODE[0] != "simple" else "official"
|
||||
return [_SN_MODE[0], other]
|
||||
return ["official", "simple"]
|
||||
|
||||
|
||||
# ========== 缓存 ==========
|
||||
|
||||
def _conn():
|
||||
conn = sqlite3.connect(CACHE_PATH, timeout=5)
|
||||
if not _cache_ready[0]:
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS walk_cache (
|
||||
key TEXT PRIMARY KEY,
|
||||
distance_m INTEGER NOT NULL,
|
||||
duration_s INTEGER NOT NULL,
|
||||
created_at REAL NOT NULL
|
||||
)
|
||||
""")
|
||||
conn.commit()
|
||||
_cache_ready[0] = True
|
||||
return conn
|
||||
|
||||
|
||||
def _cache_key(o_lat, o_lng, d_lat, d_lng) -> str:
|
||||
p = COORD_PRECISION
|
||||
return "%.*f,%.*f|%.*f,%.*f" % (p, o_lat, p, o_lng, p, d_lat, p, d_lng)
|
||||
|
||||
|
||||
def _cache_get(key):
|
||||
try:
|
||||
conn = _conn()
|
||||
row = conn.execute(
|
||||
"SELECT distance_m, duration_s, created_at FROM walk_cache WHERE key = ?",
|
||||
(key,)).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
return None
|
||||
if time.time() - float(row[2]) > CACHE_TTL_SECONDS:
|
||||
return None
|
||||
return {"distance": int(row[0]), "duration": int(row[1])}
|
||||
except Exception as exc:
|
||||
print(f"[步行路线] 读缓存失败: {exc}")
|
||||
return None
|
||||
|
||||
|
||||
def _cache_put(key, distance_m, duration_s):
|
||||
try:
|
||||
conn = _conn()
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO walk_cache (key, distance_m, duration_s, created_at) "
|
||||
"VALUES (?, ?, ?, ?)", (key, int(distance_m), int(duration_s), time.time()))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
except Exception as exc:
|
||||
print(f"[步行路线] 写缓存失败: {exc}")
|
||||
|
||||
|
||||
# ========== 节流 ==========
|
||||
|
||||
def _throttle():
|
||||
"""全局 3 QPS 上限(百度给的并发就是 3)。"""
|
||||
with _lock:
|
||||
wait = _last_call_at[0] + MIN_INTERVAL_SECONDS - time.time()
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
_last_call_at[0] = time.time()
|
||||
|
||||
|
||||
# ========== 估算兜底 ==========
|
||||
|
||||
# 百度各出行方式的距离上限(公里)。步行超 200km 会直接报
|
||||
# "the distance of path must less then 200Km",先自己挡掉。
|
||||
_MAX_ROUTE_KM = {"walking": 200, "riding": 200, "driving": 500}
|
||||
|
||||
|
||||
def _haversine_m(lat1, lng1, lat2, lng2) -> float:
|
||||
"""两点球面距离(米)。"""
|
||||
r = 6371000.0
|
||||
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||||
dphi = p2 - p1
|
||||
dlmb = math.radians(lng2 - lng1)
|
||||
a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlmb / 2) ** 2
|
||||
return 2 * r * math.asin(math.sqrt(a))
|
||||
|
||||
|
||||
def estimate(origin_lat, origin_lng, dest_lat, dest_lng) -> dict:
|
||||
"""直线 → 道路经验估算。永远有返回值。"""
|
||||
try:
|
||||
lat1, lng1, lat2, lng2 = map(float, (origin_lat, origin_lng, dest_lat, dest_lng))
|
||||
except (TypeError, ValueError):
|
||||
return {"distance": 0, "duration": 0, "source": "none"}
|
||||
r = 6371000.0
|
||||
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||||
dphi = p2 - p1
|
||||
dlmb = math.radians(lng2 - lng1)
|
||||
a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlmb / 2) ** 2
|
||||
straight = 2 * r * math.asin(math.sqrt(a))
|
||||
distance = int(round(straight * DETOUR_FACTOR))
|
||||
duration = int(round(max(distance, 1) / WALK_METERS_PER_MIN * 60))
|
||||
return {"distance": distance, "duration": duration, "straight": int(round(straight)),
|
||||
"source": "estimate"}
|
||||
|
||||
|
||||
# ========== 百度接口 ==========
|
||||
|
||||
def _call_baidu(ak, sk, origin_lat, origin_lng, dest_lat, dest_lng,
|
||||
mode="official", api="walking", with_steps=False) -> dict:
|
||||
_throttle()
|
||||
params = {
|
||||
"ak": ak,
|
||||
"origin": f"{origin_lat:.6f},{origin_lng:.6f}",
|
||||
"destination": f"{dest_lat:.6f},{dest_lng:.6f}",
|
||||
"coord_type": "gcj02", # 入参坐标系:上游车辆坐标就是 GCJ02
|
||||
# 关键:coord_type 只管"输入",折线默认按 BD09 返回(ret_coordtype 默认 bd09ll)。
|
||||
# 不显式指定的话,前端再把 BD09 当 GCJ02 转一次,整体会偏 500~900 米。
|
||||
"ret_coordtype": "gcj02",
|
||||
}
|
||||
if sk:
|
||||
# 开了 SN 校验就必须带 timestamp(否则 status=2 timestamp is required when sn isset)
|
||||
params["timestamp"] = int(time.time())
|
||||
api_path = "/directionlite/v1/" + api
|
||||
url = HOST + api_path + "?" + build_query(params, sk, mode, api_path)
|
||||
resp = requests.get(url, timeout=REQUEST_TIMEOUT)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
status = data.get("status")
|
||||
if status != 0:
|
||||
raise RuntimeError(f"status={status} message={data.get('message')}")
|
||||
result = data.get("result") or {}
|
||||
# directionlite 正常返回 result.routes[0].{distance,duration};
|
||||
# 少数版本把 distance/duration 直接挂在 result 上,一并兜住。
|
||||
route = (result.get("routes") or [{}])[0]
|
||||
distance = route.get("distance", result.get("distance"))
|
||||
duration = route.get("duration", result.get("duration"))
|
||||
if distance is None or duration is None:
|
||||
raise RuntimeError(f"返回缺字段: {str(data)[:200]}")
|
||||
out = {"distance": int(distance), "duration": int(duration)}
|
||||
if with_steps:
|
||||
out["steps"] = _parse_steps(route.get("steps") or [])
|
||||
out["points"] = _merge_path(out["steps"])
|
||||
return out
|
||||
|
||||
|
||||
def _parse_steps(raw_steps) -> list:
|
||||
"""把 steps[] 抽成前端要的最小集合(含折线)。"""
|
||||
steps = []
|
||||
for st in raw_steps:
|
||||
if not isinstance(st, dict):
|
||||
continue
|
||||
points = []
|
||||
for pair in str(st.get("path") or "").split(";"):
|
||||
if not pair:
|
||||
continue
|
||||
try:
|
||||
lng_s, lat_s = pair.split(",")
|
||||
points.append([float(lng_s), float(lat_s)])
|
||||
except ValueError:
|
||||
continue
|
||||
steps.append({
|
||||
"instruction": str(st.get("instruction") or ""),
|
||||
"distance": int(st.get("distance") or 0),
|
||||
"duration": int(st.get("duration") or 0),
|
||||
"turn_type": str(st.get("turn_type") or ""),
|
||||
"turn_type_id": st.get("turn_type_id"),
|
||||
"points": points,
|
||||
})
|
||||
return steps
|
||||
|
||||
|
||||
def _merge_path(steps, max_points=1500) -> list:
|
||||
"""把所有分段的折线接成一条,超长时按等间隔抽稀。"""
|
||||
points = []
|
||||
for st in steps:
|
||||
pts = st.get("points") or []
|
||||
if points and pts and points[-1] == pts[0]:
|
||||
pts = pts[1:]
|
||||
points.extend(pts)
|
||||
if len(points) > max_points:
|
||||
stride = max(1, len(points) // max_points)
|
||||
sampled = points[::stride]
|
||||
if sampled[-1] != points[-1]:
|
||||
sampled.append(points[-1])
|
||||
return sampled
|
||||
return points
|
||||
|
||||
|
||||
def get_nav_route(origin_lat, origin_lng, dest_lat, dest_lng, api="walking") -> dict:
|
||||
"""导航用:一次拿齐距离/耗时/分段指引/整条折线。失败返回 error。"""
|
||||
try:
|
||||
o_lat, o_lng = float(origin_lat), float(origin_lng)
|
||||
d_lat, d_lng = float(dest_lat), float(dest_lng)
|
||||
except (TypeError, ValueError):
|
||||
return {"error": "坐标非法"}
|
||||
|
||||
# 百度步行/骑行路线对距离有上限(超过会返回 status=2 的英文报错),
|
||||
# 先自己算直线距离挡掉,别把 "the distance of path must less then 200Km" 抛给用户。
|
||||
max_km = _MAX_ROUTE_KM.get(api, 200)
|
||||
if max_km:
|
||||
straight_km = _haversine_m(o_lat, o_lng, d_lat, d_lng) / 1000.0
|
||||
if straight_km > max_km:
|
||||
return {"error": f"距离太远(约 {straight_km:.0f} 公里),不提供{api}导航",
|
||||
"error_kind": "too_far"}
|
||||
|
||||
ak = get_ak()
|
||||
if not ak:
|
||||
return {"error": "未配置百度 AK"}
|
||||
|
||||
sk = get_sk()
|
||||
last_error = None
|
||||
for mode in _sn_modes():
|
||||
try:
|
||||
got = _call_baidu(ak, sk, o_lat, o_lng, d_lat, d_lng, mode,
|
||||
api=api, with_steps=True)
|
||||
_SN_MODE[0] = mode
|
||||
return {**got, "api": api}
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
text = str(exc)
|
||||
if "211" not in text and "SN" not in text.upper():
|
||||
break
|
||||
msg = str(last_error)
|
||||
if "200Km" in msg or "too long" in msg.lower():
|
||||
return {"error": "距离太远,无法规划路线", "error_kind": "too_far"}
|
||||
return {"error": f"百度返回失败: {last_error}"}
|
||||
|
||||
|
||||
def get_walk_route(origin_lat, origin_lng, dest_lat, dest_lng, use_cache=True) -> dict:
|
||||
"""返回 {distance(米), duration(秒), source: baidu|cache|estimate}。
|
||||
|
||||
source=cache 也代表数据来自百度(命中缓存)。
|
||||
"""
|
||||
try:
|
||||
o_lat, o_lng = float(origin_lat), float(origin_lng)
|
||||
d_lat, d_lng = float(dest_lat), float(dest_lng)
|
||||
except (TypeError, ValueError):
|
||||
return estimate(origin_lat, origin_lng, dest_lat, dest_lng)
|
||||
|
||||
if not (math.isfinite(o_lat) and math.isfinite(o_lng)
|
||||
and math.isfinite(d_lat) and math.isfinite(d_lng)):
|
||||
return estimate(o_lat, o_lng, d_lat, d_lng)
|
||||
|
||||
key = _cache_key(o_lat, o_lng, d_lat, d_lng)
|
||||
if use_cache:
|
||||
hit = _cache_get(key)
|
||||
if hit:
|
||||
return {**hit, "source": "cache"}
|
||||
|
||||
ak = get_ak()
|
||||
if not ak:
|
||||
return estimate(o_lat, o_lng, d_lat, d_lng)
|
||||
|
||||
sk = get_sk()
|
||||
got = None
|
||||
last_error = None
|
||||
for mode in _sn_modes():
|
||||
try:
|
||||
got = _call_baidu(ak, sk, o_lat, o_lng, d_lat, d_lng, mode)
|
||||
_SN_MODE[0] = mode # 记住能通的算法
|
||||
break
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
text = str(exc)
|
||||
# 只有 SN 相关错误才值得换算法重试,其余(配额/超时)直接退回估算
|
||||
if "211" not in text and "SN" not in text.upper():
|
||||
break
|
||||
if got is None:
|
||||
print(f"[步行路线] 百度调用失败,退回估算: {last_error}")
|
||||
return estimate(o_lat, o_lng, d_lat, d_lng)
|
||||
|
||||
_cache_put(key, got["distance"], got["duration"])
|
||||
return {**got, "source": "baidu"}
|
||||
@@ -1,442 +1,444 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""微信API通信模块
|
||||
|
||||
凭据模型(对照 98/ 反编译小程序与实机抓包还原):
|
||||
- token_id:登录后服务端下发的会话标识(单会话:小程序重新登录即失效)。
|
||||
上游目前唯一强校验的头,必填。
|
||||
- access_token:登录响应里的 JWT(30 天有效)。小程序用它在本地实时计算签名:
|
||||
hsf-x-signature = sha1(access_token + base64(签名串))。选填。
|
||||
|
||||
签名策略(双模式 + 强验证开关):
|
||||
- 常规模式:有真实 access_token 就实时计算签名;否则生成形似合法的
|
||||
sha1 伪装签名(40 位 hex、随请求变化,防上游日志识别出固定异常值)。
|
||||
- 强验证模式(管理端开关,server_config.json 持久化):模拟上游开启
|
||||
签名校验后的行为——没有真实 access_token 的凭据直接拒绝发起请求,
|
||||
提前给出明确错误,而不是发出必然失败的请求。
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import requests
|
||||
import gzip
|
||||
from pathlib import Path
|
||||
|
||||
# 旧占位签名值(仅用于识别"未配置 accessToken"的存量配置,不再对外发送)
|
||||
_DUMMY_SIGNATURE = "xiaobai"
|
||||
|
||||
|
||||
def fake_signature(timestamp: str, token_id: str) -> str:
|
||||
"""未配置 accessToken 时生成形似合法的签名:40 位小写 hex(sha1 输出格式),
|
||||
且随时间戳/凭据变化,与真实流量的日志特征一致,避免上游从日志中识别出异常固定值。"""
|
||||
return hashlib.sha1(f"{timestamp}{token_id}".encode("utf-8")).hexdigest()
|
||||
|
||||
BASE_URL = "https://bike.sdlongren.com"
|
||||
|
||||
# 强验证开关的持久化文件
|
||||
_SERVER_CONFIG_PATH = Path(__file__).parent / "server_config.json"
|
||||
|
||||
# 从配置文件加载全局凭据
|
||||
_TOKEN_CONFIG_PATH = Path(__file__).parent / "token_config.txt"
|
||||
|
||||
|
||||
# ========== 强验证开关 ==========
|
||||
def _load_server_config() -> dict:
|
||||
try:
|
||||
if _SERVER_CONFIG_PATH.exists():
|
||||
return json.loads(_SERVER_CONFIG_PATH.read_text("utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def is_strict_mode() -> bool:
|
||||
"""上游强签名验证开关:开启后无真实 accessToken 的凭据将被拒绝发起请求"""
|
||||
return bool(_load_server_config().get("require_access_token"))
|
||||
|
||||
|
||||
def set_strict_mode(enabled: bool) -> bool:
|
||||
try:
|
||||
cfg = _load_server_config()
|
||||
cfg["require_access_token"] = bool(enabled)
|
||||
_SERVER_CONFIG_PATH.write_text(json.dumps(cfg, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[强验证开关] 保存失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def has_real_access_token(access_token) -> bool:
|
||||
"""是否为可用于计算签名的真实 accessToken(排除空值与占位符)"""
|
||||
return bool(access_token) and access_token != _DUMMY_SIGNATURE
|
||||
|
||||
|
||||
def parse_access_token_expiry(access_token) -> dict:
|
||||
"""从 accessToken(JWT)解析登录态有效期。
|
||||
|
||||
小程序登录响应中的 accessToken 是 RS256 JWT,payload 里带标准
|
||||
iat / nbf / exp(实测有效期 30 天)。只解码不验签——我们只需要
|
||||
展示大致过期时间,签名校验由上游负责。
|
||||
返回:{"parseable": bool, "expire_at": ts|None, "expire_time": "YYYY-MM-DD HH:MM"|None,
|
||||
"remaining_seconds": int|None, "source": "exp"|"iat+30d"|None, "reason": str}
|
||||
"""
|
||||
import base64 as _b64
|
||||
import datetime as _dt
|
||||
import json as _json
|
||||
|
||||
token = (access_token or "").strip()
|
||||
tz = _dt.timezone(_dt.timedelta(hours=8))
|
||||
result = {"parseable": False, "expire_at": None, "expire_time": None,
|
||||
"remaining_seconds": None, "source": None, "reason": ""}
|
||||
|
||||
def _fmt(ts: int) -> str:
|
||||
return _dt.datetime.fromtimestamp(ts, tz).strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
if not has_real_access_token(token):
|
||||
result["reason"] = "未填写 AccessToken"
|
||||
return result
|
||||
parts = token.split(".")
|
||||
if len(parts) != 3 or not token.startswith("ey"):
|
||||
result["reason"] = "不是标准 JWT 格式,无法解析过期时间"
|
||||
return result
|
||||
try:
|
||||
pad = parts[1] + "=" * (-len(parts[1]) % 4)
|
||||
payload = _json.loads(_b64.urlsafe_b64decode(pad))
|
||||
except Exception:
|
||||
result["reason"] = "JWT payload 解码失败"
|
||||
return result
|
||||
|
||||
exp = payload.get("exp") if isinstance(payload, dict) else None
|
||||
iat = payload.get("iat") if isinstance(payload, dict) else None
|
||||
try:
|
||||
exp = int(exp) if exp is not None else None
|
||||
iat = int(iat) if iat is not None else None
|
||||
except (TypeError, ValueError):
|
||||
exp = iat = None
|
||||
|
||||
if exp:
|
||||
result.update(parseable=True, expire_at=exp, expire_time=_fmt(exp),
|
||||
source="exp")
|
||||
elif iat:
|
||||
expire = iat + 30 * 86400 # 实测 accessToken 有效期 30 天
|
||||
result.update(parseable=True, expire_at=expire, expire_time=_fmt(expire),
|
||||
source="iat+30d")
|
||||
else:
|
||||
result["reason"] = "JWT 中没有 exp/iat 字段,无法推算有效期"
|
||||
return result
|
||||
|
||||
result["remaining_seconds"] = int(result["expire_at"] - _dt.datetime.now(tz).timestamp())
|
||||
return result
|
||||
|
||||
|
||||
def _strict_reject() -> dict:
|
||||
return {"rtn_code": 403,
|
||||
"message": "已开启上游强签名验证:请先填写 AccessToken(从微信小程序登录响应中获取)"}
|
||||
|
||||
|
||||
def _load_token_config():
|
||||
"""从 token_config.txt 加载全局凭据。
|
||||
|
||||
token_id:必填(重新登录小程序会失效,单会话策略)。
|
||||
access_token(旧键名 wx_signature 兼容读取):选填,用于实时计算签名。
|
||||
"""
|
||||
config = {"token_id": "", "access_token": ""}
|
||||
try:
|
||||
if _TOKEN_CONFIG_PATH.exists():
|
||||
for line in _TOKEN_CONFIG_PATH.read_text("utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
k, v = line.split("=", 1)
|
||||
k = k.strip()
|
||||
if k == "wx_signature": # 旧配置键名兼容
|
||||
k = "access_token"
|
||||
config[k] = v.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return config
|
||||
|
||||
|
||||
_TOKEN_CONFIG = _load_token_config()
|
||||
_GLOBAL_TOKEN_ID = _TOKEN_CONFIG.get("token_id", "")
|
||||
_GLOBAL_ACCESS_TOKEN = _TOKEN_CONFIG.get("access_token", "")
|
||||
|
||||
# 全局凭据只来自 token_config.txt / 管理后台保存,代码中不硬编码
|
||||
if not _GLOBAL_TOKEN_ID:
|
||||
print("[全局凭据] 警告: token_config.txt 中未配置 token_id,"
|
||||
"地图采集等全局请求将无法通过上游校验,请在管理后台填写")
|
||||
|
||||
HEADERS = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"hsf-x-signature": "",
|
||||
"hsf-x-timestamp": "",
|
||||
"hsf-x-tokenid": _GLOBAL_TOKEN_ID,
|
||||
"xweb_xhr": "1",
|
||||
"platform": "xiaobai",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 MicroMessenger/7.0",
|
||||
"content-type": "application/json",
|
||||
"accept": "*/*",
|
||||
"accept-language": "*",
|
||||
"sec-fetch-site": "cross-site",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-dest": "empty",
|
||||
"referer": "https://servicewechat.com/wx10426ca961518f43/108/page-frame.html",
|
||||
}
|
||||
|
||||
SEARCH_BIKE_URL = "https://bike.sdlongren.com/project/search_bicycle"
|
||||
SEARCH_HEADERS = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "*/*",
|
||||
}
|
||||
|
||||
|
||||
def build_sign_string(method: str, path: str, timestamp: str, token_id: str,
|
||||
params: dict = None) -> str:
|
||||
"""还原小程序 c(method, path, ts, params, needToken) 的签名串"""
|
||||
s = f"{method.upper()}$Hsf-X-Timestamp:{timestamp}Hsf-X-TokenId:{token_id}${path}"
|
||||
if params:
|
||||
s += "?"
|
||||
for k in sorted(params.keys()):
|
||||
v = params[k]
|
||||
# 与小程序一致:空字符串值只拼 key,嵌套对象/数组跳过
|
||||
if not k or (isinstance(v, str) and v == ""):
|
||||
s += f"{k}&"
|
||||
elif isinstance(v, (dict, list)):
|
||||
continue
|
||||
else:
|
||||
s += f"{k}={v}&"
|
||||
s = s.rstrip("&")
|
||||
return s
|
||||
|
||||
|
||||
def compute_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||
token_id: str, params: dict = None) -> str:
|
||||
"""小程序算法:sha1(accessToken + base64(sign_str))"""
|
||||
sign_str = build_sign_string(method, path, timestamp, token_id, params)
|
||||
b64 = base64.b64encode(sign_str.encode("utf-8")).decode("ascii")
|
||||
return hashlib.sha1(f"{access_token}{b64}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def make_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||
token_id: str, params: dict = None) -> str:
|
||||
"""有真实 accessToken 就按小程序算法实时签名;
|
||||
没有则生成形似合法的 sha1 签名(40 位 hex、随请求变化),防上游日志识别。"""
|
||||
if has_real_access_token(access_token):
|
||||
return compute_signature(access_token, method, path, timestamp,
|
||||
token_id, params)
|
||||
return fake_signature(timestamp, token_id)
|
||||
|
||||
|
||||
def get_headers(timestamp: str = None) -> dict:
|
||||
"""生成带时间戳的请求头"""
|
||||
ts = timestamp or str(int(time.time()))
|
||||
headers = HEADERS.copy()
|
||||
headers["hsf-x-timestamp"] = ts
|
||||
return headers
|
||||
|
||||
|
||||
def get_signature_headers(timestamp: str = None) -> dict:
|
||||
"""车辆查询接口(/project/search_bicycle)用的简化签名头。
|
||||
有全局 accessToken 时按小程序算法计算(针对该路径);否则生成
|
||||
sha1(时间戳+token_id) 占位值(上游目前不校验)。"""
|
||||
ts = timestamp or str(int(time.time()))
|
||||
token_id = HEADERS.get("hsf-x-tokenid", "")
|
||||
if has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||
sig = compute_signature(_GLOBAL_ACCESS_TOKEN, "POST", "/project/search_bicycle",
|
||||
ts, token_id)
|
||||
else:
|
||||
sig = fake_signature(ts, token_id)
|
||||
return {
|
||||
"hsf-x-timestamp": ts,
|
||||
"hsf-x-tokenid": token_id,
|
||||
"hsf-x-signature": sig,
|
||||
"platform": "xiaobai",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_token_invalid(result: dict, scope: str):
|
||||
"""上游返回 102001(token_id 失效,通常是小程序重新登录把旧会话踢掉)时
|
||||
统一改写响应:scope='user' 面向用户提示重新配置;scope='global' 面向管理员。
|
||||
注意 global 文案刻意不含 Token 字样,避免前端误弹用户级凭据弹窗。"""
|
||||
if isinstance(result, dict) and result.get("rtn_code") == 102001:
|
||||
result["token_invalid"] = True
|
||||
if scope == "user":
|
||||
result["message"] = "Token失效,微信凭据已过期,请在个人中心重新配置"
|
||||
else:
|
||||
result["message"] = "地图数据暂不可用:服务器全局凭据已失效,请联系管理员更新"
|
||||
return result
|
||||
|
||||
|
||||
def request_api(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
||||
"""Share global map reads across users, collection jobs and worker processes."""
|
||||
if method.upper() == "GET" and path == "/project/map":
|
||||
from map_cache import shared_map_cache
|
||||
bike_type = str((params or {}).get("type", "1")).strip()
|
||||
return shared_map_cache.get(bike_type, lambda: _request_api_uncached(
|
||||
method, path, params={**(params or {}), "type": bike_type}, data=data))
|
||||
return _request_api_uncached(method, path, params=params, data=data)
|
||||
|
||||
|
||||
def _request_api_uncached(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
||||
"""通用 API 请求(使用全局凭据;强验证模式下必须有全局 accessToken)"""
|
||||
if is_strict_mode() and not has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||
return _strict_reject()
|
||||
url = f"{BASE_URL}{path}"
|
||||
ts = str(int(time.time()))
|
||||
token_id = HEADERS["hsf-x-tokenid"]
|
||||
headers = get_headers(ts)
|
||||
headers["hsf-x-signature"] = make_signature(
|
||||
_GLOBAL_ACCESS_TOKEN, method, path, ts, token_id,
|
||||
params if method.upper() == "GET" else data)
|
||||
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = requests.get(url, params=params, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
else:
|
||||
resp = requests.post(url, json=data, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
content = resp.content
|
||||
if resp.headers.get("Content-Encoding") == "gzip" or content[:2] == b'\x1f\x8b':
|
||||
try:
|
||||
content = gzip.decompress(content)
|
||||
except Exception:
|
||||
pass
|
||||
return _normalize_token_invalid(json.loads(content), "global")
|
||||
except Exception as e:
|
||||
return {"error": str(e), "rtn_code": -1}
|
||||
|
||||
|
||||
def request_with_user_auth(user_id: int, method: str, path: str,
|
||||
params: dict = None, data: dict = None,
|
||||
_silent: bool = False) -> dict:
|
||||
"""使用用户凭据(token_id 必填 + access_token 选填)发起 API 请求"""
|
||||
from db import get_user_auth
|
||||
token_id, access_token = get_user_auth(user_id)
|
||||
if not token_id:
|
||||
return {"rtn_code": 401, "message": "用户未配置 Token ID"}
|
||||
if is_strict_mode() and not has_real_access_token(access_token):
|
||||
return _strict_reject()
|
||||
|
||||
ts = str(int(time.time()))
|
||||
headers = dict(HEADERS)
|
||||
headers["hsf-x-timestamp"] = ts
|
||||
headers["hsf-x-tokenid"] = token_id
|
||||
headers["hsf-x-signature"] = make_signature(
|
||||
access_token, method, path, ts, token_id,
|
||||
params if method.upper() == "GET" else data)
|
||||
|
||||
url = f"{BASE_URL}{path}"
|
||||
|
||||
if not _silent:
|
||||
from db import get_db
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
user_email = row["email"] if row else None
|
||||
print(f"[request_with_user_auth] user={user_email}, url={url}")
|
||||
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = requests.get(url, params=params, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
else:
|
||||
resp = requests.request(method, url, params=params, json=data,
|
||||
headers=headers, timeout=10, verify=True)
|
||||
if not _silent:
|
||||
print(f"[request_with_user_auth] response status={resp.status_code}, "
|
||||
f"body={resp.text[:200]}")
|
||||
return _normalize_token_invalid(resp.json(), "user")
|
||||
except Exception as e:
|
||||
if not _silent:
|
||||
print(f"[request_with_user_auth] request error: {e}")
|
||||
return {"rtn_code": -1, "error": str(e)}
|
||||
|
||||
|
||||
def get_token_config():
|
||||
"""获取当前全局凭据"""
|
||||
return {
|
||||
"token_id": HEADERS.get("hsf-x-tokenid", ""),
|
||||
"access_token": _GLOBAL_ACCESS_TOKEN,
|
||||
"has_access_token": has_real_access_token(_GLOBAL_ACCESS_TOKEN),
|
||||
}
|
||||
|
||||
|
||||
def save_token_config(token_id: str, access_token: str):
|
||||
"""保存全局凭据到文件并更新内存"""
|
||||
global _GLOBAL_ACCESS_TOKEN
|
||||
try:
|
||||
cfg = {
|
||||
"token_id": token_id or "",
|
||||
"access_token": access_token or "",
|
||||
}
|
||||
_TOKEN_CONFIG_PATH.write_text(
|
||||
"# 全局微信凭据\n"
|
||||
"# token_id: 登录后服务端下发的会话标识(重新登录小程序会失效,单会话策略)\n"
|
||||
"# access_token: 登录响应中的 accessToken(JWT,30天有效),用于实时计算签名;留空则发占位签名\n"
|
||||
f"token_id={cfg['token_id']}\n"
|
||||
f"access_token={cfg['access_token']}\n",
|
||||
encoding="utf-8")
|
||||
HEADERS["hsf-x-tokenid"] = cfg["token_id"]
|
||||
_GLOBAL_ACCESS_TOKEN = cfg["access_token"]
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[token配置] 保存失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# 上游错误文案 → 用户可读文案
|
||||
# 上游返回的 message 经常是英文原始错误(如 "non")或内部术语,直接透传
|
||||
# 用户看不懂。这里做统一映射;匹配不到时原样返回(上游文案本身可读时
|
||||
# 保持原样最安全)。所有面向用户的出口建议走这个函数。
|
||||
# =====================================================================
|
||||
|
||||
_UPSTREAM_MESSAGE_MAP = (
|
||||
# (命中关键词列表, 展示文案, 类别) 类别: occupied=车辆被占用 / unpaid=未支付
|
||||
# 认证/凭据
|
||||
(("token", "登录"), "登录状态已过期,请重新登录并更新凭据", "auth"),
|
||||
(("signature", "签名"), "请求签名校验失败,请重新登录小程序并更新 AccessToken", "auth"),
|
||||
# 车辆状态
|
||||
(("使用中", "骑行中"), "这辆车正在被别人骑行,换一辆试试", "occupied"),
|
||||
(("占用",), "这辆车当前被占用,换一辆试试", "occupied"),
|
||||
(("已被", "锁定"), "这辆车已被锁定或预约,换一辆试试", "occupied"),
|
||||
# 订单/支付
|
||||
(("未支付", "待支付"), "你有一笔未支付的订单,请先支付后再用车", "unpaid"),
|
||||
(("余额", "欠费"), "账户余额不足,请先充值", "unpaid"),
|
||||
# 业务拒绝
|
||||
(("超出", "范围"), "当前位置不在服务区内,请到规定的还车点操作", "deny"),
|
||||
(("频繁", "稍后再试"), "操作太频繁了,请稍等几秒再试", "deny"),
|
||||
)
|
||||
|
||||
# 保留关键词:内部逻辑(自动开锁避让重试等)需要按类别分支,调用方仍可拿到
|
||||
UPSTREAM_MSG_CATEGORY_KEYWORDS = {
|
||||
"occupied": ("使用中", "占用", "已被", "骑行", "锁定"),
|
||||
"unpaid": ("未支付", "待支付", "non"),
|
||||
}
|
||||
|
||||
|
||||
def upstream_msg_category(message) -> str:
|
||||
"""上游 message 的机器可读类别(occupied/unpaid/auth/deny/'')。"""
|
||||
msg = str(message or "").lower()
|
||||
for keys, _, cat in _UPSTREAM_MESSAGE_MAP:
|
||||
if any(k in msg for k in keys):
|
||||
return cat
|
||||
return ""
|
||||
|
||||
|
||||
def friendly_upstream_message(message, fallback="操作失败,请稍后重试"):
|
||||
"""把上游 message 翻译成用户可读文案;映射不到原样返回(无 fallback)。"""
|
||||
msg = str(message or "")
|
||||
if not msg.strip():
|
||||
return fallback
|
||||
for keys, text, _ in _UPSTREAM_MESSAGE_MAP:
|
||||
if any(k in msg for k in keys):
|
||||
return text
|
||||
return msg
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""微信API通信模块
|
||||
|
||||
凭据模型(对照 98/ 反编译小程序与实机抓包还原):
|
||||
- token_id:登录后服务端下发的会话标识。上游目前唯一强校验的头,必填。
|
||||
- access_token:登录响应里的 JWT,有效期 30 天。小程序用它在本地实时计算签名:
|
||||
hsf-x-signature = sha1(access_token + base64(签名串))。选填。
|
||||
- 有效期到之前系统会发提醒邮件(1 天 / 1 小时 / 已过期),到期后到个人中心更新凭据即可。
|
||||
不要再写「打开小程序就会让网页凭据失效」这类说法——它不是事实,只会让用户不敢用官方小程序。
|
||||
|
||||
签名策略(双模式 + 强验证开关):
|
||||
- 常规模式:有真实 access_token 就实时计算签名;否则生成形似合法的
|
||||
sha1 伪装签名(40 位 hex、随请求变化,防上游日志识别出固定异常值)。
|
||||
- 强验证模式(管理端开关,server_config.json 持久化):模拟上游开启
|
||||
签名校验后的行为——没有真实 access_token 的凭据直接拒绝发起请求,
|
||||
提前给出明确错误,而不是发出必然失败的请求。
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import requests
|
||||
import gzip
|
||||
from pathlib import Path
|
||||
|
||||
# 旧占位签名值(仅用于识别"未配置 accessToken"的存量配置,不再对外发送)
|
||||
_DUMMY_SIGNATURE = "xiaobai"
|
||||
|
||||
|
||||
def fake_signature(timestamp: str, token_id: str) -> str:
|
||||
"""未配置 accessToken 时生成形似合法的签名:40 位小写 hex(sha1 输出格式),
|
||||
且随时间戳/凭据变化,与真实流量的日志特征一致,避免上游从日志中识别出异常固定值。"""
|
||||
return hashlib.sha1(f"{timestamp}{token_id}".encode("utf-8")).hexdigest()
|
||||
|
||||
BASE_URL = "https://bike.sdlongren.com"
|
||||
|
||||
# 强验证开关的持久化文件
|
||||
_SERVER_CONFIG_PATH = Path(__file__).parent / "server_config.json"
|
||||
|
||||
# 从配置文件加载全局凭据
|
||||
_TOKEN_CONFIG_PATH = Path(__file__).parent / "token_config.txt"
|
||||
|
||||
|
||||
# ========== 强验证开关 ==========
|
||||
def _load_server_config() -> dict:
|
||||
try:
|
||||
if _SERVER_CONFIG_PATH.exists():
|
||||
return json.loads(_SERVER_CONFIG_PATH.read_text("utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def is_strict_mode() -> bool:
|
||||
"""上游强签名验证开关:开启后无真实 accessToken 的凭据将被拒绝发起请求"""
|
||||
return bool(_load_server_config().get("require_access_token"))
|
||||
|
||||
|
||||
def set_strict_mode(enabled: bool) -> bool:
|
||||
try:
|
||||
cfg = _load_server_config()
|
||||
cfg["require_access_token"] = bool(enabled)
|
||||
_SERVER_CONFIG_PATH.write_text(json.dumps(cfg, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[强验证开关] 保存失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def has_real_access_token(access_token) -> bool:
|
||||
"""是否为可用于计算签名的真实 accessToken(排除空值与占位符)"""
|
||||
return bool(access_token) and access_token != _DUMMY_SIGNATURE
|
||||
|
||||
|
||||
def parse_access_token_expiry(access_token) -> dict:
|
||||
"""从 accessToken(JWT)解析登录态有效期。
|
||||
|
||||
小程序登录响应中的 accessToken 是 RS256 JWT,payload 里带标准
|
||||
iat / nbf / exp(实测有效期 30 天)。只解码不验签——我们只需要
|
||||
展示大致过期时间,签名校验由上游负责。
|
||||
返回:{"parseable": bool, "expire_at": ts|None, "expire_time": "YYYY-MM-DD HH:MM"|None,
|
||||
"remaining_seconds": int|None, "source": "exp"|"iat+30d"|None, "reason": str}
|
||||
"""
|
||||
import base64 as _b64
|
||||
import datetime as _dt
|
||||
import json as _json
|
||||
|
||||
token = (access_token or "").strip()
|
||||
tz = _dt.timezone(_dt.timedelta(hours=8))
|
||||
result = {"parseable": False, "expire_at": None, "expire_time": None,
|
||||
"remaining_seconds": None, "source": None, "reason": ""}
|
||||
|
||||
def _fmt(ts: int) -> str:
|
||||
return _dt.datetime.fromtimestamp(ts, tz).strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
if not has_real_access_token(token):
|
||||
result["reason"] = "未填写 AccessToken"
|
||||
return result
|
||||
parts = token.split(".")
|
||||
if len(parts) != 3 or not token.startswith("ey"):
|
||||
result["reason"] = "不是标准 JWT 格式,无法解析过期时间"
|
||||
return result
|
||||
try:
|
||||
pad = parts[1] + "=" * (-len(parts[1]) % 4)
|
||||
payload = _json.loads(_b64.urlsafe_b64decode(pad))
|
||||
except Exception:
|
||||
result["reason"] = "JWT payload 解码失败"
|
||||
return result
|
||||
|
||||
exp = payload.get("exp") if isinstance(payload, dict) else None
|
||||
iat = payload.get("iat") if isinstance(payload, dict) else None
|
||||
try:
|
||||
exp = int(exp) if exp is not None else None
|
||||
iat = int(iat) if iat is not None else None
|
||||
except (TypeError, ValueError):
|
||||
exp = iat = None
|
||||
|
||||
if exp:
|
||||
result.update(parseable=True, expire_at=exp, expire_time=_fmt(exp),
|
||||
source="exp")
|
||||
elif iat:
|
||||
expire = iat + 30 * 86400 # 实测 accessToken 有效期 30 天
|
||||
result.update(parseable=True, expire_at=expire, expire_time=_fmt(expire),
|
||||
source="iat+30d")
|
||||
else:
|
||||
result["reason"] = "JWT 中没有 exp/iat 字段,无法推算有效期"
|
||||
return result
|
||||
|
||||
result["remaining_seconds"] = int(result["expire_at"] - _dt.datetime.now(tz).timestamp())
|
||||
return result
|
||||
|
||||
|
||||
def _strict_reject() -> dict:
|
||||
return {"rtn_code": 403,
|
||||
"message": "已开启上游强签名验证:请先填写 AccessToken(从微信小程序登录响应中获取)"}
|
||||
|
||||
|
||||
def _load_token_config():
|
||||
"""从 token_config.txt 加载全局凭据。
|
||||
|
||||
token_id:必填(重新登录小程序会失效,单会话策略)。
|
||||
access_token(旧键名 wx_signature 兼容读取):选填,用于实时计算签名。
|
||||
"""
|
||||
config = {"token_id": "", "access_token": ""}
|
||||
try:
|
||||
if _TOKEN_CONFIG_PATH.exists():
|
||||
for line in _TOKEN_CONFIG_PATH.read_text("utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
k, v = line.split("=", 1)
|
||||
k = k.strip()
|
||||
if k == "wx_signature": # 旧配置键名兼容
|
||||
k = "access_token"
|
||||
config[k] = v.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return config
|
||||
|
||||
|
||||
_TOKEN_CONFIG = _load_token_config()
|
||||
_GLOBAL_TOKEN_ID = _TOKEN_CONFIG.get("token_id", "")
|
||||
_GLOBAL_ACCESS_TOKEN = _TOKEN_CONFIG.get("access_token", "")
|
||||
|
||||
# 全局凭据只来自 token_config.txt / 管理后台保存,代码中不硬编码
|
||||
if not _GLOBAL_TOKEN_ID:
|
||||
print("[全局凭据] 警告: token_config.txt 中未配置 token_id,"
|
||||
"地图采集等全局请求将无法通过上游校验,请在管理后台填写")
|
||||
|
||||
HEADERS = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"hsf-x-signature": "",
|
||||
"hsf-x-timestamp": "",
|
||||
"hsf-x-tokenid": _GLOBAL_TOKEN_ID,
|
||||
"xweb_xhr": "1",
|
||||
"platform": "xiaobai",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 MicroMessenger/7.0",
|
||||
"content-type": "application/json",
|
||||
"accept": "*/*",
|
||||
"accept-language": "*",
|
||||
"sec-fetch-site": "cross-site",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-dest": "empty",
|
||||
"referer": "https://servicewechat.com/wx10426ca961518f43/108/page-frame.html",
|
||||
}
|
||||
|
||||
SEARCH_BIKE_URL = "https://bike.sdlongren.com/project/search_bicycle"
|
||||
SEARCH_HEADERS = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "*/*",
|
||||
}
|
||||
|
||||
|
||||
def build_sign_string(method: str, path: str, timestamp: str, token_id: str,
|
||||
params: dict = None) -> str:
|
||||
"""还原小程序 c(method, path, ts, params, needToken) 的签名串"""
|
||||
s = f"{method.upper()}$Hsf-X-Timestamp:{timestamp}Hsf-X-TokenId:{token_id}${path}"
|
||||
if params:
|
||||
s += "?"
|
||||
for k in sorted(params.keys()):
|
||||
v = params[k]
|
||||
# 与小程序一致:空字符串值只拼 key,嵌套对象/数组跳过
|
||||
if not k or (isinstance(v, str) and v == ""):
|
||||
s += f"{k}&"
|
||||
elif isinstance(v, (dict, list)):
|
||||
continue
|
||||
else:
|
||||
s += f"{k}={v}&"
|
||||
s = s.rstrip("&")
|
||||
return s
|
||||
|
||||
|
||||
def compute_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||
token_id: str, params: dict = None) -> str:
|
||||
"""小程序算法:sha1(accessToken + base64(sign_str))"""
|
||||
sign_str = build_sign_string(method, path, timestamp, token_id, params)
|
||||
b64 = base64.b64encode(sign_str.encode("utf-8")).decode("ascii")
|
||||
return hashlib.sha1(f"{access_token}{b64}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def make_signature(access_token: str, method: str, path: str, timestamp: str,
|
||||
token_id: str, params: dict = None) -> str:
|
||||
"""有真实 accessToken 就按小程序算法实时签名;
|
||||
没有则生成形似合法的 sha1 签名(40 位 hex、随请求变化),防上游日志识别。"""
|
||||
if has_real_access_token(access_token):
|
||||
return compute_signature(access_token, method, path, timestamp,
|
||||
token_id, params)
|
||||
return fake_signature(timestamp, token_id)
|
||||
|
||||
|
||||
def get_headers(timestamp: str = None) -> dict:
|
||||
"""生成带时间戳的请求头"""
|
||||
ts = timestamp or str(int(time.time()))
|
||||
headers = HEADERS.copy()
|
||||
headers["hsf-x-timestamp"] = ts
|
||||
return headers
|
||||
|
||||
|
||||
def get_signature_headers(timestamp: str = None) -> dict:
|
||||
"""车辆查询接口(/project/search_bicycle)用的简化签名头。
|
||||
有全局 accessToken 时按小程序算法计算(针对该路径);否则生成
|
||||
sha1(时间戳+token_id) 占位值(上游目前不校验)。"""
|
||||
ts = timestamp or str(int(time.time()))
|
||||
token_id = HEADERS.get("hsf-x-tokenid", "")
|
||||
if has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||
sig = compute_signature(_GLOBAL_ACCESS_TOKEN, "POST", "/project/search_bicycle",
|
||||
ts, token_id)
|
||||
else:
|
||||
sig = fake_signature(ts, token_id)
|
||||
return {
|
||||
"hsf-x-timestamp": ts,
|
||||
"hsf-x-tokenid": token_id,
|
||||
"hsf-x-signature": sig,
|
||||
"platform": "xiaobai",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_token_invalid(result: dict, scope: str):
|
||||
"""上游返回 102001(token_id 失效,通常是小程序重新登录把旧会话踢掉)时
|
||||
统一改写响应:scope='user' 面向用户提示重新配置;scope='global' 面向管理员。
|
||||
注意 global 文案刻意不含 Token 字样,避免前端误弹用户级凭据弹窗。"""
|
||||
if isinstance(result, dict) and result.get("rtn_code") == 102001:
|
||||
result["token_invalid"] = True
|
||||
if scope == "user":
|
||||
result["message"] = ("微信凭据需要更新(上游判定已失效/已过期),"
|
||||
"请到个人中心重新获取并保存凭据")
|
||||
else:
|
||||
result["message"] = "地图数据暂不可用:服务器全局凭据已失效,请联系管理员更新"
|
||||
return result
|
||||
|
||||
|
||||
def request_api(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
||||
"""Share global map reads across users, collection jobs and worker processes."""
|
||||
if method.upper() == "GET" and path == "/project/map":
|
||||
from map_cache import shared_map_cache
|
||||
bike_type = str((params or {}).get("type", "1")).strip()
|
||||
return shared_map_cache.get(bike_type, lambda: _request_api_uncached(
|
||||
method, path, params={**(params or {}), "type": bike_type}, data=data))
|
||||
return _request_api_uncached(method, path, params=params, data=data)
|
||||
|
||||
|
||||
def _request_api_uncached(method: str, path: str, params: dict = None, data: dict = None) -> dict:
|
||||
"""通用 API 请求(使用全局凭据;强验证模式下必须有全局 accessToken)"""
|
||||
if is_strict_mode() and not has_real_access_token(_GLOBAL_ACCESS_TOKEN):
|
||||
return _strict_reject()
|
||||
url = f"{BASE_URL}{path}"
|
||||
ts = str(int(time.time()))
|
||||
token_id = HEADERS["hsf-x-tokenid"]
|
||||
headers = get_headers(ts)
|
||||
headers["hsf-x-signature"] = make_signature(
|
||||
_GLOBAL_ACCESS_TOKEN, method, path, ts, token_id,
|
||||
params if method.upper() == "GET" else data)
|
||||
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = requests.get(url, params=params, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
else:
|
||||
resp = requests.post(url, json=data, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
content = resp.content
|
||||
if resp.headers.get("Content-Encoding") == "gzip" or content[:2] == b'\x1f\x8b':
|
||||
try:
|
||||
content = gzip.decompress(content)
|
||||
except Exception:
|
||||
pass
|
||||
return _normalize_token_invalid(json.loads(content), "global")
|
||||
except Exception as e:
|
||||
return {"error": str(e), "rtn_code": -1}
|
||||
|
||||
|
||||
def request_with_user_auth(user_id: int, method: str, path: str,
|
||||
params: dict = None, data: dict = None,
|
||||
_silent: bool = False) -> dict:
|
||||
"""使用用户凭据(token_id 必填 + access_token 选填)发起 API 请求"""
|
||||
from db import get_user_auth
|
||||
token_id, access_token = get_user_auth(user_id)
|
||||
if not token_id:
|
||||
return {"rtn_code": 401, "message": "用户未配置 Token ID"}
|
||||
if is_strict_mode() and not has_real_access_token(access_token):
|
||||
return _strict_reject()
|
||||
|
||||
ts = str(int(time.time()))
|
||||
headers = dict(HEADERS)
|
||||
headers["hsf-x-timestamp"] = ts
|
||||
headers["hsf-x-tokenid"] = token_id
|
||||
headers["hsf-x-signature"] = make_signature(
|
||||
access_token, method, path, ts, token_id,
|
||||
params if method.upper() == "GET" else data)
|
||||
|
||||
url = f"{BASE_URL}{path}"
|
||||
|
||||
if not _silent:
|
||||
from db import get_db
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
user_email = row["email"] if row else None
|
||||
print(f"[request_with_user_auth] user={user_email}, url={url}")
|
||||
|
||||
try:
|
||||
if method.upper() == "GET":
|
||||
resp = requests.get(url, params=params, headers=headers,
|
||||
timeout=10, verify=True)
|
||||
else:
|
||||
resp = requests.request(method, url, params=params, json=data,
|
||||
headers=headers, timeout=10, verify=True)
|
||||
if not _silent:
|
||||
print(f"[request_with_user_auth] response status={resp.status_code}, "
|
||||
f"body={resp.text[:200]}")
|
||||
return _normalize_token_invalid(resp.json(), "user")
|
||||
except Exception as e:
|
||||
if not _silent:
|
||||
print(f"[request_with_user_auth] request error: {e}")
|
||||
return {"rtn_code": -1, "error": str(e)}
|
||||
|
||||
|
||||
def get_token_config():
|
||||
"""获取当前全局凭据"""
|
||||
return {
|
||||
"token_id": HEADERS.get("hsf-x-tokenid", ""),
|
||||
"access_token": _GLOBAL_ACCESS_TOKEN,
|
||||
"has_access_token": has_real_access_token(_GLOBAL_ACCESS_TOKEN),
|
||||
}
|
||||
|
||||
|
||||
def save_token_config(token_id: str, access_token: str):
|
||||
"""保存全局凭据到文件并更新内存"""
|
||||
global _GLOBAL_ACCESS_TOKEN
|
||||
try:
|
||||
cfg = {
|
||||
"token_id": token_id or "",
|
||||
"access_token": access_token or "",
|
||||
}
|
||||
_TOKEN_CONFIG_PATH.write_text(
|
||||
"# 全局微信凭据\n"
|
||||
"# token_id: 登录后服务端下发的会话标识(重新登录小程序会失效,单会话策略)\n"
|
||||
"# access_token: 登录响应中的 accessToken(JWT,30天有效),用于实时计算签名;留空则发占位签名\n"
|
||||
f"token_id={cfg['token_id']}\n"
|
||||
f"access_token={cfg['access_token']}\n",
|
||||
encoding="utf-8")
|
||||
HEADERS["hsf-x-tokenid"] = cfg["token_id"]
|
||||
_GLOBAL_ACCESS_TOKEN = cfg["access_token"]
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[token配置] 保存失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# 上游错误文案 → 用户可读文案
|
||||
# 上游返回的 message 经常是英文原始错误(如 "non")或内部术语,直接透传
|
||||
# 用户看不懂。这里做统一映射;匹配不到时原样返回(上游文案本身可读时
|
||||
# 保持原样最安全)。所有面向用户的出口建议走这个函数。
|
||||
# =====================================================================
|
||||
|
||||
_UPSTREAM_MESSAGE_MAP = (
|
||||
# (命中关键词列表, 展示文案, 类别) 类别: occupied=车辆被占用 / unpaid=未支付
|
||||
# 认证/凭据
|
||||
(("token", "登录"), "登录状态已过期,请重新登录并更新凭据", "auth"),
|
||||
(("signature", "签名"), "请求签名校验失败,请重新登录小程序并更新 AccessToken", "auth"),
|
||||
# 车辆状态
|
||||
(("使用中", "骑行中"), "这辆车正在被别人骑行,换一辆试试", "occupied"),
|
||||
(("占用",), "这辆车当前被占用,换一辆试试", "occupied"),
|
||||
(("已被", "锁定"), "这辆车已损坏或被锁定,换一辆试试", "occupied"),
|
||||
# 订单/支付
|
||||
(("未支付", "待支付"), "你有一笔未支付的订单,请先支付后再用车", "unpaid"),
|
||||
(("余额", "欠费"), "账户余额不足,请先充值", "unpaid"),
|
||||
# 业务拒绝
|
||||
(("超出", "范围"), "当前位置不在服务区内,请到规定的还车点操作", "deny"),
|
||||
(("频繁", "稍后再试"), "操作太频繁了,请稍等几秒再试", "deny"),
|
||||
)
|
||||
|
||||
# 保留关键词:内部逻辑(自动开锁避让重试等)需要按类别分支,调用方仍可拿到
|
||||
UPSTREAM_MSG_CATEGORY_KEYWORDS = {
|
||||
"occupied": ("使用中", "占用", "已被", "骑行", "锁定"),
|
||||
"unpaid": ("未支付", "待支付", "non"),
|
||||
}
|
||||
|
||||
|
||||
def upstream_msg_category(message) -> str:
|
||||
"""上游 message 的机器可读类别(occupied/unpaid/auth/deny/'')。"""
|
||||
msg = str(message or "").lower()
|
||||
for keys, _, cat in _UPSTREAM_MESSAGE_MAP:
|
||||
if any(k in msg for k in keys):
|
||||
return cat
|
||||
return ""
|
||||
|
||||
|
||||
def friendly_upstream_message(message, fallback="操作失败,请稍后重试"):
|
||||
"""把上游 message 翻译成用户可读文案;映射不到原样返回(无 fallback)。"""
|
||||
msg = str(message or "")
|
||||
if not msg.strip():
|
||||
return fallback
|
||||
for keys, text, _ in _UPSTREAM_MESSAGE_MAP:
|
||||
if any(k in msg for k in keys):
|
||||
return text
|
||||
return msg
|
||||
|
||||
Reference in New Issue
Block a user