Files
xbcr/subscribe.py
T
zzy 57eae3ac82 fix: 订阅实时数据的字段/车型隔离 + 补还车来源白名单 + 补发窗口 + 重试收尾
按 review 逐条修:

P0-1 实时刷新取错电量字段
- refresh_bike_points 改读 electric_quantity(兼容 electricQuantity),
  原来读 st["electric"] 永远是 None → 电量筛选全落空、排序退化成距离

P0-2 type=1 单车混进候选
- 只请求 type=3(电动车),每行带 bike_type;不再把共享单车算进
  「附近有几辆」和自动开锁候选

P0-2b 取数顺序
- 先走 request_api(60 秒共享快照),失败才用用户凭据直连一次

P1-3 订阅单不在补还车白名单
- 新增 _should_auto_return(rental):source ∈
  unlock/sync/shared/subscribe 且 order_id 非空,restore 与巡检共用

P1-4 reminder 单被当成真实订单
- _recover_overdue_rental 与 restore 都按白名单过滤,
  reminder 直接跳过,不再拿本地自增 id 当订单号白打三次上游

P1-5 补发没有下界
- _tick 加 CATCHUP_WINDOW_MIN=5:窗口内补发,超过窗口只记「今天已处理」

P2 收尾
- 重试成功补发「自动还车已成功」通知(避免用户去点旧邮件里的还车按钮)
- 重试耗尽改为给管理员发告警邮件,不再只有一行 print
- _mark_notified 支持复用已有连接/游标
- _return_candidates 惰性:先试原坐标,失败才算候选点
  (不再每次还车都多打一次 /project/map)
- 删除 map.js 死变量 _orderAlerted

文案
- 按「不写会话顶替、只写到期提醒」的口径:
  wechat.py 模块说明改为「AccessToken 30 天有效,到期前有提醒」;
  alerts.py 三处 lead 去掉「重新登录会顶掉旧会话」,只保留「请更新凭据」

测试:150 pytest(新增电量字段/车型隔离、补发窗口、reminder 跳过、
retry 收尾通知、耗尽告警)+ 32 node 全绿;浏览器冒烟 JS 异常 0
2026-11-15 17:45:30 +08:00

682 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""用车订阅提醒:按规则定时统计某停车点附近的可用电动车,可选自动开锁。
- 每用户最多 5 条规则;规则 = 停车点(下拉) + 星期 + 时间(HH:MM)
- 命中时发邮件:附近可用车辆数 + 可自动开锁的具体车辆编号
- auto_unlock:真实开锁链路(扫码 → 下单 → 开锁),带筛选/排序/冲突重试:
* 车型筛选:小车 / 大车 / 红车(可多选)
* 电量区间:min_electric ~ max_electric
* 排序:电量从高到低(默认)/ 低到高 / 距离最近
* 冲突避让:所选车若被别人同时开走,自动换下一个候选,重试次数可配(默认 3)
- 判定用最近 20 分钟内的采集点(每车取最新一条),坐标系与车辆一致(GCJ02)。
"""
import datetime as dt
import math
import sqlite3
import random
import threading
import time
from campus import bike_kind, bikes_near_parking, load_locations, parking_candidates
from db import get_db
from email_utils import send_email
CHECK_INTERVAL = 30 # 调度精度:30 秒扫一次规则
CATCHUP_WINDOW_MIN = 5 # 补发窗口:超过这么久就不再补(避免晚上补发早上的提醒)
SCAN_FRESH_MINUTES = 20 # 采集点新鲜度
MAX_RULES_PER_USER = 5
AUTO_UNLOCK_ENABLED = True # 自动开锁总开关(规则勾选 + 本开关同时为真才执行)
VALID_KINDS = ("small", "big", "red")
SORT_OPTIONS = {
"electric_desc": "电量从高到低",
"electric_asc": "电量从低到高",
"distance_asc": "距离最近优先",
}
WEEKDAY_NAMES = {0: "每天", 1: "周一", 2: "周二", 3: "周三",
4: "周四", 5: "周五", 6: "周六", 7: "周日"}
# ========== 规则校验 ==========
def normalize_rule(data: dict) -> dict:
"""校验并标准化订阅规则输入(含自动开锁的筛选/排序/重试配置)。非法抛 ValueError。"""
if not isinstance(data, dict):
raise ValueError("规则格式不正确")
try:
location_id = int(data.get("location_id"))
except (TypeError, ValueError):
raise ValueError("请选择停车点")
try:
weekday = int(data.get("weekday", 0))
except (TypeError, ValueError):
raise ValueError("星期格式不正确")
if weekday not in WEEKDAY_NAMES:
raise ValueError("星期仅支持 0(每天) 与 1-7")
time_str = str(data.get("time", "")).strip()
try:
hh, mm = time_str.split(":")
hour, minute = int(hh), int(mm)
except (ValueError, TypeError):
raise ValueError("时间格式应为 HH:MM")
if not (0 <= hour <= 23 and 0 <= minute <= 59):
raise ValueError("时间不在有效范围内")
minute_of_day = hour * 60 + minute
def _bool(name, default=False):
v = data.get(name, default)
if isinstance(v, bool):
return v
if v in (0, 1, "0", "1"):
return str(v) == "1"
if isinstance(v, str) and v.lower() in ("true", "false"):
return v.lower() == "true"
raise ValueError(f"{name} 必须是布尔值")
# 车型筛选:小车/大车/红车(small/big/red),空=不限制(存全量)
raw_kinds = data.get("kinds")
if raw_kinds in (None, ""):
kinds = ["small", "big", "red"]
else:
if isinstance(raw_kinds, str):
raw_kinds = [k.strip() for k in raw_kinds.replace(",", ",").split(",") if k.strip()]
kinds = [str(k).strip().lower() for k in raw_kinds if str(k).strip()]
invalid = [k for k in kinds if k not in VALID_KINDS]
if invalid:
raise ValueError("车型仅支持 小车/大车/红车")
if not kinds:
kinds = ["small", "big", "red"]
def _int_range(name, default, lo, hi):
v = data.get(name, default)
if v in (None, ""):
return default
try:
v = int(float(v))
except (TypeError, ValueError):
raise ValueError(f"{name} 必须是数字")
if v < lo or v > hi:
raise ValueError(f"{name} 须在 {lo} 到 {hi} 之间")
return v
min_e = _int_range("min_electric", 0, 0, 100)
max_e = _int_range("max_electric", 100, 0, 100)
if min_e > max_e:
raise ValueError("电量下限不能大于上限")
sort_by = str(data.get("sort_by") or "electric_desc").strip()
if sort_by not in SORT_OPTIONS:
raise ValueError("排序方式不支持")
try:
retry_times = int(data.get("retry_times", 3))
except (TypeError, ValueError):
raise ValueError("重试次数必须是数字")
retry_times = max(1, min(10, retry_times))
return {
"location_id": location_id,
"weekday": weekday,
"minute_of_day": minute_of_day,
"notify_enabled": _bool("notify_enabled", True),
"auto_unlock": _bool("auto_unlock", False),
"enabled": _bool("enabled", True),
"kinds": ",".join(kinds),
"min_electric": min_e,
"max_electric": max_e,
"sort_by": sort_by,
"retry_times": retry_times,
}
def rule_filters(rule: dict) -> dict:
"""从库里的规则行解析出筛选参数(容错:老数据缺列时用默认值)。"""
raw = str(rule.get("kinds") or "").strip()
kinds = [k for k in raw.split(",") if k in VALID_KINDS] or ["small", "big", "red"]
try:
retry_times = max(1, min(10, int(rule.get("retry_times") or 3)))
except (TypeError, ValueError):
retry_times = 3
sort_by = str(rule.get("sort_by") or "electric_desc")
if sort_by not in SORT_OPTIONS:
sort_by = "electric_desc"
try:
min_e = int(rule.get("min_electric") if rule.get("min_electric") is not None else 0)
except (TypeError, ValueError):
min_e = 0
try:
max_e = int(rule.get("max_electric") if rule.get("max_electric") is not None else 100)
except (TypeError, ValueError):
max_e = 100
return {"kinds": kinds, "min_electric": min_e, "max_electric": max_e,
"sort_by": sort_by, "retry_times": retry_times}
def count_user_rules(user_id: int) -> int:
conn = get_db()
row = conn.execute("SELECT COUNT(*) AS c FROM subscribe_rules WHERE user_id = ?",
(user_id,)).fetchone()
conn.close()
return row["c"] if row else 0
# ========== 车辆统计 ==========
def latest_bike_points():
"""每辆车最近一条采集点(限定新鲜度窗口)。"""
conn = get_db()
try:
rows = conn.execute("""
SELECT b.bike_code, b.latitude, b.longitude, b.state, b.status, b.electric
FROM bike_history b
JOIN (
SELECT bike_code, MAX(recorded_at) AS m
FROM bike_history
WHERE recorded_at >= datetime('now', '+8 hours', ?)
GROUP BY bike_code
) x ON b.bike_code = x.bike_code AND b.recorded_at = x.m
""", (f"-{SCAN_FRESH_MINUTES} minutes",)).fetchall()
except Exception:
rows = []
finally:
conn.close()
return [dict(r) for r in rows]
def refresh_bike_points(user_id=None):
"""判定前拉一次最新地图(**只用 type=3 电动车**,别把单车混进候选)。
取数顺序:共享快照(60 秒,省上游) → 失败才用用户凭据直连一次。
`type=1` 是共享单车,它的车牌号段也会被判成「小车」,混进来会导致
「自动开锁开了一辆单车」和「附近有 12 辆其实 8 辆是单车」。
字段名用 `electric_quantity`(上游真实字段);写成 `electric` 会永远是
None,电量筛选就全部落空(≥50% 的规则会报「附近暂无符合条件的车辆」)。
"""
from wechat import request_with_user_auth, request_api
def _fetch(use_snapshot_only=False):
try:
res = request_api("GET", "/project/map", params={"type": "3"})
if isinstance(res, dict) and res.get("rtn_code") == 0:
return res
except Exception as exc:
print(f"[订阅提醒] 快照读地图失败: {exc}")
if use_snapshot_only or not user_id:
return None
try:
res = request_with_user_auth(user_id, "GET", "/project/map",
params={"type": "3"}, _silent=True)
return res if isinstance(res, dict) and res.get("rtn_code") == 0 else None
except Exception as exc:
print(f"[订阅提醒] 用户凭据刷新地图失败: {exc}")
return None
res = _fetch()
if res is None:
time.sleep(0.6) # 上游 503/抖动:等半秒再试一次
res = _fetch()
if res is None:
return None
rows = []
for st in ((res.get("data") or {}).get("bicycleStation") or []):
lat, lng = st.get("latitude"), st.get("longitude")
if lat is None or lng is None:
continue
electric = st.get("electric_quantity")
if electric is None:
electric = st.get("electricQuantity")
if electric is None:
electric = st.get("electric")
rows.append({
"bike_code": str(st.get("code") or ""),
"latitude": lat,
"longitude": lng,
"state": st.get("state"),
"status": st.get("status"),
"electric": electric,
"bike_type": "3",
})
return rows or None
def stat_location(loc, user_id=None, fresh=True):
"""统计某个停车点附近的车辆。返回 None 表示该地点没有可用判定(缺坐标)。"""
if loc is None:
return None
try:
if loc.get("latitude") is None or loc.get("longitude") is None:
return None
except Exception:
return None
points = None
if fresh:
points = refresh_bike_points(user_id)
if not points:
points = latest_bike_points()
return bikes_near_parking(points, loc)
# ========== 自动开锁(真实链路) ==========
def _near_coord(lat, lng, jitter=0.0001):
"""车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)。"""
try:
lat, lng = float(lat), float(lng)
except (TypeError, ValueError):
lat, lng = 36.67, 116.98
return (lat + random.uniform(-jitter, jitter), lng + random.uniform(-jitter, jitter))
def _live_coord(user_id: int, code: str, btype=None):
"""实时抓该车坐标(车会被骑走),返回 (lat, lng) 或 None。"""
from wechat import request_with_user_auth
types = []
if btype:
types.append(str(btype))
for t in ("3", "1", "6"):
if t not in types:
types.append(t)
for t in types:
try:
res = request_with_user_auth(user_id, "GET", "/project/map",
params={"type": t}, _silent=True)
except Exception:
continue
if res.get("rtn_code") != 0:
continue
for st in ((res.get("data") or {}).get("bicycleStation") or []):
if str(st.get("code")) == str(code) and st.get("latitude") and st.get("longitude"):
return st["latitude"], st["longitude"]
return None
def _discard_pending_order(user_id: int, order_id, code: str,
lat=None, lng=None) -> bool:
"""下单成功但开锁失败:把这张半成品订单关掉。
不清理的话,下一次重试会再叠一张新订单 —— 上游会同时挂着几张
没人骑的订单,用户还可能被算未支付。
"""
from wechat import request_with_user_auth
data = {"order_id": order_id}
if lat is not None and lng is not None:
data.update({"latitude": lat, "longitude": lng, "code": code})
for path in ("/record/return", "/record/orderClose"):
try:
res = request_with_user_auth(user_id, "POST", path, data=data, _silent=True)
except Exception as exc:
print(f"[订阅开锁] 清理半成品订单 {order_id} 调 {path} 异常: {exc}")
continue
if isinstance(res, dict) and res.get("rtn_code") == 0:
print(f"[订阅开锁] 半成品订单 {order_id} 已通过 {path} 关闭")
return True
msg = (res or {}).get("message") if isinstance(res, dict) else None
print(f"[订阅开锁] 清理半成品订单 {order_id} 失败({path}): {msg}")
return False
def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
"""真实自动开锁:扫码 → 创建订单 → 开锁(全部使用订阅人自己的凭据)。
返回 {"success": bool, "occupied": bool, "order_id": str|None, "message": str}
occupied=True 表示「这辆车已被别人抢先」,调用方可换下一个候选重试。
"""
from wechat import request_with_user_auth
if not AUTO_UNLOCK_ENABLED:
return {"success": False, "occupied": False,
"message": "自动开锁总开关未开启"}
code = str(bike_code or "").strip()
if not code:
return {"success": False, "occupied": False, "message": "车辆编号为空"}
# 1) 扫码查车(同时判断车是否还在/是否已被占用)
bike = request_with_user_auth(user_id, "POST", "/project/bicycle",
data={"code": code}, _silent=True)
if bike.get("rtn_code") != 0:
msg = bike.get("message") or "查询车辆失败"
occupied = any(k in msg for k in ("使用中", "占用", "已被", "骑行"))
return {"success": False, "occupied": occupied, "message": msg}
bike_data = bike.get("data") or {}
if str(bike_data.get("status")) == "1":
return {"success": False, "occupied": True,
"message": "该车已被他人开锁(使用中)"}
# 2) 下单坐标:优先实时地图坐标,取不到退回扫码坐标;两者都加抖动
live = _live_coord(user_id, code, bike_data.get("type"))
if live:
lat, lng = _near_coord(live[0], live[1])
else:
lat, lng = _near_coord(bike_data.get("latitude", 36.67),
bike_data.get("longitude", 116.98))
order = request_with_user_auth(
user_id, "POST", "/record/order",
data={"code": code, "start_longitude": lng, "start_latitude": lat}, _silent=True)
if order.get("rtn_code") != 0 or not (order.get("data") or {}).get("order_id"):
msg = order.get("message") or "创建订单失败"
# 有未支付订单:尝试用月卡/周卡自动支付后重下一次
if "未支付" in msg or "待支付" in msg:
try:
from routes.rental import _try_card_pay_auto
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
unpaid = (info.get("data") or {}).get("nonDealOrder") or {}
if unpaid.get("order_id"):
pay = _try_card_pay_auto(user_id, unpaid["order_id"],
unpaid.get("code") or code)
if pay.get("success"):
order = request_with_user_auth(
user_id, "POST", "/record/order",
data={"code": code, "start_longitude": lng,
"start_latitude": lat}, _silent=True)
msg = order.get("message") or msg
except Exception as exc:
print(f"[订阅开锁] 自动卡支付异常: {exc}")
if order.get("rtn_code") != 0 or not (order.get("data") or {}).get("order_id"):
occupied = any(k in msg for k in ("使用中", "占用", "已被", "骑行", "锁定"))
if order.get("rtn_code") == 102001:
msg = "微信凭据已失效,请重新配置后再用自动开锁"
return {"success": False, "occupied": occupied, "message": msg}
order_id = order["data"]["order_id"]
# 3) 开锁
opened = request_with_user_auth(user_id, "POST", "/record/qrOrder",
data={"order_id": order_id}, _silent=True)
if opened.get("rtn_code") != 0:
# 半成品订单必须撤销,否则下一次重试会再叠一张
cleaned = _discard_pending_order(user_id, order_id, code, lat, lng)
msg = opened.get("message") or "开锁指令失败"
if cleaned:
msg += "(已撤销本次下单)"
else:
msg += "(本次下单可能残留在上游,请稍后在订单页检查)"
return {"success": False, "occupied": False, "order_id": str(order_id),
"message": msg}
# 4) 本地落单 + 计时器 + 起点位置(与手动开锁一致,source='subscribe')
try:
from db import get_user_rental_settings
from timer import start_rental_timer
settings = get_user_rental_settings(user_id)
duration = int(settings["rental_duration_minutes"])
tz = dt.timezone(dt.timedelta(hours=8))
now = dt.datetime.now(tz)
end = now + dt.timedelta(minutes=duration)
conn = get_db()
email = ""
row = conn.execute("SELECT email FROM users WHERE id = ?", (user_id,)).fetchone()
if row:
email = row["email"] or ""
try:
conn.execute("""
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time,
end_time, duration, expired, source, renewal_round)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
""", (int(order_id), str(order_id), code, email, user_id,
now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
duration))
except sqlite3.IntegrityError:
# id 与历史行冲突(极少见):改用自增 id,order_id 仍记录真实订单号
conn.execute("""
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time,
end_time, duration, expired, source, renewal_round)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
""", (str(order_id), code, email, user_id,
now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
duration))
conn.commit()
conn.close()
start_rental_timer(rental_id=int(order_id), email=email, bike_code=code,
duration_minutes=duration, user_id=user_id)
try:
from routes.rental import _record_rental_start
_record_rental_start(int(order_id), lat, lng)
except Exception as exc:
print(f"[订阅开锁] 回填起点失败: {exc}")
except Exception as exc:
# 上游已开锁成功,本地记录失败不影响结果,但要留痕
print(f"[订阅开锁] 本地落单失败(上游已开锁): {exc}")
return {"success": True, "occupied": False, "order_id": str(order_id),
"lat": lat, "lng": lng, "message": "开锁成功"}
def auto_unlock_with_retry(rule: dict, candidates: list, retry_times: int) -> dict:
"""按候选顺序尝试开锁:被他人抢先就换下一个,最多 retry_times 次。
返回 {"success": bool, "bike": dict|None, "attempts": [...], "message": str}
"""
attempts = []
tries = min(max(1, int(retry_times or 1)), max(1, min(len(candidates), 10)))
for idx, cand in enumerate(candidates[:tries], start=1):
code = cand["bike_code"]
res = _try_auto_unlock(rule["user_id"], code)
attempts.append({
"n": idx, "bike_code": code, "kind_label": cand.get("kind_label"),
"electric": cand.get("electric"), "distance": cand.get("distance"),
"success": bool(res.get("success")), "occupied": bool(res.get("occupied")),
"message": res.get("message") or "",
})
if res.get("success"):
print(f"[订阅开锁] 成功: rule={rule['id']} 第{idx}次 车辆={code}")
return {"success": True, "bike": cand, "attempts": attempts,
"order_id": res.get("order_id"),
"message": f"第 {idx} 次尝试成功"}
# 非「被占用」类失败(如凭据失效/网络)没必要继续换车
if not res.get("occupied"):
print(f"[订阅开锁] 中止: rule={rule['id']} 车辆={code} 原因={res.get('message')}")
return {"success": False, "bike": None, "attempts": attempts,
"message": res.get("message") or "开锁失败"}
print(f"[订阅开锁] 避让: rule={rule['id']} 车辆={code} 被占用,换下一个候选")
return {"success": False, "bike": None, "attempts": attempts,
"message": "候选车辆均被他人抢先" if attempts else "没有符合条件的车辆"}
# ========== 邮件 ==========
def _render_html(title, lead, details):
import html as _html
rows = "".join(
'<tr><td style="padding:8px 0;color:#64748b;width:110px;vertical-align:top">{}</td>'
'<td style="padding:8px 0;color:#0f172a;font-weight:600">{}</td></tr>'.format(
_html.escape(str(k)), _html.escape(str(v)))
for k, v in details)
return f"""<!doctype html>
<html><body style="margin:0;background:#f1f5f9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Microsoft YaHei',sans-serif">
<div style="max-width:600px;margin:0 auto;padding:30px 14px">
<div style="background:#fff;border-radius:18px;overflow:hidden;box-shadow:0 8px 30px rgba(15,23,42,.08)">
<div style="height:6px;background:#2563eb"></div>
<div style="padding:30px">
<div style="font-size:13px;color:#2563eb;font-weight:800;letter-spacing:.08em">小白超人 · 车辆订阅</div>
<h1 style="margin:10px 0 12px;font-size:24px;line-height:1.35;color:#0f172a">{_html.escape(title)}</h1>
<p style="margin:0 0 22px;color:#475569;font-size:15px;line-height:1.8">{_html.escape(lead)}</p>
<table role="presentation" style="width:100%;border-collapse:collapse;background:#f8fafc;border-radius:12px;padding:12px">
{rows}
</table>
</div>
</div>
<p style="text-align:center;color:#94a3b8;font-size:12px;margin:18px 0">这是你订阅的定时车辆播报。</p>
</div>
</body></html>"""
def _user_email(user_id):
from db import get_user_alert_email
return get_user_alert_email(user_id)
def fire_rule(rule: dict):
"""执行一条规则:按筛选条件统计候选车辆;需要时自动开锁并邮件汇报。"""
from db import get_user_alert_email
locs = load_locations()
loc = next((l for l in locs if l["id"] == rule["location_id"]), None)
to_email = get_user_alert_email(rule["user_id"])
if not to_email:
return False
if loc is None:
return False
flt = rule_filters(rule)
# 先刷新地图再看有几辆:订阅最怕“看到的是别人已经骑走的数据”
points = refresh_bike_points(rule.get("user_id")) or latest_bike_points()
stat = bikes_near_parking(points, loc)
# 候选:只含「符合车型/电量筛选」的空闲可用车,已按排序规则排好
candidates = parking_candidates(
points, loc,
kinds=flt["kinds"], min_electric=flt["min_electric"],
max_electric=flt["max_electric"], sort_by=flt["sort_by"],
limit=max(10, flt["retry_times"] + 5))
tz = dt.timezone(dt.timedelta(hours=8))
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M")
rule_desc = (f"每周{WEEKDAY_NAMES.get(rule['weekday'], '')} "
if rule["weekday"] else "每天 ") + \
f"{rule['minute_of_day'] // 60:02d}:{rule['minute_of_day'] % 60:02d}"
kind_desc = "/".join({"small": "小车", "big": "大车", "red": "红车"}[k]
for k in flt["kinds"])
filter_desc = f"{kind_desc} · 电量 {flt['min_electric']}%-{flt['max_electric']}% · " \
f"{SORT_OPTIONS.get(flt['sort_by'], flt['sort_by'])}"
unlock_result = None
n_cand = len(candidates)
if rule.get("auto_unlock") and candidates:
unlock_result = auto_unlock_with_retry(rule, candidates, flt["retry_times"])
# ---------- 组邮件 ----------
if unlock_result and unlock_result.get("success"):
bike = unlock_result["bike"]
title = f"已自动开锁 #{bike['bike_code']}({bike.get('kind_label')})"
lead = (f"你订阅的时刻到了,{loc['name']}附近符合条件的有 {n_cand} 辆,"
f"系统已按「{SORT_OPTIONS.get(flt['sort_by'])}」为你开锁 "
f"#{bike['bike_code']}。到点会自动还车并用优惠卡支付。")
elif unlock_result:
title = f"{loc['name']}附近自动开锁未成功"
lead = (f"符合条件的有 {n_cand} 辆,但本次自动开锁失败:"
f"{unlock_result.get('message')}。可手动到页面开锁。")
elif n_cand > 0:
title = f"{loc['name']}附近有 {n_cand} 辆符合条件"
lead = f"你订阅的时刻到了:{loc['name']}附近有 {n_cand} 辆符合你的筛选条件,快去开锁吧。"
else:
title = f"{loc['name']}附近暂无符合条件的车辆"
lead = (f"你订阅的时刻到了:{loc['name']}附近最近 {SCAN_FRESH_MINUTES} 分钟内共 "
f"{stat['total']} 辆车,但没有符合「{filter_desc}」的空闲车。")
details = [("订阅地点", loc["name"]), ("规则", rule_desc),
("筛选条件", filter_desc), ("播报时间", now_str),
("符合条件", f"{n_cand} 辆"),
("附近总数", f"{stat['total']} 辆(可用 {stat['available']})")]
if candidates:
top = candidates[:5]
details.append(("候选车辆", "、".join(
f"#{c['bike_code']}({c['kind_label']} {c['electric']:.0f}% {c['distance']}m)"
for c in top)))
if unlock_result:
if unlock_result.get("success"):
bike = unlock_result["bike"]
details.append(("已开锁车辆", f"#{bike['bike_code']}({bike['kind_label']})"))
details.append(("车辆电量", f"{bike['electric']:.0f}%"))
details.append(("距停车点", f"{bike['distance']} 米"))
if unlock_result.get("order_id"):
details.append(("订单号", str(unlock_result["order_id"])))
attempts = unlock_result.get("attempts") or []
if len(attempts) > 1 or not unlock_result.get("success"):
detail_lines = []
for a in attempts:
flag = "成功" if a["success"] else ("被占用,已避让" if a["occupied"] else "失败")
detail_lines.append(f"第{a['n']}次 #{a['bike_code']}:{flag}"
+ ("" if a["success"] else f"({a['message']})"))
details.append(("尝试记录", ";".join(detail_lines)))
plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details)
html_body = _render_html(title, lead, details)
return send_email(to_email, f"【小白超人】{title}", plain, html_body)
# ========== 调度 ==========
def _scheduler_loop():
"""固定节拍扫描:按单调时钟对齐,不用「干完活再睡 30 秒」,
否则发信/自动开锁一慢,节拍就整体漂移。"""
next_at = time.monotonic()
while True:
try:
_tick()
except Exception as e:
print(f"[订阅提醒] 调度异常: {e}")
next_at += CHECK_INTERVAL
delay = next_at - time.monotonic()
if delay <= 0:
# 落后太多(比如机器卡了一下)就重新对齐,不追帧
next_at = time.monotonic() + CHECK_INTERVAL
continue
time.sleep(delay)
def _fire_rule_async(rule: dict):
"""单条规则在独立线程里执行,避免串行 fire 把整轮节拍拖过一分钟。"""
try:
ok = fire_rule(rule)
except Exception as e:
ok = False
print(f"[订阅提醒] 规则 {rule['id']} 发送失败: {e}")
print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule.get('user_id')}, 发送={ok})")
def _tick():
tz = dt.timezone(dt.timedelta(hours=8))
now = dt.datetime.now(tz)
today = now.strftime("%Y-%m-%d")
weekday = now.isoweekday()
minute_of_day = now.hour * 60 + now.minute
conn = get_db()
# 补发要有下界:7:50 的规则、服务 22:00 才启动,不该在晚上补发早上的提醒。
# 超过 CATCHUP_WINDOW_MIN 的直接记成「今天已处理」,不发信。
window_start = max(0, minute_of_day - CATCHUP_WINDOW_MIN)
stale = conn.execute("""
SELECT id FROM subscribe_rules
WHERE enabled = 1 AND weekday IN (0, ?) AND minute_of_day < ?
AND last_fired_on != ?
""", (weekday, window_start, today)).fetchall()
if stale:
for r in stale:
conn.execute("UPDATE subscribe_rules SET last_fired_on = ? WHERE id = ?",
(today, r["id"]))
conn.commit()
print(f"[订阅提醒] {len(stale)} 条规则已过补发窗口(>{CATCHUP_WINDOW_MIN} 分钟),"
f"今天不再补发")
# `<=` 而不是 `=`:只要今天还没发过,到点或过点(窗口内)都补一次。
# 用 `=` 的时候,一轮跑超过一分钟就会漏掉那一分钟,当天不再补。
rules = conn.execute("""
SELECT * FROM subscribe_rules
WHERE enabled = 1 AND weekday IN (0, ?)
AND minute_of_day <= ? AND minute_of_day >= ?
AND last_fired_on != ?
""", (weekday, minute_of_day, window_start, today)).fetchall()
if not rules:
conn.close()
return
# 先占位再发送,避免重试窗口内重复触发
for r in rules:
conn.execute("UPDATE subscribe_rules SET last_fired_on = ? WHERE id = ?", (today, r["id"]))
conn.commit()
conn.close()
for r in rules:
rule = dict(r)
if not rule.get("notify_enabled") and not rule.get("auto_unlock"):
continue
threading.Thread(target=_fire_rule_async, args=(rule,), daemon=True).start()
def start_subscribe_scheduler():
t = threading.Thread(target=_scheduler_loop, daemon=True, name="subscribe-scheduler")
t.start()
print(f"[订阅提醒] 调度已启动(每 {CHECK_INTERVAL}s 扫描一次)")