feat: improve campus bike discovery and add independent live preview

This commit is contained in:
zzy
2026-11-04 16:42:47 +08:00
parent f986c8deae
commit b6b7b3dbe5
42 changed files with 5267 additions and 4313 deletions
+223
View File
@@ -0,0 +1,223 @@
"""Preview fixtures for the demo account; independent test accounts use real APIs."""
import copy
import datetime as dt
import secrets
import threading
import time
from flask import jsonify, request
DEMO_EMAIL = "demo@preview.local"
DEMO_PASSWORD = "preview123"
_lock = threading.RLock()
_rides = {}
_live_maps = {}
def sample_bikes():
bikes = []
for n in range(28):
code = str(30000193 + n) if n % 5 == 0 else str((50300 if n % 3 == 0 else 51200) + n)
state, status = ((4, 0) if n % 11 == 0 else (2, 0) if n % 13 == 0 else (1, 1) if n % 7 == 0 else (1, 0))
bikes.append({"code": code, "id": code, "state": state, "status": status,
"latitude": 36.53182 + (n // 7 - 1) * .00105,
"longitude": 116.7817 + (n % 7 - 3) * .0008,
"electric_quantity": None if n == 3 else 10 if n == 4 else 25 + (n * 13) % 75})
return bikes
def seed_preview():
from db import get_db
from routes.auth import hash_password
conn = get_db()
if conn.execute("SELECT id FROM users WHERE email=?", (DEMO_EMAIL,)).fetchone():
conn.close()
return
user_id = conn.execute("INSERT INTO users (email, password_hash) VALUES (?, ?)",
(DEMO_EMAIL, hash_password(DEMO_PASSWORD))).lastrowid
peer_id = conn.execute("INSERT INTO users (email, password_hash) VALUES (?, ?)",
("friend@preview.local", hash_password(secrets.token_urlsafe(24)))).lastrowid
places = [("图书馆", "poi", 36.5325, 116.7812), ("第一教学楼", "poi", 36.5319, 116.7824),
("学生食堂", "poi", 36.5308, 116.7801), ("宿舍区停车点", "parking", 36.5330, 116.7820),
("图书馆停车点", "parking", 36.5321, 116.7808)]
for name, kind, lat, lng in places:
conn.execute("INSERT INTO campus_locations (name,kind,latitude,longitude,radius) VALUES (?,?,?,?,150)",
(name, kind, lat, lng))
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).replace(tzinfo=None)
for n in range(68):
start = now - dt.timedelta(hours=n * 3 + 1)
end = start + dt.timedelta(minutes=12 + n % 6)
conn.execute("""INSERT INTO rentals (order_id,bike_code,email,user_id,rider_user_id,start_time,
end_time,returned_at,expired,source,start_label,end_label)
VALUES (?,?,?,?,?,?,?,?,1,'wechat',?,?)""",
(f"DEMO-{n:04}", str(51200 + n % 20), DEMO_EMAIL, user_id,
peer_id if n % 3 == 0 else None, start.strftime("%Y-%m-%d %H:%M:%S"),
end.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
"宿舍区附近", "图书馆附近"))
for n in range(72):
when = (now - dt.timedelta(minutes=n * 10)).strftime("%Y-%m-%d %H:%M:%S")
for bike in sample_bikes():
conn.execute("""INSERT INTO bike_history (bike_code,latitude,longitude,state,status,electric,recorded_at)
VALUES (?,?,?,?,?,?,?)""", (bike["code"], bike["latitude"], bike["longitude"],
bike["state"], bike["status"], bike["electric_quantity"], when))
parking = conn.execute("SELECT id FROM campus_locations WHERE kind='parking' ORDER BY id LIMIT 1").fetchone()[0]
conn.execute("""INSERT INTO subscribe_rules (user_id,location_id,weekday,minute_of_day,notify_enabled,
auto_unlock,enabled,kinds,min_electric,max_electric,sort_by,retry_times,last_run_at,last_run_status,last_run_message)
VALUES (?,?,0,715,1,0,0,'small,big,red',20,100,'distance_asc',3,?,'success',?)""",
(user_id, parking, now.strftime("%Y-%m-%d %H:%M:%S"), "演示:停车点附近有 6 辆符合条件的车辆"))
conn.commit()
conn.close()
def install_preview(app):
app.config["PREVIEW_MODE"] = True
@app.post("/api/preview/session")
def create_test_session():
from db import get_db
from rate_limit import hit
from routes.auth import _client_ip, hash_password
if not hit(("preview_session", _client_ip()), 10, 3600):
return jsonify(rtn_code=429, message="创建测试账号过于频繁,请稍后再试"), 429
conn = get_db()
email = "tester-" + secrets.token_hex(6) + "@preview.local"
uid = conn.execute("INSERT INTO users (email,password_hash) VALUES (?,?)",
(email, hash_password(secrets.token_urlsafe(32)))).lastrowid
token = secrets.token_urlsafe(32)
conn.execute("""INSERT INTO sessions (user_id,token,expires_at,device_name,last_active)
VALUES (?,?,datetime('now','+8 hours','+30 days'),'预览测试浏览器',datetime('now','+8 hours'))""", (uid, token))
conn.commit()
conn.close()
return jsonify(rtn_code=0, data={"token": token, "email": email})
@app.before_request
def preview_requests():
from routes.auth import get_current_user
from db import get_db, get_user_rental_settings
path = request.path
if path == "/api/config":
return jsonify(center_lat=36.531820, center_lng=116.780180, scale=17,
school_name="山东管理学院", type_names={"1": "单车", "3": "电动车", "6": "助力车"}, preview=True)
if not path.startswith("/api/") or path == "/api/preview/session":
return None
user = get_current_user()
if not user:
return None
if user["email"] != DEMO_EMAIL:
# The preview container has no production global token. Use this private
# test account's explicitly supplied WeChat credentials for map queries.
from wechat import request_with_user_auth
if path == "/api/auth/save_token":
with _lock:
for key in [key for key in _live_maps if key[0] == user["id"]]:
_live_maps.pop(key, None)
if path == "/api/map":
bike_type = request.args.get("type", "3")
if bike_type not in ("1", "3", "6"):
return jsonify(rtn_code=400, message="不支持的车辆类型"), 400
key = (user["id"], bike_type)
with _lock:
cached = _live_maps.get(key)
if not cached or cached[0] <= time.time():
now = time.time()
result = request_with_user_auth(user["id"], "GET", "/project/map", params={"type": bike_type})
if result.get("rtn_code") == 401:
result = {**result, "rtn_code": 400, "message": "请先在设置中填写微信凭证,再刷新车辆数据"}
ttl = 60 if result.get("rtn_code") == 0 else 5
result["map_snapshot"] = {"fetched_at": now if result.get("rtn_code") == 0 else None,
"expires_at": now + ttl, "status": "fresh" if result.get("rtn_code") == 0 else "error"}
_live_maps[key] = (now + ttl, result)
if len(_live_maps) > 200:
for expired in [k for k, v in _live_maps.items() if v[0] < now]:
_live_maps.pop(expired, None)
cached = _live_maps[key]
response = jsonify(copy.deepcopy(cached[1]))
response.headers["X-Map-Server-Time"] = str(time.time())
response.headers["Cache-Control"] = "private, no-store"
return response
if path == "/api/bicycle":
return jsonify(request_with_user_auth(user["id"], "POST", "/project/bicycle", data=request.get_json(silent=True) or {}))
if path == "/api/find_bike":
from urllib.parse import urlsplit
from wechat import SEARCH_BIKE_URL
return jsonify(request_with_user_auth(user["id"], "POST", urlsplit(SEARCH_BIKE_URL).path, data=request.get_json(silent=True) or {}))
return None
# Demo operations stay synthetic, even after live testing is enabled.
if path.startswith("/api/subscribe/") or path in ("/api/campus/locations", "/api/auth/status", "/api/auth/logout", "/api/user/orders") or path.startswith("/api/auth/sessions"):
return None
if path == "/api/auth/rental_settings":
if request.method == "POST":
from db import normalize_rental_settings, save_user_rental_settings
try:
settings = normalize_rental_settings(request.get_json(silent=True) or {})
except ValueError as exc:
return jsonify(rtn_code=400, message=str(exc)), 400
save_user_rental_settings(user["id"], settings)
return jsonify(rtn_code=0, data=get_user_rental_settings(user["id"]))
if path == "/api/auth/profile":
return jsonify(rtn_code=0, data={"email": DEMO_EMAIL, "has_auth": True, "token_id": "", "access_token": "", "strict_mode": False,
"rental_settings": get_user_rental_settings(user["id"]), "alert_email": DEMO_EMAIL})
if path in ("/api/auth/user_info", "/api/user/info"):
return jsonify(rtn_code=0, data={"has_auth": True, "true_name": "演示同学", "out_money": 12.5, "save_money": 86.0})
if path == "/api/auth/packages":
return jsonify(rtn_code=0, data={"has_auth": True, "packages": [{"name": "演示骑行月卡", "remain": 12, "remaining": 12, "expire_time": "2026-12-31"}]})
if path.startswith("/api/auth/"):
return jsonify(rtn_code=403, message="演示账号使用模拟数据;请创建独立测试账号后填写真实凭证"), 403
if path == "/api/map":
now = time.time()
response = jsonify(rtn_code=0, data={"bicycleStation": sample_bikes(), "driverArea": [], "parkeArea": []},
map_snapshot={"fetched_at": now, "expires_at": now + 60, "status": "fresh"})
response.headers["X-Map-Server-Time"] = str(now)
response.headers["Cache-Control"] = "private, no-store"
return response
if path == "/api/bicycle":
code = str((request.get_json(silent=True) or {}).get("code", ""))
bike = next((b for b in sample_bikes() if b["code"] == code), None)
return jsonify(rtn_code=0, data=bike) if bike else jsonify(rtn_code=404, message="演示数据中没有这辆车,请从附近列表选择")
if path == "/api/find_bike":
return jsonify(rtn_code=0, message="模拟寻车成功", data={})
token = request.headers.get("Authorization", "")
with _lock:
ride = _rides.get(token)
if path == "/api/order/status":
return jsonify(rtn_code=0, has_credentials=True, has_order=bool(ride), order=ride)
if path == "/api/rental/status":
settings = get_user_rental_settings(user["id"])
end = ride.get("deadline") if ride else time.time()
return jsonify(rtn_code=0, data={"active": bool(ride), "remaining_seconds": max(0, int(end - time.time())),
"current_round": 1, "total_rounds": ride.get("rounds", 1) if ride else 1,
"auto_return": settings["auto_return_enabled"],
"final_end_time": dt.datetime.fromtimestamp(end, dt.timezone(dt.timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S")})
if path == "/api/order/unlock":
if ride:
return jsonify(rtn_code=400, message="请先结束当前演示订单")
data = request.get_json(silent=True) or {}
code = str(data.get("code") or data.get("bike_code") or "51201")
ride = {"order_id": "DEMO-LIVE-" + secrets.token_hex(4), "code": code, "status": 2, "deadline": time.time() + 19 * 60, "rounds": 1}
_rides[token] = ride
return jsonify(rtn_code=0, message="模拟开锁成功", data={**ride, "rental_id": 0, "duration_minutes": 19})
if path == "/api/order/add_round":
if ride:
ride["deadline"] += 19 * 60
ride["rounds"] += 1
return jsonify(rtn_code=0, message="演示订单已追加一轮")
if path in ("/api/order/return", "/api/rental/return", "/api/share/return"):
_rides.pop(token, None)
return jsonify(rtn_code=0, message="模拟还车成功", data={"returned": True, "paid": True})
if path == "/api/order/preview":
return jsonify(rtn_code=0, data={"has_card": True, "cards": [{"name": "演示骑行月卡", "remain": 12}],
"auto_return": True, "rounds_planned": 1, "duration_minutes": 19, "est_end_time": "19 分钟后"})
if path == "/api/share/sources":
return jsonify(rtn_code=0, data={"sources": [], "hidden_count": 0})
if path == "/api/share/active":
return jsonify(rtn_code=0, data=[])
if path.startswith("/api/share/"):
return jsonify(rtn_code=0, data=[], pending=[], usable=[], mine=[])
if path == "/api/rental/sync":
return jsonify(rtn_code=0, data={"active": False})
if path.startswith("/api/order/"):
return jsonify(rtn_code=0, message="模拟操作成功", data={"paid": True})
if path.startswith("/api/history/") or path.startswith("/api/analysis/") or path == "/api/bike_history":
return None # Read-only seeded history through the real analysis code.
if path == "/api/user/orders/trajectory":
return jsonify(rtn_code=0, data={"points": [], "bike_code": "51201", "hint": "演示订单无完整轨迹"})
return jsonify(rtn_code=403, message="演示模式暂不提供此操作"), 403