Files
xbcr/routes/map_api.py
T
zzy be016621c0 fix(批次E): 可信代理、地图快照失败不空白、SSE 硬超时、bike_history 去重
- routes/auth._client_ip:可信代理前缀可配(默认 127./::1/172./10./192.168.),
  容器/Docker 部署下所有客户端不再塌成同一个限流 key(原来 45 次/分钟
  变成全站共享,一两个人就能把所有人打成 429)
- map_cache:采集失败**不再覆盖上一份好数据**,只放租约并把过期时间后推一个窗口
  (一次抖动不该让全站地图空白 60 秒);同时去掉 published=False 时的同名递归
  (deadline 每次重置 → 竞争下无界重试)。从来没过好数据时才写错误 payload,
  保证窗口内返回值稳定
- /api/ring_progress SSE 加 180 秒硬超时(同步长连接占死 worker,-w 4 时
  4 个进度页即可打满站点)
- bike_history:迁移去重 + (bike_code, recorded_at) 唯一索引,采集改 INSERT OR IGNORE
  (多进程各写一份会让行数 ×N,污染 /api/history 统计)
- 测试同步更新:地图快照失败语义改为「保留上一份好数据」

测试:167 pytest + 32 node 全绿
2026-11-15 23:51:51 +08:00

494 lines
19 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""地图数据、寻车、分析等路由"""
import json
import time
import uuid
import hashlib
import threading
import asyncio
import aiohttp
from pathlib import Path
from flask import Blueprint, current_app, jsonify, request, render_template
from db import get_db, get_user_display_name, get_user_auth
from routes.auth import get_current_user
from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS
bp = Blueprint("map_api", __name__)
# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放
BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
# 并行寻车任务
ring_tasks: dict = {}
_ring_lock = threading.Lock()
async def ring_single_bike_async(session, bike_code, school_id=10):
try:
headers = {**SEARCH_HEADERS, **get_signature_headers()}
async with session.post(
SEARCH_BIKE_URL,
json={"code": bike_code, "school_id": school_id},
headers=headers,
timeout=aiohttp.ClientTimeout(total=5)
) as resp:
data = await resp.json()
return data.get("rtn_code") == 0 or data.get("success") is True
except Exception:
return False
def run_ring_task(task_id: str):
global ring_tasks
task = ring_tasks.get(task_id)
if not task:
return
bikes = task["bikes"]
total = len(bikes)
task["total"] = total
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop)
try:
async def run_session():
semaphore = asyncio.Semaphore(20)
async with aiohttp.ClientSession(connector=connector) as session:
async def ring_one(idx, code):
async with semaphore:
if task["cancelled"]:
return False
result = await ring_single_bike_async(session, code, 10)
with _ring_lock:
task["done"] += 1
if result:
task["success"] += 1
else:
task["failed"] += 1
task["last_update"] = time.time()
return result
batch_size = 20
for i in range(0, len(bikes), batch_size):
if task["cancelled"]:
break
batch = bikes[i:i + batch_size]
await asyncio.gather(
*[ring_one(i + j, b["code"]) for j, b in enumerate(batch)],
return_exceptions=True
)
await asyncio.sleep(0.1)
loop.run_until_complete(run_session())
finally:
with _ring_lock:
task["status"] = "completed" if not task["cancelled"] else "cancelled"
task["done"] = total
loop.close()
@bp.route("/api/ring_all", methods=["POST"])
def api_ring_all():
global ring_tasks
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"})
if user["email"] not in BATCH_RING_ALLOWED_EMAILS:
return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"})
data = request.get_json() or {}
codes = data.get("codes", [])
if isinstance(codes, str):
codes = [codes]
if not codes:
return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"})
user_name = get_user_display_name(user["id"])
print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}")
task_id = str(uuid.uuid4())[:8]
task = {
"status": "running", "total": len(codes), "done": 0,
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
}
with _ring_lock:
ring_tasks[task_id] = task
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
t.start()
return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes),
"message": f"任务已启动,共 {len(codes)} 辆车"})
@bp.route("/api/ring_status/<task_id>")
def api_ring_status(task_id):
with _ring_lock:
task = ring_tasks.get(task_id)
if not task:
return jsonify({"rtn_code": 404, "message": "任务不存在"})
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
"done": task["done"], "success": task["success"], "failed": task["failed"]})
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
def api_ring_cancel(task_id):
with _ring_lock:
task = ring_tasks.get(task_id)
if not task:
return jsonify({"rtn_code": 404, "message": "任务不存在"})
if task["status"] != "running":
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
task["cancelled"] = True
task["status"] = "cancelling"
return jsonify({"rtn_code": 0, "message": "取消请求已发送"})
@bp.route("/api/ring_progress/<task_id>")
def api_ring_progress(task_id):
from flask import Response as FlaskResponse
global ring_tasks
RING_SSE_MAX_SECONDS = 180 # 单个进度 SSE 最长占用时间
def _sse(obj):
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
def generate():
last_done = -1
last_status = None
tick = 0
# 硬超时:SSE 是同步长连接,一个连接占死一个 worker。任务卡住时
# 不设上限的话(-w 4 只要 4 个进度页)整站会被打满。
deadline = time.time() + RING_SSE_MAX_SECONDS
while True:
if time.time() > deadline:
yield _sse({"type": "error", "message": "进度推送超时,请刷新页面查看结果"})
return
with _ring_lock:
task = ring_tasks.get(task_id)
if not task:
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
yield _sse({"type": "error", "message": "任务不存在或已结束"})
return
done = task["done"]
status = task["status"]
if done != last_done or status != last_status:
last_done = done
last_status = status
yield _sse({
"type": "progress",
"status": status,
"done": done,
"total": task["total"],
"success": task["success"],
"failed": task["failed"],
})
if status in ("completed", "cancelled"):
# 已结束,补发一条 done 事件后关闭
yield _sse({"type": "done", "status": status})
return
tick += 1
if tick >= 20: # 约 10s 一次心跳,避免代理/连接超时被判定为断开
tick = 0
yield ": ping\n\n"
time.sleep(0.5)
return FlaskResponse(
generate(),
mimetype="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
def api_ring_status_clear(task_id):
with _ring_lock:
ring_tasks.pop(task_id, None)
return jsonify({"rtn_code": 0, "message": "已清除"})
@bp.route("/api/map")
def api_map():
# 非登录人员不能使用:地图数据需登录后查看
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
bike_type = request.args.get("type", "1").strip()
from map_cache import MAP_TYPES
if bike_type not in MAP_TYPES:
return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400
result = request_api("GET", "/project/map", params={"type": bike_type})
# 上游错误文案统一翻译(成功响应原样透传)
if result.get("rtn_code") not in (None, 0):
from wechat import friendly_upstream_message
result = {**result,
"message": friendly_upstream_message(result.get("message", ""))}
response = jsonify(result)
# Only the server snapshot is cached; browsers must ask the server on refresh.
response.headers["Cache-Control"] = "private, no-store"
response.headers["Vary"] = "Authorization"
response.headers["X-Map-Server-Time"] = str(time.time())
return response
@bp.route("/api/bicycle", methods=["GET", "POST"])
def api_bicycle():
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
data = request.get_json() or {}
code = data.get("code", "")
if not code:
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
user_name = get_user_display_name(user["id"])
print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}")
result = request_api("POST", "/project/bicycle", data={"code": code})
if result.get("rtn_code") not in (None, 0):
from wechat import friendly_upstream_message
result = {**result,
"message": friendly_upstream_message(result.get("message", ""))}
return jsonify(result)
@bp.route("/api/find_bike", methods=["POST"])
def api_find_bike():
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
data = request.get_json() or {}
keyword = (data.get("keyword") or data.get("code") or "").strip()
if not keyword:
return jsonify({"rtn_code": 400, "message": "缺少关键字"})
school_id = data.get("school_id", 10)
result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id})
if result.get("rtn_code") not in (None, 0):
from wechat import friendly_upstream_message
result = {**result,
"message": friendly_upstream_message(result.get("message", ""))}
return jsonify(result)
@bp.route("/api/config")
def api_config():
return jsonify({
"center_lat": 36.531820, "center_lng": 116.780180,
"scale": 17, "school_name": "山东管理学院",
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
})
@bp.route("/api/nav_route")
def api_nav_route():
"""导航路线:距离/耗时/分段指引/整条折线(前端直接画到地图上)。
参数:origin_lat/origin_lng/dest_lat/dest_lng(GCJ02),mode=walking|riding
返回:{rtn_code:0, data:{distance, duration, points:[[lng,lat],...], steps:[...]}}
"""
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
from routes.auth import _client_ip
from rate_limit import hit as rl_hit
# 导航比查卡片更重,按 IP 每分钟 20 次
if not rl_hit(("nav_route", _client_ip()), 20, 60):
return jsonify({"rtn_code": 429, "message": "导航请求过于频繁,请稍后再试"}), 429
try:
o_lat = float(request.args.get("origin_lat"))
o_lng = float(request.args.get("origin_lng"))
d_lat = float(request.args.get("dest_lat"))
d_lng = float(request.args.get("dest_lng"))
except (TypeError, ValueError):
return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"})
mode = (request.args.get("mode") or "walking").strip().lower()
if mode not in ("walking", "riding"):
mode = "walking"
import walk_route
data = walk_route.get_nav_route(o_lat, o_lng, d_lat, d_lng, api=mode)
if data.get("error"):
return jsonify({"rtn_code": 500, "message": data["error"]}), 200
response = jsonify({"rtn_code": 0, "data": data})
response.headers["Cache-Control"] = "private, max-age=30"
return response
@bp.route("/api/walk_route")
def api_walk_route():
"""步行路线:真实道路距离 + 步行耗时(百度轻量级路线规划)。
参数:origin_lat/origin_lng/dest_lat/dest_lng,**全部 GCJ02**
(前端要把 BD09 的我方位置先转 GCJ02 再传)。
返回:{rtn_code:0, data:{distance, duration, source}}
source = baidu(实时)/ cache(命中缓存)/ estimate(百度不可用时的本地估算)
"""
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
from routes.auth import _client_ip
from rate_limit import hit as rl_hit
# 保护百度配额:同一 IP 每分钟 60 次(正常点卡片远低于此)
if not rl_hit(("walk_route", _client_ip()), 60, 60):
return jsonify({"rtn_code": 429, "message": "请求过于频繁,请稍后再试"}), 429
try:
o_lat = float(request.args.get("origin_lat"))
o_lng = float(request.args.get("origin_lng"))
d_lat = float(request.args.get("dest_lat"))
d_lng = float(request.args.get("dest_lng"))
except (TypeError, ValueError):
return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"})
import walk_route
data = walk_route.get_walk_route(o_lat, o_lng, d_lat, d_lng)
response = jsonify({"rtn_code": 0, "data": data})
response.headers["Cache-Control"] = "private, max-age=60"
return response
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
@bp.route("/api/map/freshness")
def api_map_freshness():
"""优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。
只读取缓存元数据,不会为了查询时间额外请求上游。
"""
from map_cache import shared_map_cache
snapshot = shared_map_cache.freshness(request.args.get("type", "3"))
if snapshot is not None:
response = jsonify({"rtn_code": 0, "data": snapshot})
response.headers["Cache-Control"] = "no-store"
return response
conn = get_db()
row = conn.execute(
"SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone()
conn.close()
latest = row["latest"] if row else None
if not latest:
return jsonify({"rtn_code": 0, "data": {
"latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}})
import datetime as dt
import sqlite3
# recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源
try:
naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S")
latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
now = dt.datetime.now(latest_dt.tzinfo)
stale = max(0, int((now - latest_dt).total_seconds()))
except (ValueError, TypeError):
return jsonify({"rtn_code": 0, "data": {
"latest": str(latest), "stale_seconds": None,
"interval_hint": "时间格式异常"}})
hint = "白天 5-10 分钟 / 夜间 30-60 分钟"
return jsonify({"rtn_code": 0, "data": {
"latest": str(latest), "stale_seconds": stale, "interval_hint": hint}})
@bp.route("/api/campus/locations")
def campus_locations():
"""校园地点(单点模型)。
- kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」;
- kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。
返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。
"""
from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations
result = []
for loc in load_locations():
item = {
"id": loc["id"],
"name": loc["name"],
"kind": loc.get("kind") or "poi",
"latitude": loc.get("latitude"),
"longitude": loc.get("longitude"),
"radius": loc.get("radius") or (
DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None),
"bd09": None,
}
if loc.get("latitude") is not None and loc.get("longitude") is not None:
bd = gcj02_to_bd09(loc["longitude"], loc["latitude"])
item["bd09"] = {"lat": bd[1], "lng": bd[0]}
result.append(item)
return jsonify({"rtn_code": 0, "data": result})
# ========== 用户信息 API ==========
@bp.route("/api/user/info")
def api_user_info():
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"})
from wechat import request_with_user_auth
token_id, access_token = get_user_auth(user["id"])
if not token_id:
return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"})
result = request_with_user_auth(user["id"], "GET", "/user/info")
if result.get("rtn_code") != 0:
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")})
data = result.get("data", {})
non_deal = data.get("nonDealOrder")
true_name = ""
account = data.get("account", {})
if isinstance(account, str):
try:
account = json.loads(account)
except Exception:
account = {}
true_name = account.get("trueName", "") if isinstance(account, dict) else ""
out_money = data.get("bus_account", {}).get("outMoneyBus", 0)
save_money = data.get("bus_account", {}).get("saveMoneyBus", 0)
return jsonify({
"rtn_code": 0, "has_auth": True,
"data": {
"true_name": true_name, "out_money": out_money,
"save_money": save_money, "has_auth": True,
"nonDealOrder": non_deal,
}
})
# ========== 首页路由 ==========
MAP_ASSETS = (
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
"js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
"js/settings-pages.js", "js/navigation.js", "js/share.js", "js/subscribe.js", "js/map.js",
)
def _map_asset_version():
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
digest = hashlib.sha256()
for filename in MAP_ASSETS:
digest.update(filename.encode())
try:
digest.update((Path(current_app.static_folder) / filename).read_bytes())
except FileNotFoundError:
digest.update(b"missing")
return digest.hexdigest()[:16]
@bp.route("/")
def index():
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
response.headers["Cache-Control"] = "no-cache"
return response
@bp.route("/analysis.html")
def analysis_page():
return render_template("analysis.html")
@bp.route("/ring_progress.html")
def ring_progress():
return render_template("ring_progress.html")