Unify city+cafe into one places page, gate join with on-page modal, and enrich ntfy with icons, tables, and action buttons across portal/API/admin. Co-authored-by: Cursor <cursoragent@cursor.com>
157 lines
5.1 KiB
Python
157 lines
5.1 KiB
Python
"""把关键事件推到自建 ntfy(https://ntfy.nomadro.cn)— Markdown 富文本。"""
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from typing import Any
|
||
|
||
import httpx
|
||
|
||
from ebook_svc.config import settings
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
DEFAULT_ICON = "https://nomadro.com/icon-192.png"
|
||
|
||
|
||
async def notify(
|
||
message: str,
|
||
*,
|
||
title: str = "Nomadmini",
|
||
tags: str | None = None,
|
||
priority: int = 3,
|
||
markdown: bool = True,
|
||
click: str | None = None,
|
||
icon: str | None = DEFAULT_ICON,
|
||
attach: str | None = None,
|
||
filename: str | None = None,
|
||
actions: list[dict[str, Any]] | None = None,
|
||
) -> bool:
|
||
if not settings.ntfy_enabled:
|
||
return False
|
||
base = settings.ntfy_base_url.rstrip("/")
|
||
topic = settings.ntfy_topic.strip().strip("/")
|
||
if not base or not topic:
|
||
return False
|
||
|
||
payload: dict[str, Any] = {
|
||
"topic": topic,
|
||
"message": (message or "")[:3900],
|
||
"title": (title or "Nomadro")[:200],
|
||
"priority": max(1, min(5, int(priority))),
|
||
"markdown": bool(markdown),
|
||
}
|
||
if tags:
|
||
payload["tags"] = [t.strip() for t in tags.split(",") if t.strip()][:12]
|
||
if icon:
|
||
payload["icon"] = icon[:512]
|
||
if click:
|
||
payload["click"] = click[:512]
|
||
if attach:
|
||
payload["attach"] = attach[:512]
|
||
if filename:
|
||
payload["filename"] = filename[:120]
|
||
if actions:
|
||
payload["actions"] = actions[:3]
|
||
|
||
headers: dict[str, str] = {"Content-Type": "application/json"}
|
||
token = (settings.ntfy_token or "").strip()
|
||
if token:
|
||
headers["Authorization"] = f"Bearer {token}"
|
||
|
||
try:
|
||
async with httpx.AsyncClient(timeout=8.0) as client:
|
||
r = await client.post(base, json=payload, headers=headers)
|
||
if r.status_code >= 400:
|
||
logger.warning("ntfy publish failed: %s %s", r.status_code, r.text[:200])
|
||
return False
|
||
return True
|
||
except Exception:
|
||
logger.exception("ntfy publish error")
|
||
return False
|
||
|
||
|
||
def _esc(value: Any, limit: int = 180) -> str:
|
||
s = str(value if value is not None else "").replace("|", "\\|").replace("\n", " ").strip()
|
||
return s[:limit]
|
||
|
||
|
||
def format_rich_message(
|
||
*,
|
||
headline: str,
|
||
bullets: list[tuple[str, str]] | None = None,
|
||
table: list[tuple[str, str]] | None = None,
|
||
footer: str | None = None,
|
||
links: list[tuple[str, str]] | None = None,
|
||
) -> str:
|
||
lines: list[str] = [f"### {_esc(headline)}", ""]
|
||
for k, v in bullets or []:
|
||
if not v:
|
||
continue
|
||
lines.append(f"- **{_esc(k)}** `{_esc(v)}`")
|
||
if table:
|
||
lines.extend(["", "| 字段 | 值 |", "| --- | --- |"])
|
||
for k, v in table[:14]:
|
||
if v is None or v == "":
|
||
continue
|
||
lines.append(f"| {_esc(k)} | `{_esc(v)}` |")
|
||
if footer:
|
||
lines.extend(["", _esc(footer, 240)])
|
||
for label, url in links or []:
|
||
if url:
|
||
lines.append(f"[{_esc(label, 40)}]({_esc(url, 400)})")
|
||
return "\n".join(lines)[:3900]
|
||
|
||
|
||
def summarize_wx_event(root: dict[str, Any]) -> tuple[str, str, str]:
|
||
"""返回 (title, message, tags)。"""
|
||
event = str(root.get("Event") or root.get("event") or "")
|
||
msg_type = str(root.get("MsgType") or root.get("msg_type") or "").lower()
|
||
openid = str(root.get("OpenId") or root.get("FromUserName") or root.get("openid") or "")
|
||
openid_short = f"…{openid[-8:]}" if len(openid) > 8 else (openid or "—")
|
||
|
||
if event == "xpay_goods_deliver_notify" or root.get("GoodsInfo") or root.get("OutTradeNo"):
|
||
out_trade_no = root.get("OutTradeNo") or root.get("out_trade_no") or "-"
|
||
product = ""
|
||
gi = root.get("GoodsInfo") or {}
|
||
if isinstance(gi, dict):
|
||
product = str(gi.get("ProductId") or gi.get("product_id") or "")
|
||
title = "支付发货"
|
||
msg = format_rich_message(
|
||
headline="💰 支付发货",
|
||
bullets=[
|
||
("订单", str(out_trade_no)),
|
||
("道具", product or "—"),
|
||
("用户", openid_short),
|
||
],
|
||
table=[(k, str(v)) for k, v in list(root.items())[:8] if k not in {"GoodsInfo"}],
|
||
)
|
||
return title, msg, "moneybag,white_check_mark"
|
||
|
||
if msg_type in {"text", "image", "voice", "video", "miniprogrampage"}:
|
||
content = str(root.get("Content") or root.get("Recognition") or "")[:180]
|
||
title = "用户消息"
|
||
msg = format_rich_message(
|
||
headline="💬 用户消息",
|
||
bullets=[
|
||
("类型", msg_type),
|
||
("用户", openid_short),
|
||
("内容", content or f"收到 {msg_type}"),
|
||
],
|
||
)
|
||
return title, msg, "speech_balloon"
|
||
|
||
if event:
|
||
title = "微信事件"
|
||
msg = format_rich_message(
|
||
headline="🔔 微信事件",
|
||
bullets=[("事件", event), ("用户", openid_short)],
|
||
)
|
||
return title, msg, "bell"
|
||
|
||
title = "微信推送"
|
||
msg = format_rich_message(
|
||
headline="📩 微信推送",
|
||
bullets=[("摘要", str(root)[:180])],
|
||
)
|
||
return title, msg, "incoming_envelope"
|