#!/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): """车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)。 坐标缺失/非法时退回**校园中心**(`campus.campus_center()`),不再用 历史硬编码 (36.67, 116.98) —— 那个点离校区约 20km,会把起点/还车点写坏。 """ try: lat, lng = float(lat), float(lng) except (TypeError, ValueError): from campus import campus_center lat, lng = campus_center() 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 _find_active_rental_id(conn, order_id): """该上游订单号是否已有「未结束」的本地记录;有就返回其 rental_id。 与 `routes.rental._find_active_rental_id` 同一口径(有意保持一致): 空 order_id(本地计时单)不参与判重。 """ if order_id is None: return None key = str(order_id).strip() if not key: return None row = conn.execute( "SELECT id FROM rentals WHERE order_id = ? AND COALESCE(expired, 0) = 0 " "ORDER BY id DESC LIMIT 1", (key,)).fetchone() return int(row["id"]) if row else None def _ensure_subscribe_rental(conn, *, order_id, code, email, user_id, start_time, end_time, duration): """订阅自动开锁的幂等落库:返回 (rental_id, created)。 与手动开锁(`routes.rental._insert_unlock_rental`)同源问题:上游同一 `order_id` 被重复使用时(规则重跑 / 网关重试 / 上游复用同一单号),绝不能 插第二行 rentals 和第二套计时器 —— 否则双份提醒、自动还车打两次、轮次翻倍。 `db.py` 的 `idx_rentals_active_order` 是硬兜底,这里先查一次做软复用。 """ key = str(order_id).strip() if order_id is not None else "" existing = _find_active_rental_id(conn, key) if existing is not None: return existing, False numeric_id = None try: numeric_id = int(order_id) except (TypeError, ValueError): numeric_id = None if numeric_id is not None: 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) """, (numeric_id, key, code, email, user_id, start_time, end_time, duration)) return numeric_id, True except sqlite3.IntegrityError: existing = _find_active_rental_id(conn, key) if existing is not None: print(f"[订阅开锁] order_id={key} 已存在未结束记录 rental_id={existing},复用") return existing, False print(f"[订阅开锁] rentals.id={numeric_id} 已被占用,改用自增 id") try: cur = 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) """, (key, code, email, user_id, start_time, end_time, duration)) except sqlite3.IntegrityError: existing = _find_active_rental_id(conn, key) if existing is not None: print(f"[订阅开锁] order_id={key} 并发重复,复用 rental_id={existing}") return existing, False raise return int(cur.lastrowid), True 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"), bike_data.get("longitude")) 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 "" start_str = now.strftime("%Y-%m-%d %H:%M:%S") end_str = end.strftime("%Y-%m-%d %H:%M:%S") rental_id, created = _ensure_subscribe_rental( conn, order_id=order_id, code=code, email=email, user_id=user_id, start_time=start_str, end_time=end_str, duration=duration) conn.commit() conn.close() if created: start_rental_timer(rental_id=int(rental_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(rental_id), lat, lng) except Exception as exc: print(f"[订阅开锁] 回填起点失败: {exc}") else: # 同一上游订单已有未结束的本地单(规则重跑/上游复用 order_id): # 复用既有 rental_id,绝不插第二行,也不重排计时器(BUG-03 的订阅侧同源问题) print(f"[订阅开锁] order_id={order_id} 已有未结束记录 rental_id={rental_id},复用不重复落单") 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( '{}' '{}'.format( _html.escape(str(k)), _html.escape(str(v))) for k, v in details) return f"""
小白超人 · 车辆订阅

{_html.escape(title)}

{_html.escape(lead)}

{rows}

这是你订阅的定时车辆播报。

""" 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 # 抢占式置位(CAS):多进程/多实例下两个 worker 会同时选到同一批规则, # 只让 UPDATE 真正命中(rowcount==1)的那个进程去发信/开锁, # 否则同一分钟会发两封邮件、勾了自动开锁的还会重复调 /record/order。 claimed = [] try: for r in rules: cur = conn.execute( "UPDATE subscribe_rules SET last_fired_on = ? " "WHERE id = ? AND last_fired_on != ?", (today, r["id"], today)) if cur.rowcount == 1: claimed.append(r) conn.commit() finally: conn.close() for r in claimed: 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 扫描一次)")