2849 lines
95 KiB
Python
2849 lines
95 KiB
Python
#!/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/<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"],
|
||
})
|
||
|
||
@app.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": "取消请求已发送"})
|
||
|
||
@app.route("/api/ring_progress/<task_id>")
|
||
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/<task_id>", 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)
|