一、审计修复(另一侧完成,我复核通过) - 认证/限流:_client_ip 归一、限流统一走 rate_limit._SlidingTable(超限只淘汰最旧 key, 不再整表 clear 自毁)、每用户会话上限 10 + 过期清理 - 邮件验证码:锁内原子占位 → 锁外发信 → 成功落码,失败回滚冷却(并发不再双发) - 租赁:rentals 部分唯一索引(同 order_id 只允许一行 expired=0,迁移前先查重)、 开锁幂等落库、Timer 代号机制(取消/重排同临界区)、minutes=null 兜底、 自动还车 30s×6 → 1m/2m/5m/10m 退避 - 安全:ring 四接口登录 + 任务归属校验(Bearer 或 ?token=,校验 sessions 表)、 共享还车坐标不再伪造、代开锁 IntegrityError 兜底、token 配置原子写(fsync + 0600) - 入口鉴权:8 个历史/分析接口未登录 401(HTTP 与 rtn_code 同时给)、 analysis.html 带 Bearer + 未登录门 + 截断提示、历史查询 LIMIT 60000 并回传 truncated - UX 四个 P0:计时条出现、真实单走 /api/order/return 而 reminder 走 /api/rental/return、 定位失败不伪造坐标(三选一弹窗)、地图/配置/脚本失败统一落到可自救失败卡片 - 测试:新增 6 个文件 62 例;既有 test_history_30d 只补登录前置 二、我复核时发现并修掉的 7 处 ① email_verify.record_cooldown 的 expires 写成 now,会被 send_code 开头的 _cleanup_locked 整条删掉 —— 任何人发一次验证码就废掉「未注册邮箱」的冷却, 找回密码又能枚举邮箱是否注册。改为活过冷却窗口,并补 3 例测试 ② timer.py 两处落库(自动续租 INSERT、sync 复活 UPDATE)没防新唯一索引: 撞索引抛 IntegrityError 会让巡检线程退出,该单从此没有计时器/自动还车(上游还在计费)。 新增 _active_rental_id_for_order(),捕获后复用存活行 ③ (0,0) 当合法坐标会先发给上游:/record/return 不校验范围,宽松后端会把车"还"在海里。 新增 _coords_usable(),不可用就跳过原始点;候选列表永远丢掉第 0 项 ④ boot_smoke.py 按旧契约要求 200,加鉴权后永远失败 → HTTPError 401 视为「未登录,预期」 ⑤ 自动还车「不放弃」缺绝对上限:加 AUTO_RETURN_GIVE_UP_SECONDS=6h,到点只告警一次并停手 ⑥ 索引谓词 aligned 到查重口径:COALESCE(expired,0)=0,旧定义自动重建 ⑦ 访问日志脱敏:?token= / ?ticket= / ?access_token= 的值替换为 ***(werkzeug + root logger) 否则容器日志里就是明文会话令牌 配套改写 tests/test_rental_dedup.py::test_return_accepts_zero_coordinates → test_return_treats_zero_coordinates_as_missing(原断言把 (0,0) 当合法值发上游) 三、验证 - python -m pytest -q → 234 passed(基线 231,净增 3) - node 5 套 → 44 pass / 0 fail - 14 个 .py ast.parse、node --check dist/app.js → 全部通过 - boot_smoke.py → exit=0;未登录 /api/history/stats、/api/analysis/overview、 /api/ring_progress/* 实测 401,/api/config 200 - 行为级:传 (0,0) 时上游只收到候选点;合法坐标仍先发上报值;唯一索引拦住重复插入
895 lines
34 KiB
Python
895 lines
34 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""数据库模块"""
|
||
import sqlite3
|
||
from pathlib import Path
|
||
|
||
DB_PATH = Path(__file__).parent / "users.db"
|
||
|
||
DEFAULT_RENTAL_SETTINGS = {
|
||
"reminder_enabled": True,
|
||
"reminder_minutes": [5, 3, 0],
|
||
"rental_duration_minutes": 19,
|
||
"auto_return_enabled": True,
|
||
# 总轮次包含首轮;默认 1 保持旧行为。
|
||
"rental_rounds": 1,
|
||
"protect_card": True,
|
||
}
|
||
ALLOWED_REMINDER_MINUTES = (10, 5, 3, 2, 1, 0)
|
||
MIN_RENTAL_ROUNDS = 1
|
||
MAX_RENTAL_ROUNDS = 20
|
||
|
||
|
||
# ========== 跨进程租约(多 worker 选主 / 单任务抢占) ==========
|
||
|
||
import os as _os
|
||
import socket as _socket
|
||
import time as _time
|
||
import uuid as _uuid
|
||
|
||
LEASE_OWNER = f"{_os.getpid()}@{_socket.gethostname()}:{_uuid.uuid4().hex[:6]}"
|
||
|
||
|
||
def acquire_lease(name: str, ttl_seconds: float = 120):
|
||
"""尝试成为某个租约的持有者;已是自己则续期。
|
||
|
||
返回 True=持有 / False=被别的进程持有 / **None=租约表不可用(老库、临时库)**。
|
||
调用方要把 None 当「按单进程处理」,否则老库上所有后台任务会被误拦。
|
||
BEGIN IMMEDIATE 保证「读-判断-写」原子:多进程同时抢只有一个成功。
|
||
"""
|
||
# 测试里用临时库、但租约走的是真实库:给一个显式开关,避免上一轮进程
|
||
# 留下的租约(300 秒)把这一轮的单测全拦掉。
|
||
if _os.environ.get("XBCR_DISABLE_LEASES") == "1":
|
||
return True
|
||
|
||
now = _time.time()
|
||
conn = get_db()
|
||
try:
|
||
conn.execute("BEGIN IMMEDIATE")
|
||
row = conn.execute(
|
||
"SELECT owner, expires_at FROM leases WHERE name = ?", (name,)).fetchone()
|
||
if row and float(row["expires_at"] or 0) > now and row["owner"] != LEASE_OWNER:
|
||
conn.rollback()
|
||
return False
|
||
conn.execute(
|
||
"INSERT INTO leases (name, owner, expires_at) VALUES (?, ?, ?) "
|
||
"ON CONFLICT(name) DO UPDATE SET owner = excluded.owner, "
|
||
"expires_at = excluded.expires_at",
|
||
(name, LEASE_OWNER, now + ttl_seconds))
|
||
conn.commit()
|
||
return True
|
||
except Exception as exc:
|
||
try:
|
||
conn.rollback()
|
||
except Exception:
|
||
pass
|
||
print(f"[租约] 获取 {name} 失败(按单进程处理): {exc}")
|
||
return None
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def release_lease(name: str):
|
||
"""主动释放(进程退出时调用;不释放也会因过期被别人接管)。"""
|
||
conn = get_db()
|
||
try:
|
||
conn.execute("DELETE FROM leases WHERE name = ? AND owner = ?", (name, LEASE_OWNER))
|
||
conn.commit()
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def lease_held_by_me(name: str) -> bool:
|
||
conn = get_db()
|
||
try:
|
||
row = conn.execute(
|
||
"SELECT owner, expires_at FROM leases WHERE name = ?", (name,)).fetchone()
|
||
return bool(row and row["owner"] == LEASE_OWNER
|
||
and float(row["expires_at"] or 0) > _time.time())
|
||
except Exception:
|
||
return False
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def get_db():
|
||
"""获取数据库连接(WAL + 忙等待,避免多线程写入时 database is locked)"""
|
||
conn = sqlite3.connect(str(DB_PATH))
|
||
conn.row_factory = sqlite3.Row
|
||
conn.execute("PRAGMA journal_mode=WAL")
|
||
conn.execute("PRAGMA busy_timeout=5000")
|
||
return conn
|
||
|
||
|
||
def init_db():
|
||
"""初始化数据库"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS users (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
email TEXT UNIQUE NOT NULL,
|
||
password_hash TEXT NOT NULL,
|
||
access_token TEXT,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
reminder_enabled INTEGER NOT NULL DEFAULT 1,
|
||
reminder_minutes TEXT NOT NULL DEFAULT '5,3,0',
|
||
rental_duration_minutes INTEGER NOT NULL DEFAULT 19,
|
||
auto_return_enabled INTEGER NOT NULL DEFAULT 1,
|
||
rental_rounds INTEGER NOT NULL DEFAULT 1,
|
||
protect_card INTEGER NOT NULL DEFAULT 1
|
||
)
|
||
""")
|
||
|
||
# 迁移:老库的 wx_signature 列重命名为 access_token(语义变更:存 accessToken 而非一次性签名)
|
||
try:
|
||
cursor.execute("ALTER TABLE users RENAME COLUMN wx_signature TO access_token")
|
||
except sqlite3.OperationalError:
|
||
pass # 已重命名过或新库
|
||
for col in ["token_id", "access_token"]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE users ADD COLUMN {col} TEXT")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
for col_def in [
|
||
("reminder_enabled", "INTEGER NOT NULL DEFAULT 1"),
|
||
("reminder_minutes", "TEXT NOT NULL DEFAULT '5,3,0'"),
|
||
("rental_duration_minutes", "INTEGER NOT NULL DEFAULT 19"),
|
||
("auto_return_enabled", "INTEGER NOT NULL DEFAULT 1"),
|
||
("rental_rounds", "INTEGER NOT NULL DEFAULT 1"),
|
||
("protect_card", "INTEGER NOT NULL DEFAULT 1"),
|
||
]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE users ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
# 老数据清洗:40 位 hex 是抓包的一次性 hsf-x-signature,不是 accessToken(JWT 以 eyJ 开头),置空
|
||
try:
|
||
cursor.execute("""
|
||
UPDATE users SET access_token = NULL
|
||
WHERE access_token IS NOT NULL
|
||
AND length(access_token) = 40
|
||
AND access_token NOT LIKE 'eyJ%'
|
||
""")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# 老库的 token_id 列带 DEFAULT '1291378'(建表时留下的),注册时没写这一列的用户
|
||
# 会被灌成这个假凭据 → 巡检拿它去探测、必被上游 102001 拒绝 →
|
||
# 全站收到「凭据已过期」误报邮件。这里启动时自动清掉:值等于该默认值且没有
|
||
# access_token 的,一律视为「未配置凭据」。
|
||
# 新库/新注册都不会再写入默认值(auth 注册显式传 NULL)。
|
||
try:
|
||
cursor.execute("""
|
||
UPDATE users SET token_id = NULL
|
||
WHERE token_id = '1291378'
|
||
AND (access_token IS NULL OR access_token = '')
|
||
""")
|
||
if cursor.rowcount:
|
||
print(f"[迁移] 清理 {cursor.rowcount} 个注册遗留的默认 token_id(1291378)")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# 跨进程租约:多 worker 部署时用来选主(只有一个进程跑后台线程/采集/调度),
|
||
# 也用来做「同一单只能一个进程处理」的原子抢占。
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS leases (
|
||
name TEXT PRIMARY KEY,
|
||
owner TEXT NOT NULL,
|
||
expires_at REAL NOT NULL
|
||
)
|
||
""")
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS sessions (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
user_id INTEGER NOT NULL,
|
||
token TEXT UNIQUE NOT NULL,
|
||
expires_at TIMESTAMP NOT NULL,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||
)
|
||
""")
|
||
|
||
# 多设备登录:为每台设备记录标识信息(用于“我的 → 登录设备管理”展示与下线)
|
||
for col_def in [("device_name", "TEXT"), ("device_id", "TEXT"),
|
||
("user_agent", "TEXT"), ("last_active", "TIMESTAMP")]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE sessions ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS reminders (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
user_id INTEGER NOT NULL,
|
||
bike_code TEXT NOT NULL,
|
||
email TEXT NOT NULL,
|
||
duration INTEGER NOT NULL,
|
||
start_time TIMESTAMP,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||
)
|
||
""")
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS rentals (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
order_id TEXT,
|
||
bike_code TEXT NOT NULL,
|
||
email TEXT NOT NULL,
|
||
user_id INTEGER,
|
||
start_time TIMESTAMP NOT NULL,
|
||
end_time TIMESTAMP NOT NULL,
|
||
expired INTEGER DEFAULT 0,
|
||
source TEXT DEFAULT 'reminder',
|
||
notified_10 INTEGER DEFAULT 0,
|
||
notified_5 INTEGER DEFAULT 0,
|
||
notified_3 INTEGER DEFAULT 0,
|
||
notified_2 INTEGER DEFAULT 0,
|
||
notified_1 INTEGER DEFAULT 0,
|
||
notified_0 INTEGER DEFAULT 0,
|
||
renewal_round INTEGER NOT NULL DEFAULT 1,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
# 邮件一键还车的能力令牌。数据库只保存 SHA-256 摘要,
|
||
# 邮件中的原始 token 泄漏数据库时不可被反推。
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS rental_return_tokens (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
rental_id INTEGER NOT NULL,
|
||
token_hash TEXT UNIQUE NOT NULL,
|
||
expires_at TIMESTAMP NOT NULL,
|
||
used_at TIMESTAMP,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
FOREIGN KEY (rental_id) REFERENCES rentals(id)
|
||
)
|
||
""")
|
||
cursor.execute("""
|
||
CREATE INDEX IF NOT EXISTS idx_return_tokens_rental
|
||
ON rental_return_tokens(rental_id)
|
||
""")
|
||
|
||
for col in ["duration", "notified_10", "notified_5", "notified_3",
|
||
"notified_2", "notified_1", "notified_0", "user_id",
|
||
"renewal_round"]:
|
||
try:
|
||
if col == "user_id":
|
||
cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER")
|
||
elif col == "renewal_round":
|
||
cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER NOT NULL DEFAULT 1")
|
||
else:
|
||
cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER DEFAULT 0")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# 「同一个 order_id 只允许一行未结束的订单」——客户端双击/重放、上游对同一张单重复
|
||
# 返回同一个 order_id 时,以前会插出两行 rentals(两套计时器、两份提醒、可能重复扣卡)。
|
||
# 应用层在 routes/rental.py::_insert_unlock_rental 里先查重复用,这里再加数据库兜底。
|
||
#
|
||
# 只约束「未结束」的行:expired=1 的历史行、order_id 为空的本地计时单都不受影响,
|
||
# 因此 430 行历史数据(实测 0 组重复)可以直接迁移,且本段可重复执行(幂等)。
|
||
try:
|
||
dup_groups = cursor.execute("""
|
||
SELECT COUNT(*) FROM (
|
||
SELECT order_id FROM rentals
|
||
WHERE order_id IS NOT NULL AND order_id != '' AND COALESCE(expired, 0) = 0
|
||
GROUP BY order_id HAVING COUNT(*) > 1)
|
||
""").fetchone()[0]
|
||
if dup_groups:
|
||
# 老库里已经存在重复的未结束单:不擅自删/改业务数据,只记日志,交给人工核对。
|
||
print(f"[迁移] 发现 {dup_groups} 个 order_id 存在多行未结束订单,"
|
||
f"跳过唯一索引创建(应用层查重仍然生效)")
|
||
else:
|
||
# 谓词要和上面的查重口径一致:旧定义用 `expired = 0`,会把
|
||
# expired IS NULL 的老行排除在唯一约束之外。发现旧定义就重建
|
||
# (能走到这里说明已经确认没有重复,重建是安全的)。
|
||
try:
|
||
row = cursor.execute(
|
||
"SELECT sql FROM sqlite_master WHERE type='index' AND name=?",
|
||
("idx_rentals_active_order",)).fetchone()
|
||
except sqlite3.OperationalError:
|
||
row = None
|
||
existing_sql = (row[0] if row else "") or ""
|
||
if existing_sql and "COALESCE" not in existing_sql.upper():
|
||
cursor.execute("DROP INDEX idx_rentals_active_order")
|
||
print("[迁移] 重建 rentals 未结束订单唯一索引(谓词补 COALESCE)")
|
||
cursor.execute("""
|
||
CREATE UNIQUE INDEX IF NOT EXISTS idx_rentals_active_order
|
||
ON rentals(order_id)
|
||
WHERE order_id IS NOT NULL AND order_id != '' AND COALESCE(expired, 0) = 0
|
||
""")
|
||
except sqlite3.OperationalError as exc:
|
||
print(f"[迁移] rentals 未结束订单唯一索引创建失败(忽略): {exc}")
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS bike_history (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
bike_code TEXT NOT NULL,
|
||
latitude REAL,
|
||
longitude REAL,
|
||
status INTEGER DEFAULT 1,
|
||
state INTEGER DEFAULT 1,
|
||
electric REAL DEFAULT 100,
|
||
recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
# 多进程/多实例采集会重复写同一秒的位置:先去重再建唯一索引,
|
||
# 让 INSERT OR IGNORE 把重复写入挡掉,避免行数 ×N 污染 /api/history 统计。
|
||
try:
|
||
cursor.execute("""
|
||
DELETE FROM bike_history
|
||
WHERE id NOT IN (
|
||
SELECT MIN(id) FROM bike_history GROUP BY bike_code, recorded_at
|
||
)
|
||
""")
|
||
if cursor.rowcount:
|
||
print(f"[迁移] bike_history 去重 {cursor.rowcount} 行")
|
||
cursor.execute("""
|
||
CREATE UNIQUE INDEX IF NOT EXISTS idx_bike_history_code_time
|
||
ON bike_history (bike_code, recorded_at)
|
||
""")
|
||
except sqlite3.OperationalError as exc:
|
||
print(f"[迁移] bike_history 唯一索引创建失败(忽略): {exc}")
|
||
|
||
for col_def in [("state", "INTEGER DEFAULT 1"), ("electric", "REAL DEFAULT 100")]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE bike_history ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# 分析查询均按 bike_code / recorded_at 过滤,无索引会全表扫描
|
||
cursor.execute("""
|
||
CREATE INDEX IF NOT EXISTS idx_history_code_time
|
||
ON bike_history(bike_code, recorded_at)
|
||
""")
|
||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_history_time ON bike_history(recorded_at)")
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS snapshots (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
snapshot_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
total_bikes INTEGER DEFAULT 0,
|
||
available_count INTEGER DEFAULT 0,
|
||
inuse_count INTEGER DEFAULT 0,
|
||
locked_count INTEGER DEFAULT 0,
|
||
reserved_count INTEGER DEFAULT 0,
|
||
low_count INTEGER DEFAULT 0,
|
||
data_json TEXT,
|
||
source TEXT DEFAULT 'web',
|
||
recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
try:
|
||
cursor.execute("ALTER TABLE rentals ADD COLUMN source TEXT DEFAULT 'reminder'")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
try:
|
||
cursor.execute("ALTER TABLE rentals ADD COLUMN order_id TEXT")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
try:
|
||
cursor.execute("ALTER TABLE rentals ADD COLUMN rider_user_id INTEGER")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# 兼容修复:历史遗留的共享订单若 source 未被正确标记,按 rider_user_id 回填
|
||
try:
|
||
cursor.execute("""
|
||
UPDATE rentals SET source = 'shared'
|
||
WHERE rider_user_id IS NOT NULL AND rider_user_id != user_id
|
||
AND (source IS NULL OR source != 'shared')
|
||
""")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 共享电动车 =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS share_requests (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
from_user_id INTEGER NOT NULL,
|
||
to_user_id INTEGER NOT NULL,
|
||
status TEXT NOT NULL DEFAULT 'pending',
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS shares (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
owner_user_id INTEGER NOT NULL,
|
||
rider_user_id INTEGER NOT NULL,
|
||
daily_limit INTEGER NOT NULL DEFAULT 3,
|
||
require_card INTEGER NOT NULL DEFAULT 0,
|
||
card_min_times INTEGER NOT NULL DEFAULT 0,
|
||
status TEXT NOT NULL DEFAULT 'active',
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
unbound_by INTEGER
|
||
)
|
||
""")
|
||
try:
|
||
cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_shares_pair ON shares(owner_user_id, rider_user_id)")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# 共享电动车:双方给对方起的私密昵称备注(微信式给备注)
|
||
# owner_remark = 共享方(owner) 给 用车方(rider) 起的备注(owner 侧显示)
|
||
# rider_remark = 用车方(rider) 给 共享方(owner) 起的备注(rider 侧显示)
|
||
for _col in ["owner_remark", "rider_remark"]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE shares ADD COLUMN {_col} TEXT")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS share_usage (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
owner_user_id INTEGER NOT NULL,
|
||
rider_user_id INTEGER NOT NULL,
|
||
use_date TEXT NOT NULL,
|
||
used_count INTEGER NOT NULL DEFAULT 0,
|
||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
try:
|
||
cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_share_usage_day ON share_usage(owner_user_id, rider_user_id, use_date)")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 注册邀请码(管理员签发,注册时必填并核销) =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS invite_codes (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
code TEXT UNIQUE NOT NULL,
|
||
max_uses INTEGER NOT NULL DEFAULT 1,
|
||
used_count INTEGER NOT NULL DEFAULT 0,
|
||
used_by TEXT NOT NULL DEFAULT '',
|
||
note TEXT NOT NULL DEFAULT '',
|
||
disabled INTEGER NOT NULL DEFAULT 0,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
# ===== 校园地点(教学楼/兴趣点 POI + 停车区) =====
|
||
# 坐标统一存 GCJ02(与上游车辆接口同一坐标系);前端点选得到的是百度 BD09,
|
||
# 入库前先经 coordtransform.bd09togcj02 转换。polygon 为 JSON 数组 [[lat,lng],...]。
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS campus_locations (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name TEXT NOT NULL,
|
||
kind TEXT NOT NULL DEFAULT 'poi',
|
||
latitude REAL,
|
||
longitude REAL,
|
||
radius INTEGER,
|
||
polygon TEXT,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
try:
|
||
cursor.execute("ALTER TABLE campus_locations ADD COLUMN radius INTEGER")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 订单起终点(从哪里骑到哪里)+ 实际还车时间 + 轮次覆盖 =====
|
||
for col_def in [
|
||
("start_latitude", "REAL"), ("start_longitude", "REAL"),
|
||
("end_latitude", "REAL"), ("end_longitude", "REAL"),
|
||
("start_label", "TEXT"), ("end_label", "TEXT"),
|
||
("returned_at", "TIMESTAMP"),
|
||
("rounds_override", "INTEGER"),
|
||
]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 用车订阅规则(定时查看某停车点附近车辆,可选自动开锁) =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS subscribe_rules (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
user_id INTEGER NOT NULL,
|
||
location_id INTEGER,
|
||
weekday INTEGER NOT NULL DEFAULT 0,
|
||
minute_of_day INTEGER NOT NULL DEFAULT 720,
|
||
notify_enabled INTEGER NOT NULL DEFAULT 1,
|
||
auto_unlock INTEGER NOT NULL DEFAULT 0,
|
||
enabled INTEGER NOT NULL DEFAULT 1,
|
||
last_fired_on TEXT NOT NULL DEFAULT '',
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
# 自动开锁的筛选 / 排序 / 重试配置
|
||
for col_def in [
|
||
("kinds", "TEXT NOT NULL DEFAULT 'small,big,red'"), # 允许车型:small/big/red
|
||
("min_electric", "INTEGER NOT NULL DEFAULT 0"), # 电量下限
|
||
("max_electric", "INTEGER NOT NULL DEFAULT 100"), # 电量上限
|
||
("sort_by", "TEXT NOT NULL DEFAULT 'electric_desc'"), # 排序:electric_desc/electric_asc/distance_asc
|
||
("retry_times", "INTEGER NOT NULL DEFAULT 3"), # 被他人抢先时的候选重试次数
|
||
]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE subscribe_rules ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 凭据告警去重(同一凭据同一级别只发一次) =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS credential_alerts (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
target TEXT NOT NULL,
|
||
level TEXT NOT NULL,
|
||
sent_on TEXT NOT NULL,
|
||
sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
UNIQUE(target, level)
|
||
)
|
||
""")
|
||
|
||
# ===== 数据导出直链令牌(1 小时有效,免登录下载) =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS export_tokens (
|
||
token TEXT PRIMARY KEY,
|
||
scope TEXT NOT NULL DEFAULT 'history_csv',
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
expires_at TIMESTAMP NOT NULL
|
||
)
|
||
""")
|
||
|
||
# 用户告警接收邮箱(凭据失效提醒;空则回退账号邮箱)
|
||
try:
|
||
cursor.execute("ALTER TABLE users ADD COLUMN alert_email TEXT")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
|
||
|
||
|
||
def get_user_auth(user_id: int):
|
||
"""获取用户凭据,返回 (token_id, access_token)。
|
||
token_id 必填(上游唯一强校验项);access_token 选填(用于实时计算签名)。"""
|
||
if not user_id:
|
||
return None, None
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT token_id, access_token FROM users WHERE id = ?", (user_id,))
|
||
row = cursor.fetchone()
|
||
conn.close()
|
||
if row and row["token_id"]:
|
||
return row["token_id"], row["access_token"]
|
||
return None, None
|
||
|
||
|
||
def parse_reminder_minutes(value):
|
||
"""解析提醒时间,只保留 UI 支持的节点,去重后降序。"""
|
||
if value is None:
|
||
return list(DEFAULT_RENTAL_SETTINGS["reminder_minutes"])
|
||
if isinstance(value, str):
|
||
raw = [part.strip() for part in value.split(",") if part.strip()]
|
||
elif isinstance(value, (list, tuple, set)):
|
||
raw = list(value)
|
||
else:
|
||
raw = []
|
||
selected = set()
|
||
for item in raw:
|
||
try:
|
||
minute = int(item)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if minute in ALLOWED_REMINDER_MINUTES:
|
||
selected.add(minute)
|
||
return [minute for minute in ALLOWED_REMINDER_MINUTES if minute in selected]
|
||
|
||
|
||
def normalize_rental_settings(data: dict):
|
||
"""校验并标准化来自用户端或管理端的用车设置。"""
|
||
if not isinstance(data, dict):
|
||
raise ValueError("设置格式不正确")
|
||
|
||
def parse_bool(name, default):
|
||
value = data.get(name, default)
|
||
if isinstance(value, bool):
|
||
return value
|
||
if value in (0, 1, "0", "1"):
|
||
return str(value) == "1"
|
||
if isinstance(value, str) and value.lower() in ("true", "false"):
|
||
return value.lower() == "true"
|
||
raise ValueError(f"{name} 必须是布尔值")
|
||
|
||
raw_minutes = data.get("reminder_minutes", DEFAULT_RENTAL_SETTINGS["reminder_minutes"])
|
||
if not isinstance(raw_minutes, (list, tuple, set)):
|
||
raise ValueError("提醒时间必须为数组")
|
||
try:
|
||
numeric_minutes = [int(value) for value in raw_minutes]
|
||
except (TypeError, ValueError):
|
||
raise ValueError("提醒时间包含无效值")
|
||
invalid = [value for value in numeric_minutes if value not in ALLOWED_REMINDER_MINUTES]
|
||
if invalid:
|
||
raise ValueError("提醒时间仅支持 10、5、3、2、1、0 分钟")
|
||
|
||
try:
|
||
duration = int(data.get("rental_duration_minutes", 19))
|
||
except (TypeError, ValueError):
|
||
raise ValueError("用车到期时间必须是整数")
|
||
if duration < 1 or duration > 180:
|
||
raise ValueError("用车到期时间须在 1 到 180 分钟之间")
|
||
|
||
try:
|
||
rounds = int(data.get("rental_rounds", MIN_RENTAL_ROUNDS))
|
||
except (TypeError, ValueError):
|
||
raise ValueError("自动续租轮次必须是整数")
|
||
if rounds < MIN_RENTAL_ROUNDS or rounds > MAX_RENTAL_ROUNDS:
|
||
raise ValueError(f"自动续租轮次须在 {MIN_RENTAL_ROUNDS} 到 {MAX_RENTAL_ROUNDS} 轮之间")
|
||
|
||
return {
|
||
"reminder_enabled": parse_bool("reminder_enabled", True),
|
||
"reminder_minutes": parse_reminder_minutes(numeric_minutes),
|
||
"rental_duration_minutes": duration,
|
||
"auto_return_enabled": parse_bool("auto_return_enabled", True),
|
||
"rental_rounds": rounds,
|
||
"protect_card": parse_bool("protect_card", True),
|
||
}
|
||
|
||
|
||
def get_user_rental_settings(user_id: int):
|
||
"""获取用户用车策略;无用户或老数据均返回安全默认值。"""
|
||
defaults = dict(DEFAULT_RENTAL_SETTINGS)
|
||
defaults["reminder_minutes"] = list(DEFAULT_RENTAL_SETTINGS["reminder_minutes"])
|
||
if not user_id:
|
||
return defaults
|
||
conn = get_db()
|
||
try:
|
||
row = conn.execute("""
|
||
SELECT reminder_enabled, reminder_minutes, rental_duration_minutes,
|
||
auto_return_enabled, rental_rounds, protect_card
|
||
FROM users WHERE id = ?
|
||
""", (user_id,)).fetchone()
|
||
except sqlite3.OperationalError:
|
||
# 兼容尚未执行 init_db 迁移的测试库/启动早期连接。
|
||
conn.close()
|
||
return defaults
|
||
conn.close()
|
||
if not row:
|
||
return defaults
|
||
try:
|
||
duration = int(row["rental_duration_minutes"])
|
||
except (TypeError, ValueError):
|
||
duration = defaults["rental_duration_minutes"]
|
||
try:
|
||
rounds = int(row["rental_rounds"])
|
||
except (KeyError, TypeError, ValueError):
|
||
rounds = defaults["rental_rounds"]
|
||
rounds = max(MIN_RENTAL_ROUNDS, min(MAX_RENTAL_ROUNDS, rounds))
|
||
return {
|
||
"reminder_enabled": bool(row["reminder_enabled"]),
|
||
"reminder_minutes": parse_reminder_minutes(row["reminder_minutes"]),
|
||
"rental_duration_minutes": max(1, min(180, duration)),
|
||
"auto_return_enabled": bool(row["auto_return_enabled"]),
|
||
"rental_rounds": rounds,
|
||
"protect_card": bool(row["protect_card"]),
|
||
}
|
||
|
||
|
||
def save_user_rental_settings(user_id: int, settings: dict):
|
||
"""保存已通过路由层校验的用车策略。"""
|
||
reminder_minutes = parse_reminder_minutes(settings.get("reminder_minutes"))
|
||
duration = int(settings.get("rental_duration_minutes", 19))
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
UPDATE users SET reminder_enabled = ?, reminder_minutes = ?,
|
||
rental_duration_minutes = ?, auto_return_enabled = ?,
|
||
rental_rounds = ?, protect_card = ?
|
||
WHERE id = ?
|
||
""", (
|
||
1 if settings.get("reminder_enabled") else 0,
|
||
",".join(str(v) for v in reminder_minutes),
|
||
duration,
|
||
1 if settings.get("auto_return_enabled") else 0,
|
||
int(settings.get("rental_rounds", MIN_RENTAL_ROUNDS)),
|
||
1 if settings.get("protect_card", True) else 0,
|
||
user_id,
|
||
))
|
||
changed = cursor.rowcount
|
||
conn.commit()
|
||
conn.close()
|
||
return bool(changed)
|
||
|
||
|
||
# ===== 注册邀请码 =====
|
||
|
||
def create_invite_codes(count: int, max_uses: int, note: str = ""):
|
||
"""批量签发邀请码,返回生成的明文码列表(仅签发时可见完整列表)。"""
|
||
import secrets
|
||
codes = []
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # 去掉易混淆的 I/O/0/1
|
||
while len(codes) < count:
|
||
code = "XB-" + "".join(secrets.choice(alphabet) for _ in range(6))
|
||
try:
|
||
cursor.execute(
|
||
"INSERT INTO invite_codes (code, max_uses, note) VALUES (?, ?, ?)",
|
||
(code, max(1, min(999, max_uses)), (note or "")[:100]))
|
||
codes.append(code)
|
||
except sqlite3.IntegrityError:
|
||
continue # 撞码重生成
|
||
conn.commit()
|
||
conn.close()
|
||
return codes
|
||
|
||
|
||
def list_invite_codes():
|
||
"""列出所有邀请码(含使用进度与使用人)。"""
|
||
conn = get_db()
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT * FROM invite_codes ORDER BY id DESC")]
|
||
conn.close()
|
||
return rows
|
||
|
||
|
||
def set_invite_code_disabled(code_id: int, disabled: bool):
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("UPDATE invite_codes SET disabled = ? WHERE id = ?",
|
||
(1 if disabled else 0, code_id))
|
||
changed = cursor.rowcount
|
||
conn.commit()
|
||
conn.close()
|
||
return bool(changed)
|
||
|
||
|
||
def delete_invite_code(code_id: int):
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("DELETE FROM invite_codes WHERE id = ?", (code_id,))
|
||
changed = cursor.rowcount
|
||
conn.commit()
|
||
conn.close()
|
||
return bool(changed)
|
||
|
||
|
||
def consume_invite_code(code: str, email: str):
|
||
"""核销邀请码(原子操作:仅未停用且未用满时通过)。返回 (ok, message)。"""
|
||
code = (code or "").strip().upper()
|
||
if not code:
|
||
return False, "请输入邀请码"
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
UPDATE invite_codes
|
||
SET used_count = used_count + 1,
|
||
used_by = CASE WHEN used_by = '' THEN ? ELSE used_by || ',' || ? END
|
||
WHERE code = ? AND disabled = 0 AND used_count < max_uses
|
||
""", (email, email, code))
|
||
ok = cursor.rowcount == 1
|
||
conn.commit()
|
||
conn.close()
|
||
if ok:
|
||
return True, ""
|
||
# 未通过时给出具体原因
|
||
conn = get_db()
|
||
row = conn.execute("SELECT disabled, used_count, max_uses FROM invite_codes WHERE code = ?",
|
||
(code,)).fetchone()
|
||
conn.close()
|
||
if not row:
|
||
return False, "邀请码无效"
|
||
if row["disabled"]:
|
||
return False, "邀请码已被停用"
|
||
return False, "邀请码已被用完"
|
||
|
||
|
||
def get_user_display_name(user_id: int) -> str:
|
||
"""获取用户显示名称"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT email, access_token, token_id FROM users WHERE id = ?", (user_id,))
|
||
row = cursor.fetchone()
|
||
conn.close()
|
||
if not row:
|
||
return "未知用户"
|
||
email = row["email"]
|
||
if row["token_id"]:
|
||
name = email.split("@")[0]
|
||
return f"{name}"
|
||
return email
|
||
|
||
|
||
def get_all_users():
|
||
"""获取所有用户列表"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT id, email, access_token, token_id,
|
||
reminder_enabled, reminder_minutes, rental_duration_minutes, auto_return_enabled,
|
||
rental_rounds, protect_card,
|
||
CASE WHEN token_id IS NOT NULL AND token_id != '' THEN 1 ELSE 0 END as has_auth,
|
||
CASE WHEN access_token IS NOT NULL AND access_token != '' THEN 1 ELSE 0 END as has_access_token
|
||
FROM users ORDER BY id
|
||
""")
|
||
users = [dict(r) for r in cursor.fetchall()]
|
||
conn.close()
|
||
for user in users:
|
||
user["reminder_enabled"] = bool(user.get("reminder_enabled"))
|
||
user["auto_return_enabled"] = bool(user.get("auto_return_enabled"))
|
||
user["rental_rounds"] = max(
|
||
MIN_RENTAL_ROUNDS,
|
||
min(MAX_RENTAL_ROUNDS, int(user.get("rental_rounds") or MIN_RENTAL_ROUNDS)),
|
||
)
|
||
user["protect_card"] = bool(user.get("protect_card"))
|
||
user["reminder_minutes"] = parse_reminder_minutes(user.get("reminder_minutes"))
|
||
return users
|
||
|
||
|
||
def get_all_rentals(limit=200):
|
||
"""获取所有租车记录(共享订单附带骑行者邮箱)"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT r.*, u.email as user_email, ru.email as rider_email
|
||
FROM rentals r
|
||
LEFT JOIN users u ON r.user_id = u.id
|
||
LEFT JOIN users ru ON r.rider_user_id = ru.id
|
||
ORDER BY r.id DESC LIMIT ?
|
||
""", (limit,))
|
||
rentals = [dict(r) for r in cursor.fetchall()]
|
||
conn.close()
|
||
return rentals
|
||
|
||
|
||
def get_rental_status_label(expired: int, end_time: str) -> str:
|
||
"""返回租车状态标签"""
|
||
if expired:
|
||
return "已完成"
|
||
import datetime as dt
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
now = dt.datetime.now(tz)
|
||
try:
|
||
end = dt.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
|
||
if now > end:
|
||
return "已超时"
|
||
return "进行中"
|
||
except:
|
||
return "未知"
|
||
|
||
|
||
def get_user_alert_email(user_id: int) -> str:
|
||
"""获取用户告警接收邮箱;未设置时回退账号邮箱。"""
|
||
if not user_id:
|
||
return ""
|
||
conn = get_db()
|
||
try:
|
||
row = conn.execute("SELECT email, alert_email FROM users WHERE id = ?", (user_id,)).fetchone()
|
||
except sqlite3.OperationalError:
|
||
# 旧库/极简 schema 缺 alert_email 列:回退账号邮箱
|
||
row = None
|
||
try:
|
||
row = conn.execute("SELECT email, NULL AS alert_email FROM users WHERE id = ?",
|
||
(user_id,)).fetchone()
|
||
except sqlite3.OperationalError:
|
||
row = None
|
||
conn.close()
|
||
if not row:
|
||
return ""
|
||
return (row["alert_email"] or "").strip() or (row["email"] or "").strip()
|
||
|
||
|
||
def set_user_alert_email(user_id: int, email: str) -> bool:
|
||
email = (email or "").strip()
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("UPDATE users SET alert_email = ? WHERE id = ?", (email or None, user_id))
|
||
changed = cursor.rowcount
|
||
conn.commit()
|
||
conn.close()
|
||
return bool(changed)
|