Files
xbcr/routes/map_api.py
T

413 lines
16 KiB
Python

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