初版:小白超人(从线上实例导出)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# Flask Blueprint 路由模块
|
||||
+1226
File diff suppressed because it is too large
Load Diff
+743
@@ -0,0 +1,743 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""用户认证路由"""
|
||||
import re
|
||||
import hashlib
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from db import (get_db, get_user_rental_settings, normalize_rental_settings,
|
||||
save_user_rental_settings, consume_invite_code, get_user_alert_email)
|
||||
from wechat import request_with_user_auth
|
||||
import email_verify
|
||||
import rate_limit
|
||||
|
||||
bp = Blueprint("auth", __name__)
|
||||
|
||||
|
||||
# ========== 简易限流(内存版,单进程足够) ==========
|
||||
# 登录:同一 (IP, 邮箱) 连续失败 5 次锁定 15 分钟
|
||||
# 注册:同一 IP 每小时最多 5 次注册
|
||||
_rl_lock = threading.Lock()
|
||||
_login_fail: dict = {} # (ip, email) -> [fail_count, first_fail_ts]
|
||||
_register_ips: dict = {} # ip -> [count, window_start_ts]
|
||||
LOGIN_MAX_FAILS = 5
|
||||
LOGIN_LOCK_SECONDS = 15 * 60
|
||||
REGISTER_MAX_PER_HOUR = 5
|
||||
|
||||
|
||||
def _client_ip() -> str:
|
||||
"""获取真实客户端 IP。
|
||||
|
||||
本服务部署在 nginx 反代之后(HTTP 直连本机),取 IP 的规则:
|
||||
- 仅当请求来自本机回环(nginx 与本服务同机部署)时,才信任代理注入的头:
|
||||
优先 X-Real-IP,其次 X-Forwarded-For 的最右一项;
|
||||
- 其余来源(含内网直连)一律使用 remote_addr,
|
||||
防止局域网/直连客户端伪造 X-Real-IP 绕过限流与登录锁定。"""
|
||||
remote = request.remote_addr or ""
|
||||
if remote in ("127.0.0.1", "::1"):
|
||||
real = request.headers.get("X-Real-IP", "").strip()
|
||||
if real:
|
||||
return real
|
||||
xff = request.headers.get("X-Forwarded-For", "").strip()
|
||||
if xff:
|
||||
return xff.split(",")[-1].strip()
|
||||
return remote or "unknown"
|
||||
|
||||
|
||||
def _strict_signature_required() -> bool:
|
||||
"""上游强签名验证是否开启(管理端开关)"""
|
||||
from wechat import is_strict_mode
|
||||
return is_strict_mode()
|
||||
|
||||
|
||||
def _login_rate_ok(ip: str, email: str):
|
||||
"""检查登录是否被锁定。返回 (ok, 剩余秒数)"""
|
||||
key = (ip, email)
|
||||
now = time.time()
|
||||
with _rl_lock:
|
||||
entry = _login_fail.get(key)
|
||||
if not entry:
|
||||
return True, 0
|
||||
count, first_ts = entry
|
||||
if now - first_ts > LOGIN_LOCK_SECONDS:
|
||||
# 窗口已过,重置
|
||||
del _login_fail[key]
|
||||
return True, 0
|
||||
if count >= LOGIN_MAX_FAILS:
|
||||
return False, int(LOGIN_LOCK_SECONDS - (now - first_ts))
|
||||
return True, 0
|
||||
|
||||
|
||||
def _login_record_fail(ip: str, email: str):
|
||||
key = (ip, email)
|
||||
now = time.time()
|
||||
with _rl_lock:
|
||||
entry = _login_fail.get(key)
|
||||
if not entry or now - entry[1] > LOGIN_LOCK_SECONDS:
|
||||
_login_fail[key] = [1, now]
|
||||
else:
|
||||
entry[0] += 1
|
||||
|
||||
|
||||
def _login_record_success(ip: str, email: str):
|
||||
with _rl_lock:
|
||||
_login_fail.pop((ip, email), None)
|
||||
|
||||
|
||||
def _register_rate_ok(ip: str):
|
||||
now = time.time()
|
||||
with _rl_lock:
|
||||
entry = _register_ips.get(ip)
|
||||
if not entry or now - entry[1] > 3600:
|
||||
_register_ips[ip] = [1, now]
|
||||
return True
|
||||
entry[0] += 1
|
||||
return entry[0] <= REGISTER_MAX_PER_HOUR
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return hashlib.sha256(password.encode()).hexdigest()
|
||||
|
||||
|
||||
def generate_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
SESSION_EXPIRY_DAYS = 30
|
||||
|
||||
|
||||
def _ua_label(ua: str) -> str:
|
||||
"""从 User-Agent 生成一个可读的设备名(服务端权威解析)。
|
||||
原生壳(Android WebView 注入 xbniu-native)显示为 Native App;
|
||||
鸿蒙(OpenHarmony/ArkWeb)识别为鸿蒙;无匹配时不写"未知"。"""
|
||||
if "xbniu-native" in ua.lower():
|
||||
return "Native App"
|
||||
if "Windows NT" in ua:
|
||||
os_name = "Windows"
|
||||
elif "iPhone" in ua or "iPad" in ua or "iPod" in ua:
|
||||
os_name = "iOS"
|
||||
elif "OpenHarmony" in ua or "HarmonyOS" in ua or "ArkWeb" in ua:
|
||||
os_name = "鸿蒙"
|
||||
elif "Android" in ua:
|
||||
os_name = "Android"
|
||||
elif "Mac OS X" in ua:
|
||||
os_name = "macOS"
|
||||
elif "Linux" in ua:
|
||||
os_name = "Linux"
|
||||
elif "Mobile" in ua:
|
||||
os_name = "移动设备"
|
||||
else:
|
||||
os_name = "电脑"
|
||||
browser = "浏览器"
|
||||
if "MicroMessenger" in ua:
|
||||
browser = "微信"
|
||||
elif "HuaweiBrowser" in ua:
|
||||
browser = "华为浏览器"
|
||||
elif "Edg/" in ua:
|
||||
browser = "Edge"
|
||||
elif "QQBrowser" in ua:
|
||||
browser = "QQ浏览器"
|
||||
elif "MiuiBrowser" in ua:
|
||||
browser = "小米浏览器"
|
||||
elif "Chrome/" in ua:
|
||||
browser = "Chrome"
|
||||
elif "Firefox/" in ua:
|
||||
browser = "Firefox"
|
||||
elif "Safari/" in ua:
|
||||
browser = "Safari"
|
||||
return f"{os_name} · {browser}"
|
||||
|
||||
|
||||
def _collect_device_info(data):
|
||||
"""从请求提取/生成设备标识信息。仅用于设备管理展示,不改变认证方式。
|
||||
设备名以服务端按 UA 解析为准(含 Native App / 鸿蒙识别),
|
||||
仅当请求无 UA 时才退回客户端上报的名字。
|
||||
返回 (device_name, device_id, user_agent)"""
|
||||
ua = (request.headers.get("User-Agent", "") or "").strip()
|
||||
device_id = (data.get("device_id") or "").strip()
|
||||
if not device_id:
|
||||
device_id = hashlib.sha256((ua or "unknown").encode("utf-8")).hexdigest()[:16]
|
||||
if ua:
|
||||
device_name = _ua_label(ua)
|
||||
else:
|
||||
device_name = (data.get("device_name") or "").strip() or "未知设备"
|
||||
return device_name[:60], device_id[:64], ua[:500]
|
||||
|
||||
|
||||
def get_current_user():
|
||||
"""获取当前登录用户"""
|
||||
token = request.headers.get("Authorization", "").replace("Bearer ", "")
|
||||
if not token:
|
||||
return None
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT users.id, users.email FROM sessions
|
||||
JOIN users ON sessions.user_id = users.id
|
||||
WHERE sessions.token = ? AND sessions.expires_at > datetime('now', '+8 hours')
|
||||
""", (token,))
|
||||
user = cursor.fetchone()
|
||||
if user:
|
||||
# 最近活跃时间:节流刷新(至多每 5 分钟写一次),供“登录设备管理”展示;时间统一为 GMT+8
|
||||
cursor.execute("""
|
||||
UPDATE sessions SET last_active = datetime('now', '+8 hours')
|
||||
WHERE token = ? AND (last_active IS NULL
|
||||
OR last_active < datetime('now', '+8 hours', '-300 seconds'))
|
||||
""", (token,))
|
||||
# 登录设备类型:只要有请求(含打开页面时的 /api/auth/status)就按最新 UA 刷新,
|
||||
# 同一会话换浏览器/进原生壳后立即生效;仅在类型确实变化时才产生写入
|
||||
ua = (request.headers.get("User-Agent", "") or "").strip()
|
||||
if ua:
|
||||
label = _ua_label(ua)[:60]
|
||||
cursor.execute("""
|
||||
UPDATE sessions
|
||||
SET device_name = ?, user_agent = ?
|
||||
WHERE token = ? AND (device_name != ? OR user_agent != ?)
|
||||
""", (label, ua[:500], token, label, ua[:500]))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return dict(user) if user else None
|
||||
|
||||
|
||||
def login_required():
|
||||
"""验证登录状态"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
|
||||
return user
|
||||
|
||||
|
||||
@bp.route("/api/auth/send_code", methods=["POST"])
|
||||
def auth_send_code():
|
||||
"""发送邮箱验证码。purpose=register 注册 / reset 重置密码。
|
||||
无论邮箱是否已注册都返回同样的成功响应,避免通过本接口枚举已注册邮箱;
|
||||
重置用途时未注册邮箱实际不会发信(静默丢弃)。验证码 60 秒冷却与 IP 上限在服务端强制。"""
|
||||
data = request.get_json() or {}
|
||||
email = data.get("email", "").strip().lower()
|
||||
purpose = str(data.get("purpose", "register")).strip() or "register"
|
||||
if purpose not in ("register", "reset"):
|
||||
purpose = "register"
|
||||
if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email):
|
||||
return jsonify({"rtn_code": 400, "message": "邮箱格式不正确"})
|
||||
ip = _client_ip()
|
||||
if not email_verify.ip_send_allowed(ip):
|
||||
return jsonify({"rtn_code": 429,
|
||||
"message": "验证码请求过于频繁,请稍后再试"}), 429
|
||||
cooldown = email_verify.check_send_cooldown(email)
|
||||
if cooldown > 0:
|
||||
return jsonify({"rtn_code": 429,
|
||||
"message": f"发送过于频繁,请 {cooldown} 秒后再试"}), 429
|
||||
if purpose == "reset":
|
||||
# 防枚举:未注册邮箱保持相同响应但不真正发信
|
||||
conn = get_db()
|
||||
row = conn.execute("SELECT id FROM users WHERE email = ?", (email,)).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
return jsonify({"rtn_code": 0, "message": "验证码已发送,请查收邮箱(注意垃圾箱)"})
|
||||
ok, message = email_verify.send_code(email, purpose=purpose)
|
||||
if not ok:
|
||||
return jsonify({"rtn_code": 500, "message": message})
|
||||
return jsonify({"rtn_code": 0, "message": "验证码已发送,请查收邮箱(注意垃圾箱)"})
|
||||
|
||||
|
||||
@bp.route("/api/auth/register", methods=["POST"])
|
||||
def register():
|
||||
data = request.get_json() or {}
|
||||
email = data.get("email", "").strip().lower()
|
||||
password = data.get("password", "")
|
||||
# access_token 选填;兼容旧前端的 wx_signature / token 键名
|
||||
access_token = (data.get("access_token") or data.get("wx_signature")
|
||||
or data.get("token") or "").strip()
|
||||
token_id = data.get("token_id", "").strip()
|
||||
code = str(data.get("code", "")).strip()
|
||||
|
||||
if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email):
|
||||
return jsonify({"rtn_code": 400, "message": "邮箱格式不正确"})
|
||||
if len(password) < 6:
|
||||
return jsonify({"rtn_code": 400, "message": "密码至少6位"})
|
||||
if not code:
|
||||
return jsonify({"rtn_code": 400, "message": "请输入邮箱验证码"})
|
||||
if not _register_rate_ok(_client_ip()):
|
||||
return jsonify({"rtn_code": 429, "message": "注册过于频繁,请稍后再试"})
|
||||
# 先校验验证码再查邮箱是否已注册:验证码与邮箱绑定,
|
||||
# 攻击者拿不到别人邮箱里的验证码就无法探测该邮箱是否已注册。
|
||||
if not email_verify.verify_code(email, code):
|
||||
return jsonify({"rtn_code": 400, "message": "验证码错误或已过期,请重新获取"})
|
||||
if _strict_signature_required() and not access_token:
|
||||
return jsonify({"rtn_code": 400,
|
||||
"message": "已开启强签名验证:注册时必须填写 AccessToken"})
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id FROM users WHERE email = ?", (email,))
|
||||
if cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": "该邮箱已注册"})
|
||||
|
||||
# 注册时尚无登录态,凭据有效性由服务端直接向上游校验
|
||||
# (前端注册表单预检用的 verify_token 接口需要登录,此处为权威校验)
|
||||
if token_id or access_token:
|
||||
valid, msg = _verify_upstream_token(token_id, access_token)
|
||||
if not valid:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": f"微信凭据校验未通过:{msg}"})
|
||||
|
||||
# 邀请码:所有其他校验通过后再核销,避免失败尝试浪费使用次数
|
||||
invite_code = str(data.get("invite_code", "")).strip()
|
||||
ok, invite_msg = consume_invite_code(invite_code, email)
|
||||
if not ok:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": invite_msg})
|
||||
|
||||
password_hash = hash_password(password)
|
||||
cursor.execute(
|
||||
"INSERT INTO users (email, password_hash, access_token, token_id) VALUES (?, ?, ?, ?)",
|
||||
(email, password_hash, access_token if access_token else None,
|
||||
token_id if token_id else None)
|
||||
)
|
||||
user_id = cursor.lastrowid
|
||||
|
||||
session_token = generate_token()
|
||||
device_name, device_id, user_agent = _collect_device_info(data)
|
||||
cursor.execute("""
|
||||
INSERT INTO sessions (user_id, token, expires_at, device_name, device_id, user_agent, last_active)
|
||||
VALUES (?, ?, datetime('now', '+8 hours', '+30 days'), ?, ?, ?, datetime('now', '+8 hours'))
|
||||
""", (user_id, session_token, device_name, device_id, user_agent))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
# 只有用户自带微信凭据时才启动订单检测;不再默认继承全局 token_id
|
||||
if token_id:
|
||||
from timer import start_user_order_checker
|
||||
start_user_order_checker(user_id)
|
||||
|
||||
return jsonify({"rtn_code": 0, "message": "注册成功",
|
||||
"data": {"token": session_token, "email": email}})
|
||||
|
||||
|
||||
@bp.route("/api/auth/reset_password", methods=["POST"])
|
||||
def auth_reset_password():
|
||||
"""忘记密码:邮箱验证码重置。成功后作废该账号全部登录会话(防凭据盗用延续)。"""
|
||||
data = request.get_json() or {}
|
||||
email = data.get("email", "").strip().lower()
|
||||
password = data.get("password", "")
|
||||
code = str(data.get("code", "")).strip()
|
||||
if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email):
|
||||
return jsonify({"rtn_code": 400, "message": "邮箱格式不正确"})
|
||||
if len(password) < 6:
|
||||
return jsonify({"rtn_code": 400, "message": "密码至少6位"})
|
||||
if not code:
|
||||
return jsonify({"rtn_code": 400, "message": "请输入邮箱验证码"})
|
||||
# 限流:每 IP 每小时最多 10 次重置尝试(验证码本身另有 5 次错误作废)
|
||||
if not rate_limit.hit(("reset_pwd", _client_ip()), 10, 3600):
|
||||
return jsonify({"rtn_code": 429, "message": "尝试过于频繁,请稍后再试"})
|
||||
if not email_verify.verify_code(email, code, purpose="reset"):
|
||||
return jsonify({"rtn_code": 400, "message": "验证码错误或已过期,请重新获取"})
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id FROM users WHERE email = ?", (email,))
|
||||
user = cursor.fetchone()
|
||||
if not user:
|
||||
conn.close()
|
||||
# 验证码已消费:不回滚(保持与发送时相同的防枚举语义)
|
||||
return jsonify({"rtn_code": 400, "message": "该邮箱尚未注册"})
|
||||
cursor.execute("UPDATE users SET password_hash = ? WHERE id = ?",
|
||||
(hash_password(password), user["id"]))
|
||||
cursor.execute("DELETE FROM sessions WHERE user_id = ?", (user["id"],))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"[操作日志] 重置密码: email={email}")
|
||||
return jsonify({"rtn_code": 0, "message": "密码已重置,请使用新密码重新登录"})
|
||||
|
||||
|
||||
@bp.route("/api/auth/alert_email", methods=["GET", "POST"])
|
||||
def auth_alert_email():
|
||||
"""查看/设置凭据失效告警接收邮箱(默认账号邮箱)。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
if request.method == "GET":
|
||||
from db import get_user_alert_email
|
||||
return jsonify({"rtn_code": 0, "data": {"alert_email": get_user_alert_email(user["id"])}})
|
||||
data = request.get_json(silent=True) or {}
|
||||
email = str(data.get("email", "")).strip().lower()
|
||||
if email and not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email):
|
||||
return jsonify({"rtn_code": 400, "message": "邮箱格式不正确"})
|
||||
from db import set_user_alert_email
|
||||
if not set_user_alert_email(user["id"], email):
|
||||
return jsonify({"rtn_code": 404, "message": "用户不存在"})
|
||||
return jsonify({"rtn_code": 0, "message": "告警邮箱已保存"})
|
||||
|
||||
|
||||
@bp.route("/api/auth/login", methods=["POST"])
|
||||
def login():
|
||||
data = request.get_json() or {}
|
||||
email = data.get("email", "").strip().lower()
|
||||
password = data.get("password", "")
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id, email, password_hash FROM users WHERE email = ?", (email,))
|
||||
user = cursor.fetchone()
|
||||
ip = _client_ip()
|
||||
ok, wait_seconds = _login_rate_ok(ip, email)
|
||||
if not ok:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 429,
|
||||
"message": f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"})
|
||||
if not user or user["password_hash"] != hash_password(password):
|
||||
conn.close()
|
||||
_login_record_fail(ip, email)
|
||||
return jsonify({"rtn_code": 400, "message": "邮箱或密码错误"})
|
||||
_login_record_success(ip, email)
|
||||
|
||||
# 支持多设备同时登录:不再清空该用户的旧会话,仅为本设备新增一条会话
|
||||
session_token = generate_token()
|
||||
device_name, device_id, user_agent = _collect_device_info(data)
|
||||
cursor.execute("""
|
||||
INSERT INTO sessions (user_id, token, expires_at, device_name, device_id, user_agent, last_active)
|
||||
VALUES (?, ?, datetime('now', '+8 hours', '+30 days'), ?, ?, ?, datetime('now', '+8 hours'))
|
||||
""", (user["id"], session_token, device_name, device_id, user_agent))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
return jsonify({"rtn_code": 0, "message": "登录成功",
|
||||
"data": {"token": session_token, "email": user["email"]}})
|
||||
|
||||
|
||||
@bp.route("/api/auth/logout", methods=["POST"])
|
||||
def logout():
|
||||
token = request.headers.get("Authorization", "").replace("Bearer ", "")
|
||||
if token:
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM sessions WHERE token = ?", (token,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "已退出登录"})
|
||||
|
||||
|
||||
@bp.route("/api/auth/status")
|
||||
def auth_status():
|
||||
user = get_current_user()
|
||||
from wechat import is_strict_mode
|
||||
strict = is_strict_mode()
|
||||
if user:
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT access_token FROM users WHERE id = ?", (user["id"],))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
has_at = bool(row and row["access_token"])
|
||||
data = {"logged_in": True, "email": user["email"],
|
||||
"strict_mode": strict, "has_access_token": has_at}
|
||||
if strict and not has_at:
|
||||
data["notice"] = "已开启强签名验证:请补充 AccessToken"
|
||||
return jsonify({"rtn_code": 0, "data": data})
|
||||
return jsonify({"rtn_code": 0, "data": {"logged_in": False, "strict_mode": strict}})
|
||||
|
||||
|
||||
@bp.route("/api/auth/sessions", methods=["GET"])
|
||||
def list_sessions():
|
||||
"""列出当前账号所有登录设备(多设备会话),标记当前设备"""
|
||||
token = request.headers.get("Authorization", "").replace("Bearer ", "")
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT id, device_name, device_id, user_agent, created_at, last_active,
|
||||
CASE WHEN token = ? THEN 1 ELSE 0 END AS is_current
|
||||
FROM sessions
|
||||
WHERE user_id = ? AND expires_at > datetime('now', '+8 hours')
|
||||
ORDER BY is_current DESC,
|
||||
COALESCE(last_active, created_at, '1970-01-01') DESC, id DESC
|
||||
""", (token, user["id"]))
|
||||
sessions = [dict(r) for r in cursor.fetchall()]
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "data": {"sessions": sessions}})
|
||||
|
||||
|
||||
@bp.route("/api/auth/sessions/kick", methods=["POST"])
|
||||
def kick_session():
|
||||
"""下线某台设备(仅限当前账号下的其他设备,禁止下线自己)"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
|
||||
data = request.get_json() or {}
|
||||
try:
|
||||
session_id = int(data.get("session_id"))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"rtn_code": 400, "message": "参数错误"})
|
||||
token = request.headers.get("Authorization", "").replace("Bearer ", "")
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id FROM sessions WHERE token = ? AND user_id = ?",
|
||||
(token, user["id"]))
|
||||
cur = cursor.fetchone()
|
||||
if cur and cur["id"] == session_id:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": "不能下线当前设备"})
|
||||
cursor.execute("DELETE FROM sessions WHERE id = ? AND user_id = ?",
|
||||
(session_id, user["id"]))
|
||||
deleted = cursor.rowcount
|
||||
conn.commit()
|
||||
conn.close()
|
||||
if deleted:
|
||||
return jsonify({"rtn_code": 0, "message": "已下线该设备"})
|
||||
return jsonify({"rtn_code": 404, "message": "设备不存在或已下线"})
|
||||
|
||||
|
||||
@bp.route("/api/auth/sessions/logout_all", methods=["POST"])
|
||||
def logout_all_other_sessions():
|
||||
"""下线当前账号除本设备外的所有登录设备"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
|
||||
token = request.headers.get("Authorization", "").replace("Bearer ", "")
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM sessions WHERE user_id = ? AND token != ?",
|
||||
(user["id"], token))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "已下线其他所有设备"})
|
||||
|
||||
|
||||
@bp.route("/api/auth/save_token", methods=["POST"])
|
||||
def save_xbniu_token():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
data = request.get_json() or {}
|
||||
# access_token 选填;兼容旧前端的 wx_signature / token 键名
|
||||
access_token = (data.get("access_token") or data.get("wx_signature")
|
||||
or data.get("token") or "").strip()
|
||||
token_id = data.get("token_id", "").strip()
|
||||
if _strict_signature_required() and not access_token:
|
||||
return jsonify({"rtn_code": 400,
|
||||
"message": "已开启强签名验证:必须填写 AccessToken"})
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 400, "message": "Token ID 不能为空"})
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"UPDATE users SET access_token = ?, token_id = ? WHERE id = ?",
|
||||
(access_token if access_token else None, token_id if token_id else None, user["id"])
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
from timer import start_user_order_checker, stop_user_order_checker
|
||||
if token_id:
|
||||
start_user_order_checker(user["id"])
|
||||
else:
|
||||
stop_user_order_checker(user["id"])
|
||||
try:
|
||||
from routes.rental import _user_info_cache
|
||||
_user_info_cache.pop(user["id"], None) # 凭据变了,订单状态缓存立即失效
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return jsonify({"rtn_code": 0, "message": "凭据已保存"})
|
||||
|
||||
|
||||
def _verify_upstream_token(token_id: str, access_token: str) -> tuple:
|
||||
"""向上游校验微信凭据有效性。返回 (valid, message)。
|
||||
供 verify_token 接口(已登录,防枚举)与注册流程(注册时尚无登录态)共用。"""
|
||||
import requests as req
|
||||
from wechat import BASE_URL, make_signature
|
||||
timestamp = str(int(time.time()))
|
||||
test_headers = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"User-Agent": "Mozilla/5.0 (Linux; Android 13; V2134A Build/TP1A.220624.014) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 "
|
||||
"Chrome/107.0.0.0 Mobile Safari/537.36 "
|
||||
"MicroMessenger/8.0.43.2540(0x28002B33) WeChat/arm64 Weixin "
|
||||
"NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "*/*",
|
||||
"hsf-x-timestamp": timestamp,
|
||||
"hsf-x-tokenid": token_id,
|
||||
"hsf-x-signature": make_signature(access_token, "GET", "/user/info",
|
||||
timestamp, token_id),
|
||||
"platform": "xiaobai",
|
||||
}
|
||||
try:
|
||||
# 用 /user/info 验证:与车型无关,任何校区都返回 0,仅校验凭据有效性
|
||||
resp = req.get(f"{BASE_URL}/user/info",
|
||||
headers=test_headers, timeout=8)
|
||||
result = resp.json()
|
||||
if result.get("rtn_code") == 0:
|
||||
return True, "凭据有效"
|
||||
msg = result.get("message", "凭据无效")
|
||||
if result.get("rtn_code") == 102001:
|
||||
msg = "Token 已失效,请在小程序重新登录后获取新凭据"
|
||||
return False, msg
|
||||
except Exception as e:
|
||||
return False, f"验证失败: {e}"
|
||||
|
||||
|
||||
@bp.route("/api/auth/verify_token", methods=["POST"])
|
||||
def verify_xbniu_token():
|
||||
"""验证微信凭据有效性。需要已登录,防止被当作开放代理探测任意 token_id。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
data = request.get_json() or {}
|
||||
# access_token 选填(为空则用伪装签名,只验证 token_id 有效性);
|
||||
# 兼容旧前端的 wx_signature 键名
|
||||
access_token = (data.get("access_token") or data.get("wx_signature")
|
||||
or data.get("token") or "").strip()
|
||||
token_id = data.get("token_id", "").strip()
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 400, "message": "Token ID 不能为空"})
|
||||
|
||||
valid, msg = _verify_upstream_token(token_id, access_token)
|
||||
return jsonify({"rtn_code": 0, "valid": valid, "message": msg})
|
||||
|
||||
|
||||
@bp.route("/api/auth/profile", methods=["GET"])
|
||||
def get_profile():
|
||||
"""获取用户基本信息(包含token)"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT access_token, token_id FROM users WHERE id = ?", (user["id"],))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
|
||||
token_id = row["token_id"] if row else ""
|
||||
access_token = row["access_token"] if row else None
|
||||
|
||||
from wechat import parse_access_token_expiry
|
||||
expiry = parse_access_token_expiry(access_token)
|
||||
|
||||
return jsonify({
|
||||
"rtn_code": 0,
|
||||
"data": {
|
||||
"email": user["email"],
|
||||
"access_token": access_token,
|
||||
"token": access_token, # 旧前端兼容别名
|
||||
"token_id": token_id,
|
||||
"has_auth": bool(token_id),
|
||||
"has_access_token": bool(access_token),
|
||||
"access_token_expiry": expiry,
|
||||
"strict_mode": _strict_signature_required(),
|
||||
"alert_email": get_user_alert_email(user["id"]),
|
||||
"rental_settings": get_user_rental_settings(user["id"]),
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@bp.route("/api/auth/rental_settings", methods=["GET", "POST"])
|
||||
def rental_settings():
|
||||
"""查看或修改当前用户的提醒、到期时间与自动还车策略。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
if request.method == "GET":
|
||||
return jsonify({"rtn_code": 0, "data": get_user_rental_settings(user["id"])})
|
||||
try:
|
||||
settings = normalize_rental_settings(request.get_json(silent=True) or {})
|
||||
except ValueError as exc:
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
if not save_user_rental_settings(user["id"], settings):
|
||||
return jsonify({"rtn_code": 404, "message": "用户不存在"})
|
||||
from timer import reschedule_user_rental_timers
|
||||
reschedule_user_rental_timers(user["id"], apply_duration=True)
|
||||
return jsonify({"rtn_code": 0, "message": "用车设置已保存", "data": settings})
|
||||
|
||||
|
||||
@bp.route("/api/auth/user_info", methods=["GET"])
|
||||
def get_user_info():
|
||||
"""获取用户真实信息(姓名、已付钱、省的钱)- 需要有凭据"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT access_token, token_id FROM users WHERE id = ?", (user["id"],))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
|
||||
access_token = row["access_token"] if row else None
|
||||
token_id = row["token_id"] if row else ""
|
||||
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"true_name": None, "out_money": None, "save_money": None
|
||||
}})
|
||||
|
||||
true_name = None
|
||||
out_money = None
|
||||
save_money = None
|
||||
try:
|
||||
user_info = request_with_user_auth(user["id"], "GET", "/user/info", _silent=True)
|
||||
if user_info and user_info.get("rtn_code") == 0:
|
||||
data = user_info.get("data", {})
|
||||
true_name = data.get("trueName") or data.get("nickName")
|
||||
account = data.get("account", {})
|
||||
out_money = account.get("outMoney")
|
||||
save_money = account.get("saveMoney")
|
||||
except:
|
||||
pass
|
||||
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"true_name": true_name, "out_money": out_money,
|
||||
"save_money": save_money, "has_auth": True
|
||||
}})
|
||||
|
||||
|
||||
@bp.route("/api/auth/packages", methods=["GET"])
|
||||
def get_user_packages():
|
||||
"""获取用户的已购卡包信息"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
from db import get_user_auth
|
||||
token_id, access_token = get_user_auth(user["id"])
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 400, "message": "请先在个人中心填写 Token ID 和签名",
|
||||
"data": {"packages": [], "has_auth": False}})
|
||||
|
||||
import requests as req
|
||||
from wechat import BASE_URL, make_signature
|
||||
timestamp = str(int(time.time()))
|
||||
headers = {
|
||||
"Host": "bike.sdlongren.com",
|
||||
"hsf-x-timestamp": timestamp,
|
||||
"hsf-x-tokenid": token_id,
|
||||
"hsf-x-signature": make_signature(access_token, "GET", "/user/packages",
|
||||
timestamp, token_id),
|
||||
"xweb_xhr": "1", "platform": "xiaobai",
|
||||
"user-agent": "Mozilla/5.0 (Linux; Android 13; V2134A Build/TP1A.220624.014) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 "
|
||||
"Chrome/107.0.0.0 Mobile Safari/537.36 "
|
||||
"MicroMessenger/8.0.43.2540(0x28002B33) WeChat/arm64 Weixin "
|
||||
"NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android",
|
||||
"content-type": "application/json", "accept": "*/*",
|
||||
"referer": "https://servicewechat.com/wx10426ca961518f43/108/page-frame.html",
|
||||
}
|
||||
try:
|
||||
resp = req.get(f"{BASE_URL}/user/packages",
|
||||
headers=headers, timeout=10, verify=True)
|
||||
result = resp.json()
|
||||
packages = result.get("data", {}).get("bike_packages", [])
|
||||
return jsonify({"rtn_code": 0, "data": {"packages": packages, "has_auth": True}})
|
||||
except Exception as e:
|
||||
return jsonify({"rtn_code": 500, "message": f"请求失败: {e}",
|
||||
"data": {"packages": [], "has_auth": True}})
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""抓包工具安装包下载
|
||||
|
||||
安装包体积较大(约 160MB),放在项目根的 downloads/ 目录而不是 static/,
|
||||
避免被 Flask 静态路由以外的缓存策略干扰,也便于单独替换升级。
|
||||
|
||||
公开访问:用户注册前就需要拿到工具,若加登录校验会形成「没工具拿不到凭据、
|
||||
没凭据注册不了」的死循环。
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, jsonify, send_from_directory
|
||||
|
||||
bp = Blueprint("download", __name__)
|
||||
|
||||
# 磁盘上用 ASCII 文件名:中文与全角括号在部分 Linux 文件系统/nginx 配置下
|
||||
# 容易出编码问题。对外的下载文件名由 download_name 还原。
|
||||
DOWNLOADS_DIR = Path(__file__).parent.parent / "downloads"
|
||||
CAPTURE_TOOL_FILE = "xbniu-capture-tool.exe"
|
||||
CAPTURE_TOOL_NAME = "小白超人抓包工具(新版).exe"
|
||||
|
||||
|
||||
@bp.route("/download/capture-tool.exe", methods=["GET", "HEAD"])
|
||||
def download_capture_tool():
|
||||
if not (DOWNLOADS_DIR / CAPTURE_TOOL_FILE).is_file():
|
||||
return jsonify({"rtn_code": 404, "message": "安装包暂未上传"}), 404
|
||||
# conditional=True 支持 Range 请求,大文件可断点续传/多线程下载
|
||||
resp = send_from_directory(
|
||||
DOWNLOADS_DIR,
|
||||
CAPTURE_TOOL_FILE,
|
||||
as_attachment=True,
|
||||
download_name=CAPTURE_TOOL_NAME,
|
||||
conditional=True,
|
||||
max_age=3600,
|
||||
)
|
||||
# Flask 只在收到 Range 时才回 Content-Range,但下载管理器需要先看到
|
||||
# Accept-Ranges 才敢发 Range,所以这里显式声明支持续传
|
||||
resp.headers["Accept-Ranges"] = "bytes"
|
||||
return resp
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据导出:历史轨迹 CSV 直链下载。
|
||||
|
||||
流程:登录用户在分析页点导出 → POST /api/export/create(需登录)→
|
||||
返回 /export/csv/<token> 直链(免登录,1 小时有效,一次性换浏览器可继续下载)。
|
||||
前端用 detectInAppBrowser 复用「复制链接到外部浏览器」提示(微信/原生壳内无法下载)。
|
||||
|
||||
CSV 内容:最近 3 天全部车辆点位(与库内保留策略一致)。
|
||||
"""
|
||||
import csv
|
||||
import datetime as dt
|
||||
import io
|
||||
import secrets
|
||||
|
||||
from flask import Blueprint, jsonify, request, Response
|
||||
|
||||
from db import get_db
|
||||
from routes.auth import get_current_user
|
||||
|
||||
bp = Blueprint("export", __name__)
|
||||
|
||||
EXPORT_TTL_HOURS = 1
|
||||
# 与 app.HISTORY_RETENTION_DAYS 对齐(bike_history 库内保留窗口)
|
||||
HISTORY_DAYS = 30
|
||||
|
||||
_STATE_LABELS = {
|
||||
"available": "可用", "used": "使用中", "locked": "欠压",
|
||||
"reserved": "损坏", "low": "低电量",
|
||||
}
|
||||
|
||||
|
||||
def _classify(state, status, electric):
|
||||
try:
|
||||
state = int(state)
|
||||
except (TypeError, ValueError):
|
||||
state = 1
|
||||
try:
|
||||
status = int(status)
|
||||
except (TypeError, ValueError):
|
||||
status = 1
|
||||
try:
|
||||
electric = float(electric)
|
||||
except (TypeError, ValueError):
|
||||
electric = 100.0
|
||||
if state == 10 or electric < 20:
|
||||
return "low"
|
||||
if state == 4:
|
||||
return "locked"
|
||||
if state == 2:
|
||||
return "reserved"
|
||||
if state == 1 and status == 1:
|
||||
return "used"
|
||||
return "available"
|
||||
|
||||
|
||||
def _clean_expired_tokens(conn):
|
||||
conn.execute("DELETE FROM export_tokens WHERE expires_at < datetime('now', '+8 hours')")
|
||||
|
||||
|
||||
@bp.route("/api/export/create", methods=["POST"])
|
||||
def export_create():
|
||||
"""创建导出直链。body: {type: 'history_csv'}(当前仅一种)。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json(silent=True) or {}
|
||||
export_type = str(data.get("type") or "history_csv")
|
||||
if export_type != "history_csv":
|
||||
return jsonify({"rtn_code": 400, "message": "暂不支持该导出类型"})
|
||||
|
||||
token = secrets.token_urlsafe(24)
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
expires = (dt.datetime.now(tz) + dt.timedelta(hours=EXPORT_TTL_HOURS)).strftime(
|
||||
"%Y-%m-%d %H:%M:%S")
|
||||
conn = get_db()
|
||||
_clean_expired_tokens(conn)
|
||||
conn.execute(
|
||||
"INSERT INTO export_tokens (token, scope, expires_at) VALUES (?, ?, ?)",
|
||||
(token, export_type, expires))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"[导出] 创建直链: user={user['email']}, 有效期至 {expires}")
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"url": f"/export/csv/{token}",
|
||||
"expires_at": expires,
|
||||
"ttl_hours": EXPORT_TTL_HOURS,
|
||||
}})
|
||||
|
||||
|
||||
@bp.route("/export/csv/<token>")
|
||||
def export_download(token):
|
||||
"""直链下载(免登录):1 小时内有效,可重复下载,换浏览器也能用。"""
|
||||
token = (token or "").strip()
|
||||
if not token or len(token) > 120:
|
||||
return jsonify({"rtn_code": 400, "message": "导出链接无效"}), 400
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT token, scope, expires_at FROM export_tokens WHERE token = ?",
|
||||
(token,)).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
return jsonify({"rtn_code": 404, "message": "导出链接不存在或已失效"}), 404
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
try:
|
||||
expires = dt.datetime.strptime(row["expires_at"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"rtn_code": 400, "message": "导出链接已失效"}), 400
|
||||
if expires <= dt.datetime.now(tz):
|
||||
return jsonify({"rtn_code": 400, "message": "导出链接已过期(有效期 1 小时),请重新生成"}), 400
|
||||
|
||||
stamp = dt.datetime.now(tz).strftime("%Y%m%d-%H%M")
|
||||
filename = f"xbniu_history_{stamp}.csv"
|
||||
|
||||
def generate():
|
||||
# UTF-8 BOM:让 Excel 直接双击打开不乱码
|
||||
yield "\ufeff"
|
||||
buf = io.StringIO()
|
||||
writer = csv.writer(buf, lineterminator="\n")
|
||||
writer.writerow(["bike_code", "latitude", "longitude",
|
||||
"state_label", "electric", "recorded_at"])
|
||||
yield buf.getvalue()
|
||||
buf.seek(0)
|
||||
buf.truncate(0)
|
||||
|
||||
conn = get_db()
|
||||
try:
|
||||
cursor = conn.execute("""
|
||||
SELECT bike_code, latitude, longitude, state, status, electric, recorded_at
|
||||
FROM bike_history
|
||||
WHERE recorded_at >= datetime('now', '+8 hours', ?)
|
||||
ORDER BY recorded_at ASC, bike_code
|
||||
""", (f"-{HISTORY_DAYS} days",))
|
||||
while True:
|
||||
rows = cursor.fetchmany(2000)
|
||||
if not rows:
|
||||
break
|
||||
for r in rows:
|
||||
writer.writerow([
|
||||
r["bike_code"], r["latitude"], r["longitude"],
|
||||
_STATE_LABELS.get(_classify(r["state"], r["status"], r["electric"]),
|
||||
"未知"),
|
||||
r["electric"], r["recorded_at"],
|
||||
])
|
||||
yield buf.getvalue()
|
||||
buf.seek(0)
|
||||
buf.truncate(0)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
resp = Response(generate(), mimetype="text/csv; charset=utf-8")
|
||||
resp.headers["Content-Disposition"] = f"attachment; filename=\"{filename}\""
|
||||
resp.headers["Cache-Control"] = "no-store"
|
||||
return resp
|
||||
@@ -0,0 +1,412 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""地图数据、寻车、分析等路由"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
import hashlib
|
||||
import threading
|
||||
import asyncio
|
||||
import aiohttp
|
||||
from pathlib import Path
|
||||
from flask import Blueprint, current_app, jsonify, request, render_template
|
||||
|
||||
from db import get_db, get_user_display_name, get_user_auth
|
||||
from routes.auth import get_current_user
|
||||
from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS
|
||||
|
||||
bp = Blueprint("map_api", __name__)
|
||||
|
||||
# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放
|
||||
BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
|
||||
|
||||
# 并行寻车任务
|
||||
ring_tasks: dict = {}
|
||||
_ring_lock = threading.Lock()
|
||||
|
||||
|
||||
async def ring_single_bike_async(session, bike_code, school_id=10):
|
||||
try:
|
||||
headers = {**SEARCH_HEADERS, **get_signature_headers()}
|
||||
async with session.post(
|
||||
SEARCH_BIKE_URL,
|
||||
json={"code": bike_code, "school_id": school_id},
|
||||
headers=headers,
|
||||
timeout=aiohttp.ClientTimeout(total=5)
|
||||
) as resp:
|
||||
data = await resp.json()
|
||||
return data.get("rtn_code") == 0 or data.get("success") is True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def run_ring_task(task_id: str):
|
||||
global ring_tasks
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return
|
||||
bikes = task["bikes"]
|
||||
total = len(bikes)
|
||||
task["total"] = total
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop)
|
||||
try:
|
||||
async def run_session():
|
||||
semaphore = asyncio.Semaphore(20)
|
||||
async with aiohttp.ClientSession(connector=connector) as session:
|
||||
async def ring_one(idx, code):
|
||||
async with semaphore:
|
||||
if task["cancelled"]:
|
||||
return False
|
||||
result = await ring_single_bike_async(session, code, 10)
|
||||
with _ring_lock:
|
||||
task["done"] += 1
|
||||
if result:
|
||||
task["success"] += 1
|
||||
else:
|
||||
task["failed"] += 1
|
||||
task["last_update"] = time.time()
|
||||
return result
|
||||
batch_size = 20
|
||||
for i in range(0, len(bikes), batch_size):
|
||||
if task["cancelled"]:
|
||||
break
|
||||
batch = bikes[i:i + batch_size]
|
||||
await asyncio.gather(
|
||||
*[ring_one(i + j, b["code"]) for j, b in enumerate(batch)],
|
||||
return_exceptions=True
|
||||
)
|
||||
await asyncio.sleep(0.1)
|
||||
loop.run_until_complete(run_session())
|
||||
finally:
|
||||
with _ring_lock:
|
||||
task["status"] = "completed" if not task["cancelled"] else "cancelled"
|
||||
task["done"] = total
|
||||
loop.close()
|
||||
|
||||
|
||||
@bp.route("/api/ring_all", methods=["POST"])
|
||||
def api_ring_all():
|
||||
global ring_tasks
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
if user["email"] not in BATCH_RING_ALLOWED_EMAILS:
|
||||
return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"})
|
||||
data = request.get_json() or {}
|
||||
codes = data.get("codes", [])
|
||||
if isinstance(codes, str):
|
||||
codes = [codes]
|
||||
if not codes:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}")
|
||||
task_id = str(uuid.uuid4())[:8]
|
||||
task = {
|
||||
"status": "running", "total": len(codes), "done": 0,
|
||||
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
|
||||
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
|
||||
}
|
||||
with _ring_lock:
|
||||
ring_tasks[task_id] = task
|
||||
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
|
||||
t.start()
|
||||
return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes),
|
||||
"message": f"任务已启动,共 {len(codes)} 辆车"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_status/<task_id>")
|
||||
def api_ring_status(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
|
||||
"done": task["done"], "success": task["success"], "failed": task["failed"]})
|
||||
|
||||
|
||||
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
|
||||
def api_ring_cancel(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
if task["status"] != "running":
|
||||
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
|
||||
task["cancelled"] = True
|
||||
task["status"] = "cancelling"
|
||||
return jsonify({"rtn_code": 0, "message": "取消请求已发送"})
|
||||
|
||||
|
||||
@bp.route("/api/ring_progress/<task_id>")
|
||||
def api_ring_progress(task_id):
|
||||
from flask import Response as FlaskResponse
|
||||
global ring_tasks
|
||||
def _sse(obj):
|
||||
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
||||
def generate():
|
||||
last_done = -1
|
||||
last_status = None
|
||||
tick = 0
|
||||
while True:
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
|
||||
yield _sse({"type": "error", "message": "任务不存在或已结束"})
|
||||
return
|
||||
done = task["done"]
|
||||
status = task["status"]
|
||||
if done != last_done or status != last_status:
|
||||
last_done = done
|
||||
last_status = status
|
||||
yield _sse({
|
||||
"type": "progress",
|
||||
"status": status,
|
||||
"done": done,
|
||||
"total": task["total"],
|
||||
"success": task["success"],
|
||||
"failed": task["failed"],
|
||||
})
|
||||
if status in ("completed", "cancelled"):
|
||||
# 已结束,补发一条 done 事件后关闭
|
||||
yield _sse({"type": "done", "status": status})
|
||||
return
|
||||
tick += 1
|
||||
if tick >= 20: # 约 10s 一次心跳,避免代理/连接超时被判定为断开
|
||||
tick = 0
|
||||
yield ": ping\n\n"
|
||||
time.sleep(0.5)
|
||||
return FlaskResponse(
|
||||
generate(),
|
||||
mimetype="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
|
||||
def api_ring_status_clear(task_id):
|
||||
with _ring_lock:
|
||||
ring_tasks.pop(task_id, None)
|
||||
return jsonify({"rtn_code": 0, "message": "已清除"})
|
||||
|
||||
|
||||
@bp.route("/api/map")
|
||||
def api_map():
|
||||
# 非登录人员不能使用:地图数据需登录后查看
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
bike_type = request.args.get("type", "1").strip()
|
||||
from map_cache import MAP_TYPES
|
||||
if bike_type not in MAP_TYPES:
|
||||
return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400
|
||||
result = request_api("GET", "/project/map", params={"type": bike_type})
|
||||
# 上游错误文案统一翻译(成功响应原样透传)
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
response = jsonify(result)
|
||||
# Only the server snapshot is cached; browsers must ask the server on refresh.
|
||||
response.headers["Cache-Control"] = "private, no-store"
|
||||
response.headers["Vary"] = "Authorization"
|
||||
response.headers["X-Map-Server-Time"] = str(time.time())
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/api/bicycle", methods=["GET", "POST"])
|
||||
def api_bicycle():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
code = data.get("code", "")
|
||||
if not code:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
|
||||
user_name = get_user_display_name(user["id"])
|
||||
print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}")
|
||||
result = request_api("POST", "/project/bicycle", data={"code": code})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/find_bike", methods=["POST"])
|
||||
def api_find_bike():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||
data = request.get_json() or {}
|
||||
keyword = (data.get("keyword") or data.get("code") or "").strip()
|
||||
if not keyword:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少关键字"})
|
||||
school_id = data.get("school_id", 10)
|
||||
result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id})
|
||||
if result.get("rtn_code") not in (None, 0):
|
||||
from wechat import friendly_upstream_message
|
||||
result = {**result,
|
||||
"message": friendly_upstream_message(result.get("message", ""))}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/config")
|
||||
def api_config():
|
||||
return jsonify({
|
||||
"center_lat": 36.531820, "center_lng": 116.780180,
|
||||
"scale": 17, "school_name": "山东管理学院",
|
||||
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
|
||||
})
|
||||
|
||||
|
||||
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
|
||||
@bp.route("/api/map/freshness")
|
||||
def api_map_freshness():
|
||||
"""优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。
|
||||
|
||||
只读取缓存元数据,不会为了查询时间额外请求上游。
|
||||
"""
|
||||
from map_cache import shared_map_cache
|
||||
snapshot = shared_map_cache.freshness(request.args.get("type", "3"))
|
||||
if snapshot is not None:
|
||||
response = jsonify({"rtn_code": 0, "data": snapshot})
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone()
|
||||
conn.close()
|
||||
latest = row["latest"] if row else None
|
||||
if not latest:
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}})
|
||||
|
||||
import datetime as dt
|
||||
import sqlite3
|
||||
# recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源
|
||||
try:
|
||||
naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S")
|
||||
latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
|
||||
now = dt.datetime.now(latest_dt.tzinfo)
|
||||
stale = max(0, int((now - latest_dt).total_seconds()))
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": None,
|
||||
"interval_hint": "时间格式异常"}})
|
||||
|
||||
hint = "白天 5-10 分钟 / 夜间 30-60 分钟"
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"latest": str(latest), "stale_seconds": stale, "interval_hint": hint}})
|
||||
|
||||
|
||||
@bp.route("/api/campus/locations")
|
||||
def campus_locations():
|
||||
"""校园地点(单点模型)。
|
||||
|
||||
- kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」;
|
||||
- kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。
|
||||
|
||||
返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。
|
||||
"""
|
||||
from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations
|
||||
result = []
|
||||
for loc in load_locations():
|
||||
item = {
|
||||
"id": loc["id"],
|
||||
"name": loc["name"],
|
||||
"kind": loc.get("kind") or "poi",
|
||||
"latitude": loc.get("latitude"),
|
||||
"longitude": loc.get("longitude"),
|
||||
"radius": loc.get("radius") or (
|
||||
DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None),
|
||||
"bd09": None,
|
||||
}
|
||||
if loc.get("latitude") is not None and loc.get("longitude") is not None:
|
||||
bd = gcj02_to_bd09(loc["longitude"], loc["latitude"])
|
||||
item["bd09"] = {"lat": bd[1], "lng": bd[0]}
|
||||
result.append(item)
|
||||
return jsonify({"rtn_code": 0, "data": result})
|
||||
|
||||
|
||||
# ========== 用户信息 API ==========
|
||||
@bp.route("/api/user/info")
|
||||
def api_user_info():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
|
||||
from wechat import request_with_user_auth
|
||||
token_id, access_token = get_user_auth(user["id"])
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"})
|
||||
|
||||
result = request_with_user_auth(user["id"], "GET", "/user/info")
|
||||
if result.get("rtn_code") != 0:
|
||||
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")})
|
||||
|
||||
data = result.get("data", {})
|
||||
non_deal = data.get("nonDealOrder")
|
||||
true_name = ""
|
||||
account = data.get("account", {})
|
||||
if isinstance(account, str):
|
||||
try:
|
||||
account = json.loads(account)
|
||||
except Exception:
|
||||
account = {}
|
||||
true_name = account.get("trueName", "") if isinstance(account, dict) else ""
|
||||
|
||||
out_money = data.get("bus_account", {}).get("outMoneyBus", 0)
|
||||
save_money = data.get("bus_account", {}).get("saveMoneyBus", 0)
|
||||
|
||||
return jsonify({
|
||||
"rtn_code": 0, "has_auth": True,
|
||||
"data": {
|
||||
"true_name": true_name, "out_money": out_money,
|
||||
"save_money": save_money, "has_auth": True,
|
||||
"nonDealOrder": non_deal,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
# ========== 首页路由 ==========
|
||||
MAP_ASSETS = (
|
||||
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
|
||||
"js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
|
||||
"js/settings-pages.js", "js/map.js",
|
||||
)
|
||||
|
||||
|
||||
def _map_asset_version():
|
||||
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
|
||||
digest = hashlib.sha256()
|
||||
for filename in MAP_ASSETS:
|
||||
digest.update(filename.encode())
|
||||
try:
|
||||
digest.update((Path(current_app.static_folder) / filename).read_bytes())
|
||||
except FileNotFoundError:
|
||||
digest.update(b"missing")
|
||||
return digest.hexdigest()[:16]
|
||||
|
||||
|
||||
@bp.route("/")
|
||||
def index():
|
||||
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/analysis.html")
|
||||
def analysis_page():
|
||||
return render_template("analysis.html")
|
||||
|
||||
|
||||
@bp.route("/ring_progress.html")
|
||||
def ring_progress():
|
||||
return render_template("ring_progress.html")
|
||||
+1493
File diff suppressed because it is too large
Load Diff
+930
@@ -0,0 +1,930 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""共享电动车路由 — 申请/接受/权限/解绑/共享开锁与还车"""
|
||||
import datetime as dt
|
||||
import random
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from functools import wraps
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from db import get_db, get_user_auth, get_user_display_name, get_user_rental_settings
|
||||
from routes.auth import get_current_user
|
||||
from wechat import request_with_user_auth
|
||||
|
||||
bp = Blueprint("share", __name__)
|
||||
|
||||
_shared_return_locks = {}
|
||||
_shared_return_locks_guard = threading.Lock()
|
||||
|
||||
DEFAULT_DAILY_LIMIT = 3
|
||||
DEFAULT_REQUIRE_CARD = 1
|
||||
DEFAULT_CARD_MIN_TIMES = 1
|
||||
|
||||
|
||||
def _partner_display(share_or_none, fallback_email):
|
||||
return (share_or_none or {}).get("owner_remark") or fallback_email
|
||||
|
||||
|
||||
def _serialize_shared_return(func):
|
||||
"""同一共享订单的车主/骑行者还车请求串行执行。"""
|
||||
@wraps(func)
|
||||
def wrapped(*args, **kwargs):
|
||||
data = request.get_json(silent=True) or {}
|
||||
key = str(data.get("order_id") or data.get("rental_id") or "missing")
|
||||
with _shared_return_locks_guard:
|
||||
lock = _shared_return_locks.setdefault(key, threading.Lock())
|
||||
with lock:
|
||||
return func(*args, **kwargs)
|
||||
return wrapped
|
||||
|
||||
|
||||
def _beijing_now():
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
return dt.datetime.now(tz)
|
||||
|
||||
|
||||
def _today_str():
|
||||
return _beijing_now().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _upstream_order_finished(user_id: int, order_id) -> bool:
|
||||
"""在还车调用响应不明确时,以用户真实订单状态做二次确认。"""
|
||||
result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||||
if result.get("rtn_code") != 0:
|
||||
return False
|
||||
non_deal = (result.get("data") or {}).get("nonDealOrder")
|
||||
if not non_deal or not non_deal.get("order_id"):
|
||||
return True
|
||||
if str(non_deal.get("order_id")) != str(order_id):
|
||||
return True
|
||||
return str(non_deal.get("status")) != "2"
|
||||
|
||||
|
||||
def _user_email(user_id: int):
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT email FROM users WHERE id = ?", (user_id,))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
return row["email"] if row else None
|
||||
|
||||
|
||||
def _find_share(owner_user_id: int, rider_user_id: int):
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT * FROM shares
|
||||
WHERE owner_user_id = ? AND rider_user_id = ? AND status = 'active'
|
||||
LIMIT 1
|
||||
""", (owner_user_id, rider_user_id))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def _get_share_by_id(share_id: int):
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM shares WHERE id = ?", (share_id,))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def _viewer_remark(share: dict, viewer_user_id: int) -> str:
|
||||
"""返回 viewer 为对方(partner)起的私密备注(昵称);未设置为空串。
|
||||
备注私有:仅本人可见,起名者对另一方的称呼。
|
||||
- 共享方(owner)给用车方(rider)起的备注存 owner_remark
|
||||
- 用车方(rider)给共享方(owner)起的备注存 rider_remark"""
|
||||
if not share:
|
||||
return ""
|
||||
if share.get("owner_user_id") == viewer_user_id:
|
||||
return share.get("owner_remark") or ""
|
||||
if share.get("rider_user_id") == viewer_user_id:
|
||||
return share.get("rider_remark") or ""
|
||||
return ""
|
||||
|
||||
|
||||
def _get_usage(owner_user_id: int, rider_user_id: int, date_str: str):
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT used_count FROM share_usage
|
||||
WHERE owner_user_id = ? AND rider_user_id = ? AND use_date = ?
|
||||
""", (owner_user_id, rider_user_id, date_str))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
return row["used_count"] if row else 0
|
||||
|
||||
|
||||
def _inc_usage(owner_user_id: int, rider_user_id: int, date_str: str):
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
INSERT INTO share_usage (owner_user_id, rider_user_id, use_date, used_count)
|
||||
VALUES (?, ?, ?, 1)
|
||||
ON CONFLICT(owner_user_id, rider_user_id, use_date)
|
||||
DO UPDATE SET used_count = used_count + 1, updated_at = CURRENT_TIMESTAMP
|
||||
""", (owner_user_id, rider_user_id, date_str))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def _owner_card_status(owner_user_id: int):
|
||||
"""读取共享者(owner)微信优惠卡实时状态。
|
||||
返回 (known, has_card, max_remain, msg)
|
||||
known=False 表示读取失败;max_remain=None 表示无限次"""
|
||||
try:
|
||||
res = request_with_user_auth(owner_user_id, "GET", "/user/packages", _silent=True)
|
||||
except Exception:
|
||||
return False, False, None, "无法确认优惠卡状态"
|
||||
if not res or res.get("rtn_code") != 0:
|
||||
return False, False, None, "无法确认优惠卡状态"
|
||||
pkgs = ((res.get("data") or {}).get("bike_packages")) or []
|
||||
nums = []
|
||||
for p in pkgs:
|
||||
rt = p.get("remainTimes")
|
||||
if rt is None or str(rt).strip() in ("", "None", "null"):
|
||||
nums.append(None) # 无限次
|
||||
continue
|
||||
try:
|
||||
nums.append(int(float(rt)))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if not nums:
|
||||
return True, False, 0, "共享者没有优惠卡"
|
||||
has_inf = any(x is None for x in nums)
|
||||
mx = max((x for x in nums if x is not None), default=0)
|
||||
return True, True, (None if has_inf else mx), ""
|
||||
|
||||
|
||||
def _share_card_block(share: dict, card_status) -> str:
|
||||
"""返回卡规则拦截原因;'' 表示通过。card_status=(known,has_card,max_remain,msg)"""
|
||||
if not share.get("require_card"):
|
||||
return ""
|
||||
known, has_card, max_remain, msg = card_status
|
||||
if not known:
|
||||
return msg or "无法确认优惠卡状态"
|
||||
if not has_card:
|
||||
return "共享者没有优惠卡"
|
||||
need = share.get("card_min_times") or 0
|
||||
if need > 0 and max_remain is not None and max_remain < need:
|
||||
return f"共享者优惠卡剩余不足({max_remain}次 < {need}次)"
|
||||
return ""
|
||||
|
||||
|
||||
def _owner_has_active_order(owner_user_id: int):
|
||||
"""共享者账号当前是否已有在用订单(自己骑或正被某个被共享者在用)"""
|
||||
now_bj = _beijing_now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT id FROM rentals
|
||||
WHERE user_id = ? AND expired = 0 AND end_time > ?
|
||||
LIMIT 1
|
||||
""", (owner_user_id, now_bj))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
return row is not None
|
||||
|
||||
|
||||
def _share_state(share: dict, rider_user_id: int):
|
||||
"""计算某条共享关系的实时状态(骑行者视角)"""
|
||||
used = _get_usage(share["owner_user_id"], rider_user_id, _today_str())
|
||||
limit = share.get("daily_limit") or 0
|
||||
remain = max(0, limit - used)
|
||||
known, has_card, max_remain, msg = _owner_card_status(share["owner_user_id"])
|
||||
card_block = _share_card_block(share, (known, has_card, max_remain, msg))
|
||||
busy = _owner_has_active_order(share["owner_user_id"])
|
||||
reasons = []
|
||||
if busy:
|
||||
reasons.append("正在使用中,暂无法代开锁")
|
||||
if not busy and remain <= 0:
|
||||
reasons.append("今日次数已用完")
|
||||
if not busy and card_block:
|
||||
reasons.append(card_block)
|
||||
can_use = (not busy) and remain > 0 and not card_block
|
||||
return {
|
||||
"used_today": used,
|
||||
"daily_limit": limit,
|
||||
"remaining_today": remain,
|
||||
"card_block": card_block,
|
||||
"busy": busy,
|
||||
"reasons": reasons,
|
||||
"can_use": can_use,
|
||||
}
|
||||
|
||||
|
||||
# ========== 申请 / 接受 ==========
|
||||
|
||||
@bp.route("/api/share/request", methods=["POST"])
|
||||
def share_request():
|
||||
"""骑行者发起共享申请:输入共享者(车主)邮箱"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json() or {}
|
||||
to_email = str(data.get("to_email", "")).strip().lower()
|
||||
if not to_email:
|
||||
return jsonify({"rtn_code": 400, "message": "请输入对方邮箱"})
|
||||
if to_email == user["email"].lower():
|
||||
return jsonify({"rtn_code": 400, "message": "不能申请共享给自己"})
|
||||
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id FROM users WHERE email = ?", (to_email,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": "对方账号不存在"})
|
||||
to_user_id = row["id"]
|
||||
conn.close()
|
||||
|
||||
if _find_share(to_user_id, user["id"]):
|
||||
return jsonify({"rtn_code": 400, "message": "对方已经共享给你了"})
|
||||
if _find_share(user["id"], to_user_id):
|
||||
return jsonify({"rtn_code": 400, "message": "你已共享给对方,无需申请"})
|
||||
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT id, status FROM share_requests
|
||||
WHERE from_user_id = ? AND to_user_id = ?
|
||||
ORDER BY id DESC LIMIT 1
|
||||
""", (user["id"], to_user_id))
|
||||
exist = cur.fetchone()
|
||||
if exist:
|
||||
if exist["status"] == "pending":
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "已发送申请,等待对方接受"})
|
||||
# rejected / cancelled → 允许重新发起
|
||||
cur.execute("""
|
||||
UPDATE share_requests SET status = 'pending', updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
""", (exist["id"],))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "已重新发送申请"})
|
||||
|
||||
cur.execute("""
|
||||
INSERT INTO share_requests (from_user_id, to_user_id, status)
|
||||
VALUES (?, ?, 'pending')
|
||||
""", (user["id"], to_user_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
# 离线通知:给车主发一封「有人申请共享」邮件(线程内发送,不阻塞响应)
|
||||
try:
|
||||
from rental_mail import send_share_request_email
|
||||
from_name = get_user_display_name(user["id"])
|
||||
threading.Thread(
|
||||
target=send_share_request_email,
|
||||
args=(to_user_id, from_name, user["email"]),
|
||||
daemon=True,
|
||||
).start()
|
||||
except Exception as exc:
|
||||
print(f"[共享申请] 通知邮件调度失败: {exc}")
|
||||
return jsonify({"rtn_code": 0, "message": "共享申请已发送,等待对方接受"})
|
||||
|
||||
|
||||
@bp.route("/api/share/pending", methods=["GET"])
|
||||
def share_pending():
|
||||
"""车主视角:待处理的共享申请列表"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT sr.id, sr.from_user_id, sr.status, sr.created_at, u.email AS from_email
|
||||
FROM share_requests sr
|
||||
JOIN users u ON u.id = sr.from_user_id
|
||||
WHERE sr.to_user_id = ? AND sr.status = 'pending'
|
||||
ORDER BY sr.id ASC
|
||||
""", (user["id"],))
|
||||
rows = [dict(r) for r in cur.fetchall()]
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "data": rows})
|
||||
|
||||
|
||||
@bp.route("/api/share/respond", methods=["POST"])
|
||||
def share_respond():
|
||||
"""车主接受/拒绝共享申请。接受后立即建立共享(默认权限)"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json() or {}
|
||||
req_id = data.get("request_id")
|
||||
accept = bool(data.get("accept"))
|
||||
if not req_id:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少 request_id"})
|
||||
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM share_requests WHERE id = ? AND to_user_id = ?",
|
||||
(req_id, user["id"]))
|
||||
req = cur.fetchone()
|
||||
if not req:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 404, "message": "申请不存在"})
|
||||
rider_id = req["from_user_id"]
|
||||
|
||||
if not accept:
|
||||
cur.execute("UPDATE share_requests SET status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?", (req_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "已拒绝"})
|
||||
|
||||
# 接受:检查/建立共享关系
|
||||
cur.execute("SELECT * FROM shares WHERE owner_user_id = ? AND rider_user_id = ?",
|
||||
(user["id"], rider_id))
|
||||
share = cur.fetchone()
|
||||
if share:
|
||||
if share["status"] == "active":
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": "共享关系已存在"})
|
||||
cur.execute("""
|
||||
UPDATE shares SET status = 'active', daily_limit = ?, require_card = ?, card_min_times = ?,
|
||||
unbound_by = NULL, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
""", (DEFAULT_DAILY_LIMIT, DEFAULT_REQUIRE_CARD, DEFAULT_CARD_MIN_TIMES, share["id"]))
|
||||
share_id = share["id"]
|
||||
else:
|
||||
cur.execute("""
|
||||
INSERT INTO shares (owner_user_id, rider_user_id, daily_limit, require_card, card_min_times, status)
|
||||
VALUES (?, ?, ?, ?, ?, 'active')
|
||||
""", (user["id"], rider_id, DEFAULT_DAILY_LIMIT, DEFAULT_REQUIRE_CARD, DEFAULT_CARD_MIN_TIMES))
|
||||
share_id = cur.lastrowid
|
||||
|
||||
cur.execute("UPDATE share_requests SET status = 'accepted', updated_at = CURRENT_TIMESTAMP WHERE id = ?", (req_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
rider_email = _user_email(rider_id)
|
||||
return jsonify({"rtn_code": 0, "message": "已接受", "data": {
|
||||
"share_id": share_id, "rider_email": rider_email,
|
||||
"daily_limit": DEFAULT_DAILY_LIMIT, "require_card": DEFAULT_REQUIRE_CARD,
|
||||
"card_min_times": DEFAULT_CARD_MIN_TIMES,
|
||||
}})
|
||||
|
||||
|
||||
# ========== 权限管理 / 解绑 ==========
|
||||
|
||||
@bp.route("/api/share/config", methods=["POST"])
|
||||
def share_config():
|
||||
"""车主修改共享权限(限双方任意可解绑)"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json() or {}
|
||||
share_id = data.get("share_id")
|
||||
share = _get_share_by_id(share_id) if share_id else None
|
||||
if not share:
|
||||
return jsonify({"rtn_code": 404, "message": "共享关系不存在"})
|
||||
if share["owner_user_id"] != user["id"]:
|
||||
return jsonify({"rtn_code": 403, "message": "只有共享者可以修改权限"})
|
||||
|
||||
try:
|
||||
daily_limit = max(0, min(99, int(data.get("daily_limit", share["daily_limit"]))))
|
||||
except (TypeError, ValueError):
|
||||
daily_limit = share["daily_limit"]
|
||||
require_card = 1 if data.get("require_card", bool(share["require_card"])) in (True, 1, "1", "true") else 0
|
||||
try:
|
||||
card_min_times = max(0, min(999, int(data.get("card_min_times", share["card_min_times"]))))
|
||||
except (TypeError, ValueError):
|
||||
card_min_times = share["card_min_times"]
|
||||
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
UPDATE shares SET daily_limit = ?, require_card = ?, card_min_times = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
""", (daily_limit, require_card, card_min_times, share_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "权限已更新"})
|
||||
|
||||
|
||||
@bp.route("/api/share/unbind", methods=["POST"])
|
||||
def share_unbind():
|
||||
"""任一方解绑共享关系"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json() or {}
|
||||
share_id = data.get("share_id")
|
||||
share = _get_share_by_id(share_id) if share_id else None
|
||||
if not share:
|
||||
return jsonify({"rtn_code": 404, "message": "共享关系不存在"})
|
||||
if user["id"] not in (share["owner_user_id"], share["rider_user_id"]):
|
||||
return jsonify({"rtn_code": 403, "message": "无权操作"})
|
||||
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
UPDATE shares SET status = 'unbound', unbound_by = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
""", (user["id"], share_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "已解绑"})
|
||||
|
||||
|
||||
@bp.route("/api/share/remark", methods=["POST"])
|
||||
def share_remark():
|
||||
"""任一方(共享方/用车方)给对方(partner)设置私密备注(昵称),仅本人可见。
|
||||
- 共享方(owner)设置 → owner_remark(owner 侧显示)
|
||||
- 用车方(rider)设置 → rider_remark(rider 侧显示)
|
||||
remark 传空串可清除备注。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json() or {}
|
||||
share_id = data.get("share_id")
|
||||
remark = str(data.get("remark", "")).strip()
|
||||
share = _get_share_by_id(share_id) if share_id else None
|
||||
if not share:
|
||||
return jsonify({"rtn_code": 404, "message": "共享关系不存在"})
|
||||
if user["id"] not in (share["owner_user_id"], share["rider_user_id"]):
|
||||
return jsonify({"rtn_code": 403, "message": "无权操作"})
|
||||
if len(remark) > 50:
|
||||
return jsonify({"rtn_code": 400, "message": "备注最多50字"})
|
||||
is_owner = share["owner_user_id"] == user["id"]
|
||||
col = "owner_remark" if is_owner else "rider_remark"
|
||||
partner_id = share["rider_user_id"] if is_owner else share["owner_user_id"]
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(f"UPDATE shares SET {col} = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(remark or None, share_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0,
|
||||
"message": "备注已保存" if remark else "备注已清除",
|
||||
"data": {"share_id": share_id, "remark": remark,
|
||||
"partner_email": _user_email(partner_id)}})
|
||||
|
||||
|
||||
# ========== 列表 ==========
|
||||
|
||||
@bp.route("/api/share/list", methods=["GET"])
|
||||
def share_list():
|
||||
"""双tab数据:可使用的(别人共享给我) / 我共享的(我共享给别人)"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
me = user["id"]
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
|
||||
# 可使用的:owner 共享给我
|
||||
cur.execute("""
|
||||
SELECT s.*, u.email AS owner_email FROM shares s
|
||||
JOIN users u ON u.id = s.owner_user_id
|
||||
WHERE s.rider_user_id = ? AND s.status = 'active'
|
||||
ORDER BY s.id DESC
|
||||
""", (me,))
|
||||
usable_rows = [dict(r) for r in cur.fetchall()]
|
||||
|
||||
# 我共享的:我共享给 rider
|
||||
cur.execute("""
|
||||
SELECT s.*, u.email AS rider_email FROM shares s
|
||||
JOIN users u ON u.id = s.rider_user_id
|
||||
WHERE s.owner_user_id = ? AND s.status = 'active'
|
||||
ORDER BY s.id DESC
|
||||
""", (me,))
|
||||
shared_rows = [dict(r) for r in cur.fetchall()]
|
||||
conn.close()
|
||||
|
||||
usable = []
|
||||
for s in usable_rows:
|
||||
st = _share_state(s, me)
|
||||
usable.append({
|
||||
"share_id": s["id"],
|
||||
"owner_user_id": s["owner_user_id"],
|
||||
"owner_email": s["owner_email"],
|
||||
"owner_name": get_user_display_name(s["owner_user_id"]),
|
||||
"remark": s.get("rider_remark") or "",
|
||||
"daily_limit": s["daily_limit"],
|
||||
"require_card": s["require_card"],
|
||||
"card_min_times": s["card_min_times"],
|
||||
"used_today": st["used_today"],
|
||||
"remaining_today": st["remaining_today"],
|
||||
"card_block": st["card_block"],
|
||||
"reasons": st["reasons"],
|
||||
"can_use": st["can_use"],
|
||||
})
|
||||
|
||||
shared = []
|
||||
for s in shared_rows:
|
||||
rider_id = s["rider_user_id"]
|
||||
st = _share_state(s, rider_id)
|
||||
shared.append({
|
||||
"share_id": s["id"],
|
||||
"rider_user_id": rider_id,
|
||||
"rider_email": s["rider_email"],
|
||||
"rider_name": get_user_display_name(rider_id),
|
||||
"remark": s.get("owner_remark") or "",
|
||||
"daily_limit": s["daily_limit"],
|
||||
"require_card": s["require_card"],
|
||||
"card_min_times": s["card_min_times"],
|
||||
"rider_used_today": st["used_today"],
|
||||
"rider_remaining_today": st["remaining_today"],
|
||||
})
|
||||
|
||||
return jsonify({"rtn_code": 0, "data": {"usable": usable, "shared": shared}})
|
||||
|
||||
|
||||
@bp.route("/api/share/sources", methods=["GET"])
|
||||
def share_sources():
|
||||
"""开锁弹窗用:列出我(骑行者)可用的共享者;show_unavailable=1 时包含次数为0的"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
me = user["id"]
|
||||
show_all = request.args.get("show_unavailable") == "1"
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT s.*, u.email AS owner_email FROM shares s
|
||||
JOIN users u ON u.id = s.owner_user_id
|
||||
WHERE s.rider_user_id = ? AND s.status = 'active'
|
||||
ORDER BY s.id DESC
|
||||
""", (me,))
|
||||
rows = [dict(r) for r in cur.fetchall()]
|
||||
conn.close()
|
||||
|
||||
sources, hidden = [], 0
|
||||
for s in rows:
|
||||
st = _share_state(s, me)
|
||||
item = {
|
||||
"share_id": s["id"],
|
||||
"owner_user_id": s["owner_user_id"],
|
||||
"owner_email": s["owner_email"],
|
||||
"owner_name": get_user_display_name(s["owner_user_id"]),
|
||||
"remark": s.get("rider_remark") or "",
|
||||
"remaining_today": st["remaining_today"],
|
||||
"daily_limit": s["daily_limit"],
|
||||
"card_block": st["card_block"],
|
||||
"busy": st["busy"],
|
||||
"reasons": st["reasons"],
|
||||
"can_use": st["can_use"],
|
||||
}
|
||||
if item["can_use"]:
|
||||
sources.append(item)
|
||||
elif st["busy"]:
|
||||
# 车主/其他人在使用中:显示出来(置灰提示),不归入"隐藏不可用"
|
||||
sources.append(item)
|
||||
else:
|
||||
hidden += 1
|
||||
if show_all:
|
||||
sources.append(item)
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"sources": sources, "hidden_count": hidden, "has_any": bool(sources or hidden)}})
|
||||
|
||||
|
||||
@bp.route("/api/share/active", methods=["GET"])
|
||||
def share_active():
|
||||
"""横幅用:当前与共享相关的在用车辆(我是车主共享出去/我是骑行者正在用)"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
me = user["id"]
|
||||
from timer import _get_remaining_seconds
|
||||
now_bj = _beijing_now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT r.*, u.email AS partner_email FROM rentals r
|
||||
JOIN users u ON u.id = CASE WHEN r.user_id = ? THEN r.rider_user_id ELSE r.user_id END
|
||||
WHERE ((r.user_id = ? AND r.rider_user_id IS NOT NULL AND r.rider_user_id != ?)
|
||||
OR r.rider_user_id = ?)
|
||||
AND r.expired = 0 AND r.end_time > ?
|
||||
ORDER BY r.id DESC
|
||||
""", (me, me, me, me, now_bj))
|
||||
rows = [dict(r) for r in cur.fetchall()]
|
||||
conn.close()
|
||||
|
||||
result = []
|
||||
# 只去掉共享记录表内同一个上游订单的历史重复行;不会与骑行者
|
||||
# 自己账号的普通/待支付订单合并,二者应在前端同时展示。
|
||||
seen_orders = set()
|
||||
for r in rows:
|
||||
order_key = str(r.get("order_id") or r["id"])
|
||||
if order_key in seen_orders:
|
||||
continue
|
||||
seen_orders.add(order_key)
|
||||
try:
|
||||
remain = _get_remaining_seconds(r)
|
||||
except Exception:
|
||||
remain = 0
|
||||
if remain <= 0:
|
||||
continue
|
||||
# 取该对(owner, rider)的私密备注:仅显示 viewer(me) 给 partner 起的备注
|
||||
is_owner = r["user_id"] == me
|
||||
partner_user_id = r["rider_user_id"] if is_owner else r["user_id"]
|
||||
remark = ""
|
||||
try:
|
||||
c2 = get_db()
|
||||
cu2 = c2.cursor()
|
||||
cu2.execute("""
|
||||
SELECT owner_remark, rider_remark FROM shares
|
||||
WHERE owner_user_id = ? AND rider_user_id = ?
|
||||
ORDER BY id DESC LIMIT 1
|
||||
""", (r["user_id"], r["rider_user_id"]))
|
||||
srow = cu2.fetchone()
|
||||
c2.close()
|
||||
if srow:
|
||||
remark = (srow["owner_remark"] or "") if is_owner else (srow["rider_remark"] or "")
|
||||
except Exception:
|
||||
remark = ""
|
||||
result.append({
|
||||
"rental_id": r["id"],
|
||||
"order_id": r.get("order_id") or r["id"],
|
||||
"bike_code": r["bike_code"],
|
||||
"role": "owner" if is_owner else "rider",
|
||||
"partner_email": r["partner_email"],
|
||||
"partner_name": get_user_display_name(partner_user_id),
|
||||
"remark": remark,
|
||||
"remaining_seconds": remain,
|
||||
"end_time": r["end_time"],
|
||||
})
|
||||
return jsonify({"rtn_code": 0, "data": result})
|
||||
|
||||
|
||||
# ========== 共享开锁 / 还车 ==========
|
||||
|
||||
@bp.route("/api/order/shared_unlock", methods=["POST"])
|
||||
def shared_unlock():
|
||||
"""骑行者用共享者的凭据开锁(真实后端)"""
|
||||
rider = get_current_user()
|
||||
if not rider:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json() or {}
|
||||
code = str(data.get("code", "")).strip()
|
||||
owner_user_id = data.get("owner_user_id")
|
||||
if not code:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少车辆编码"})
|
||||
if not owner_user_id:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少共享者"})
|
||||
try:
|
||||
owner_user_id = int(owner_user_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"rtn_code": 400, "message": "共享者参数错误"})
|
||||
|
||||
share = _find_share(owner_user_id, rider["id"])
|
||||
if not share:
|
||||
return jsonify({"rtn_code": 400, "message": "共享关系不存在或已解绑"})
|
||||
|
||||
# 1. 共享者凭据
|
||||
token_id, access_token = get_user_auth(owner_user_id)
|
||||
if not token_id:
|
||||
return jsonify({"rtn_code": 400, "message": "共享者未配置微信凭据"})
|
||||
|
||||
# 2. 并发检查:同一 wx 账号同时只能有一个在用订单
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
now_bj = _beijing_now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
cur.execute("""
|
||||
SELECT * FROM rentals WHERE user_id = ? AND expired = 0 AND end_time > ?
|
||||
ORDER BY id DESC LIMIT 1
|
||||
""", (owner_user_id, now_bj))
|
||||
active_rental = cur.fetchone()
|
||||
if active_rental:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": "共享者/车辆正在使用中,暂无法代开锁"})
|
||||
conn.close()
|
||||
|
||||
# 3. 次数限制
|
||||
st = _share_state(share, rider["id"])
|
||||
if not st["can_use"]:
|
||||
msg = ";".join(st["reasons"]) or "当前不可用"
|
||||
return jsonify({"rtn_code": 400, "message": f"共享使用被限制:{msg}"})
|
||||
|
||||
owner_email = _user_email(owner_user_id)
|
||||
rider_name = get_user_display_name(rider["id"])
|
||||
print(f"[共享开锁] rider={rider['email']} uses owner={owner_email}, code={code}")
|
||||
|
||||
# 4. 真实后端:扫码→下单→开锁(全部使用 owner 凭据)
|
||||
bike_result = request_with_user_auth(owner_user_id, "POST", "/project/bicycle",
|
||||
data={"code": code}, _silent=True)
|
||||
if bike_result.get("rtn_code") != 0:
|
||||
return jsonify({"rtn_code": bike_result.get("rtn_code", 500),
|
||||
"message": bike_result.get("message", "获取车辆信息失败")})
|
||||
|
||||
# 用实时地图坐标(+抖动)作下单起点:优先 /project/map 抓该车当前坐标
|
||||
from routes.rental import _fetch_live_bike_coord, _near_coord
|
||||
bd = bike_result.get("data") or {}
|
||||
live = _fetch_live_bike_coord(owner_user_id, code, bd.get("type"))
|
||||
if live:
|
||||
latitude, longitude = _near_coord(live[0], live[1])
|
||||
else:
|
||||
latitude, longitude = _near_coord(
|
||||
bd.get("latitude", 36.67), bd.get("longitude", 116.98)
|
||||
)
|
||||
|
||||
order_result = request_with_user_auth(
|
||||
owner_user_id, "POST", "/record/order",
|
||||
data={"code": code, "start_longitude": longitude, "start_latitude": latitude},
|
||||
_silent=True)
|
||||
if order_result.get("rtn_code") != 0 or not (order_result.get("data") or {}).get("order_id"):
|
||||
return jsonify({"rtn_code": order_result.get("rtn_code", 500),
|
||||
"message": order_result.get("message", "创建订单失败")})
|
||||
|
||||
order_id = order_result["data"]["order_id"]
|
||||
open_result = request_with_user_auth(owner_user_id, "POST", "/record/qrOrder",
|
||||
data={"order_id": order_id}, _silent=True)
|
||||
if open_result.get("rtn_code") != 0:
|
||||
return jsonify({"rtn_code": open_result.get("rtn_code", 500),
|
||||
"message": open_result.get("message", "开锁失败"),
|
||||
"order_id": order_id})
|
||||
|
||||
# 5. 本地记录 + 计时器 + 使用次数
|
||||
duration = get_user_rental_settings(rider["id"])["rental_duration_minutes"]
|
||||
start_time = _beijing_now()
|
||||
end_time = start_time + dt.timedelta(minutes=duration)
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
row_id = None
|
||||
try:
|
||||
cur.execute("""
|
||||
INSERT INTO rentals (id, order_id, bike_code, email, user_id, rider_user_id,
|
||||
start_time, end_time, duration, expired, source)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'shared')
|
||||
""", (int(order_id), order_id, code, owner_email, owner_user_id, rider["id"],
|
||||
start_time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration))
|
||||
row_id = int(order_id)
|
||||
except sqlite3.IntegrityError:
|
||||
# id 与历史行冲突(极少数情况):改用自增 id,order_id 仍记录真实订单号
|
||||
cur.execute("""
|
||||
INSERT INTO rentals (order_id, bike_code, email, user_id, rider_user_id,
|
||||
start_time, end_time, duration, expired, source)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'shared')
|
||||
""", (order_id, code, owner_email, owner_user_id, rider["id"],
|
||||
start_time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration))
|
||||
row_id = cur.lastrowid
|
||||
except Exception as e:
|
||||
print(f"[共享开锁] 本地记录失败: {e}")
|
||||
if row_id:
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
if row_id:
|
||||
from timer import start_rental_timer
|
||||
start_rental_timer(rental_id=row_id, email=owner_email, bike_code=code,
|
||||
duration_minutes=duration, user_id=owner_user_id)
|
||||
_inc_usage(owner_user_id, rider["id"], _today_str())
|
||||
# 回填共享订单起点(GCJ02):走 share 自己的 get_db,保持事务归属一致
|
||||
try:
|
||||
from routes.rental import _set_rental_start
|
||||
conn = get_db()
|
||||
_set_rental_start(conn, row_id, latitude, longitude)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
except Exception as exc:
|
||||
print(f"[共享开锁] 回填起点失败: {exc}")
|
||||
# 车主邮件:昵称(邮箱)已开始使用你的电动车 + 车辆当前位置
|
||||
try:
|
||||
from rental_mail import send_share_started_email
|
||||
threading.Thread(
|
||||
target=send_share_started_email,
|
||||
args=(row_id, owner_user_id, rider["id"], code,
|
||||
latitude, longitude, duration,
|
||||
_get_usage(owner_user_id, rider["id"], _today_str()),
|
||||
share.get("daily_limit") or 0),
|
||||
daemon=True,
|
||||
).start()
|
||||
except Exception as exc:
|
||||
print(f"[共享开锁] 车主通知邮件调度失败: {exc}")
|
||||
|
||||
# 成功提示:rider 侧若给 owner 起过私密备注,则显示该备注(昵称),否则退回邮箱
|
||||
rider_label = (share.get("rider_remark") or "").strip() or owner_email
|
||||
return jsonify({"rtn_code": 0, "message": f"已使用{rider_label}的共享开锁成功",
|
||||
"order_id": order_id, "bike_code": code})
|
||||
|
||||
|
||||
@bp.route("/api/share/return", methods=["POST"])
|
||||
@_serialize_shared_return
|
||||
def share_return():
|
||||
"""共享还车:车主或骑行者都可还(使用 owner 凭据的真实还车)"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json() or {}
|
||||
order_id = data.get("order_id") or data.get("rental_id")
|
||||
latitude = data.get("latitude")
|
||||
longitude = data.get("longitude")
|
||||
if not order_id:
|
||||
return jsonify({"rtn_code": 400, "message": "缺少订单ID"})
|
||||
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM rentals WHERE order_id = ? OR id = ? ORDER BY id DESC LIMIT 1",
|
||||
(order_id, order_id))
|
||||
rental = cur.fetchone()
|
||||
conn.close()
|
||||
if not rental:
|
||||
return jsonify({"rtn_code": 404, "message": "记录不存在"})
|
||||
if user["id"] not in (rental["user_id"], rental["rider_user_id"]):
|
||||
return jsonify({"rtn_code": 403, "message": "无权操作"})
|
||||
# 以 rider_user_id 判定是否为共享订单(不依赖 source,兼容历史遗留行)
|
||||
if not rental["rider_user_id"] or rental["rider_user_id"] == rental["user_id"]:
|
||||
return jsonify({"rtn_code": 400, "message": "该订单不是共享订单"})
|
||||
if rental["expired"]:
|
||||
return jsonify({"rtn_code": 0, "message": "订单已结束,无需重复还车"})
|
||||
|
||||
owner_user_id = rental["user_id"]
|
||||
bike_code = rental["bike_code"]
|
||||
if not latitude or not longitude:
|
||||
latitude, longitude = 36.67, 116.98
|
||||
|
||||
# 真实还车(owner 凭据):checkLocation → 非还车点则就近停车点
|
||||
from routes.rental import _try_card_pay_auto, get_nearest_park_point
|
||||
from timer import _cancel_rental_timers
|
||||
|
||||
check_result = request_with_user_auth(
|
||||
owner_user_id, "POST", "/record/checkLocation",
|
||||
data={"longitude": longitude, "latitude": latitude, "bicycleCode": bike_code},
|
||||
_silent=True)
|
||||
use_nearest = False
|
||||
if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True:
|
||||
nearest = get_nearest_park_point(latitude, longitude)
|
||||
if nearest:
|
||||
latitude = nearest.get("latitude") or nearest.get("lat")
|
||||
longitude = nearest.get("longitude") or nearest.get("lng")
|
||||
use_nearest = True
|
||||
|
||||
upstream_order_id = rental["order_id"] or order_id
|
||||
return_result = request_with_user_auth(
|
||||
owner_user_id, "POST", "/record/return",
|
||||
data={"order_id": int(upstream_order_id) if str(upstream_order_id).isdigit() else upstream_order_id,
|
||||
"longitude": longitude, "latitude": latitude}, _silent=True)
|
||||
|
||||
confirmed_by_status = False
|
||||
if return_result.get("rtn_code") != 0:
|
||||
# 锁车指令可能已经被车辆执行,但 HTTP 响应超时/异常。短暂复查真实订单
|
||||
# 状态;只在上游明确显示不再骑行时按成功处理,避免误报也避免误清理。
|
||||
for attempt in range(4):
|
||||
if attempt:
|
||||
time.sleep(1)
|
||||
if _upstream_order_finished(owner_user_id, upstream_order_id):
|
||||
confirmed_by_status = True
|
||||
break
|
||||
if not confirmed_by_status:
|
||||
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
||||
"message": return_result.get("message", "还车失败")})
|
||||
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT id FROM rentals
|
||||
WHERE id = ? OR (order_id = ? AND user_id = ? AND expired = 0)
|
||||
""", (rental["id"], str(upstream_order_id), owner_user_id))
|
||||
finished_rental_ids = [row["id"] for row in cur.fetchall()]
|
||||
# 回填终点:expired=1 + 实际还车时间 + 终点坐标/位置标签(复用同一连接,
|
||||
# 与 share_return 的其他写库同事务,且测试替身 get_db 也能生效)
|
||||
try:
|
||||
from routes.rental import _set_rental_finished
|
||||
_set_rental_finished(
|
||||
conn, "WHERE order_id = ? AND user_id = ? AND expired = 0",
|
||||
(str(upstream_order_id), owner_user_id), latitude, longitude)
|
||||
except Exception as exc:
|
||||
print(f"[共享还车] 回填终点失败: {exc}")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
for rental_id in finished_rental_ids:
|
||||
_cancel_rental_timers(int(rental_id))
|
||||
|
||||
# 还车后清除订单状态短缓存,避免前端短时间继续显示旧横幅。
|
||||
from routes.rental import _user_info_cache
|
||||
_user_info_cache.pop(owner_user_id, None)
|
||||
|
||||
# 双方邮件:从哪里骑到哪里
|
||||
try:
|
||||
from rental_mail import send_share_returned_email
|
||||
threading.Thread(
|
||||
target=send_share_returned_email,
|
||||
args=(rental["id"], upstream_order_id, owner_user_id,
|
||||
rental["rider_user_id"], bike_code, latitude, longitude),
|
||||
daemon=True,
|
||||
).start()
|
||||
except Exception as exc:
|
||||
print(f"[共享还车] 通知邮件调度失败: {exc}")
|
||||
|
||||
# 真实还车已成功。自动尝试月卡/周卡支付仅作为附加操作,任何异常都不应让已成功的还车被前端判为失败。
|
||||
pay_result = {}
|
||||
try:
|
||||
pay_result = _try_card_pay_auto(owner_user_id, str(upstream_order_id), bike_code) or {}
|
||||
except Exception as e:
|
||||
print(f"[共享还车] 自动卡支付异常(不影响还车结果): {e}")
|
||||
pay_result = {}
|
||||
pay_msg = pay_result.get("message", "")
|
||||
success_message = "还车成功"
|
||||
if confirmed_by_status:
|
||||
success_message += "(已通过订单状态确认)"
|
||||
return jsonify({"rtn_code": 0,
|
||||
"message": success_message + (f",{pay_msg}" if pay_result.get("success") else ""),
|
||||
"used_nearest": use_nearest, "card_pay": pay_result})
|
||||
@@ -0,0 +1,200 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""订阅提醒路由:规则的增删改查(每用户最多 5 条)。
|
||||
|
||||
规则除「停车点 + 星期 + 时间」外,还带自动开锁配置:
|
||||
- kinds:允许车型 small/big/red(小车/大车/红车)
|
||||
- min_electric / max_electric:电量区间
|
||||
- sort_by:electric_desc(默认) / electric_asc / distance_asc
|
||||
- retry_times:被他人抢先时的候选重试次数(1-10,默认 3)
|
||||
"""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from db import get_db
|
||||
from routes.auth import get_current_user
|
||||
import subscribe as sub
|
||||
|
||||
bp = Blueprint("subscribe", __name__)
|
||||
|
||||
|
||||
def _rule_row(row: dict, locations_by_id: dict) -> dict:
|
||||
loc = locations_by_id.get(row.get("location_id"))
|
||||
flt = sub.rule_filters(dict(row))
|
||||
return {
|
||||
"id": row["id"],
|
||||
"location_id": row.get("location_id"),
|
||||
"location_name": loc["name"] if loc else None,
|
||||
"weekday": row["weekday"],
|
||||
"minute_of_day": row["minute_of_day"],
|
||||
"notify_enabled": bool(row["notify_enabled"]),
|
||||
"auto_unlock": bool(row["auto_unlock"]),
|
||||
"enabled": bool(row["enabled"]),
|
||||
"last_fired_on": row.get("last_fired_on") or "",
|
||||
# 自动开锁筛选配置
|
||||
"kinds": flt["kinds"],
|
||||
"min_electric": flt["min_electric"],
|
||||
"max_electric": flt["max_electric"],
|
||||
"sort_by": flt["sort_by"],
|
||||
"retry_times": flt["retry_times"],
|
||||
"sort_by_label": sub.SORT_OPTIONS.get(flt["sort_by"], flt["sort_by"]),
|
||||
"kind_labels": [{"small": "小车", "big": "大车", "red": "红车"}[k]
|
||||
for k in flt["kinds"]],
|
||||
}
|
||||
|
||||
|
||||
@bp.route("/api/subscribe/rules")
|
||||
def rules_list():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
conn = get_db()
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT * FROM subscribe_rules WHERE user_id = ? ORDER BY id",
|
||||
(user["id"],)).fetchall()]
|
||||
conn.close()
|
||||
from campus import load_locations
|
||||
locations_by_id = {l["id"]: l for l in load_locations()}
|
||||
return jsonify({"rtn_code": 0,
|
||||
"data": [_rule_row(r, locations_by_id) for r in rows]})
|
||||
|
||||
|
||||
@bp.route("/api/subscribe/rules", methods=["POST"])
|
||||
def rules_create():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
if sub.count_user_rules(user["id"]) >= sub.MAX_RULES_PER_USER:
|
||||
return jsonify({"rtn_code": 400,
|
||||
"message": f"最多 {sub.MAX_RULES_PER_USER} 条规则,请先删除不需要的"})
|
||||
try:
|
||||
fields = sub.normalize_rule(request.get_json(silent=True) or {})
|
||||
except ValueError as exc:
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
from campus import get_location
|
||||
loc = get_location(fields["location_id"])
|
||||
if not loc:
|
||||
return jsonify({"rtn_code": 400, "message": "所选停车点不存在(可能已被管理员删除)"})
|
||||
if (loc.get("kind") or "") != "parking":
|
||||
return jsonify({"rtn_code": 400,
|
||||
"message": "订阅只能选择「停车点」(楼/兴趣点只用于起终点归属)"})
|
||||
conn = get_db()
|
||||
conn.execute("""
|
||||
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
||||
notify_enabled, auto_unlock, enabled,
|
||||
kinds, min_electric, max_electric, sort_by, retry_times)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?)
|
||||
""", (user["id"], fields["location_id"], fields["weekday"], fields["minute_of_day"],
|
||||
1 if fields["notify_enabled"] else 0, 1 if fields["auto_unlock"] else 0,
|
||||
fields["kinds"], fields["min_electric"], fields["max_electric"],
|
||||
fields["sort_by"], fields["retry_times"]))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "订阅规则已添加"})
|
||||
|
||||
|
||||
@bp.route("/api/subscribe/rules/<int:rule_id>", methods=["PUT"])
|
||||
def rules_update(rule_id: int):
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
data = request.get_json(silent=True) or {}
|
||||
conn = get_db()
|
||||
row = conn.execute("SELECT * FROM subscribe_rules WHERE id = ? AND user_id = ?",
|
||||
(rule_id, user["id"])).fetchone()
|
||||
if not row:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 404, "message": "规则不存在"})
|
||||
current = dict(row)
|
||||
updates = []
|
||||
params = []
|
||||
|
||||
def _truthy(v):
|
||||
return 1 if v in (True, 1, "1", "true") else 0
|
||||
|
||||
if "enabled" in data:
|
||||
updates.append("enabled = ?")
|
||||
params.append(_truthy(data.get("enabled")))
|
||||
if "notify_enabled" in data:
|
||||
updates.append("notify_enabled = ?")
|
||||
params.append(_truthy(data.get("notify_enabled")))
|
||||
if "auto_unlock" in data:
|
||||
updates.append("auto_unlock = ?")
|
||||
params.append(_truthy(data.get("auto_unlock")))
|
||||
|
||||
# 组合校验:任何一个筛选字段变化时,用「现值 + 新值」整体校验一次
|
||||
filter_keys = ("kinds", "min_electric", "max_electric", "sort_by", "retry_times")
|
||||
if any(k in data for k in filter_keys):
|
||||
flt = sub.rule_filters(current)
|
||||
merged = {
|
||||
"location_id": current.get("location_id"),
|
||||
"weekday": current.get("weekday"),
|
||||
"time": "%02d:%02d" % (int(current.get("minute_of_day") or 0) // 60,
|
||||
int(current.get("minute_of_day") or 0) % 60),
|
||||
"kinds": data.get("kinds", flt["kinds"]),
|
||||
"min_electric": data.get("min_electric", flt["min_electric"]),
|
||||
"max_electric": data.get("max_electric", flt["max_electric"]),
|
||||
"sort_by": data.get("sort_by", flt["sort_by"]),
|
||||
"retry_times": data.get("retry_times", flt["retry_times"]),
|
||||
"notify_enabled": True,
|
||||
"auto_unlock": bool(current.get("auto_unlock")),
|
||||
}
|
||||
try:
|
||||
fields = sub.normalize_rule(merged)
|
||||
except ValueError as exc:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
updates.extend(["kinds = ?", "min_electric = ?", "max_electric = ?",
|
||||
"sort_by = ?", "retry_times = ?"])
|
||||
params.extend([fields["kinds"], fields["min_electric"], fields["max_electric"],
|
||||
fields["sort_by"], fields["retry_times"]])
|
||||
|
||||
if ("time" in data and "weekday" in data) or ("time" in data or "weekday" in data):
|
||||
merged_time = {
|
||||
"location_id": current.get("location_id"),
|
||||
"weekday": data.get("weekday", current.get("weekday")),
|
||||
"time": data.get("time") or "%02d:%02d" % (
|
||||
int(current.get("minute_of_day") or 0) // 60,
|
||||
int(current.get("minute_of_day") or 0) % 60),
|
||||
}
|
||||
try:
|
||||
fields = sub.normalize_rule(merged_time)
|
||||
except ValueError as exc:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
updates.extend(["weekday = ?", "minute_of_day = ?"])
|
||||
params.extend([fields["weekday"], fields["minute_of_day"]])
|
||||
|
||||
if not updates:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": "没有需要更新的字段"})
|
||||
params.extend([rule_id, user["id"]])
|
||||
conn.execute(f"UPDATE subscribe_rules SET {', '.join(updates)} "
|
||||
f"WHERE id = ? AND user_id = ?", params)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "规则已更新"})
|
||||
|
||||
|
||||
@bp.route("/api/subscribe/rules/<int:rule_id>", methods=["DELETE"])
|
||||
def rules_delete(rule_id: int):
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
conn = get_db()
|
||||
conn.execute("DELETE FROM subscribe_rules WHERE id = ? AND user_id = ?",
|
||||
(rule_id, user["id"]))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 0, "message": "规则已删除"})
|
||||
|
||||
|
||||
@bp.route("/api/subscribe/options")
|
||||
def subscribe_options():
|
||||
"""订阅可选项(车型/排序),供前端渲染下拉与说明。"""
|
||||
return jsonify({"rtn_code": 0, "data": {
|
||||
"kinds": [{"key": "small", "label": "小车"},
|
||||
{"key": "big", "label": "大车"},
|
||||
{"key": "red", "label": "红车"}],
|
||||
"sort_by": [{"key": k, "label": v} for k, v in sub.SORT_OPTIONS.items()],
|
||||
"auto_unlock_enabled": sub.AUTO_UNLOCK_ENABLED,
|
||||
}})
|
||||
Reference in New Issue
Block a user