nomadro/src/lib/ntfy-rich.ts
Eric 3e60ba1a1b Ship social places/join UX, room-archive ops, and rich Markdown ntfy alerts.
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>
2026-11-05 12:21:01 +08:00

248 lines
6.5 KiB
TypeScript

/**
* Build detailed Markdown bodies + actions for ntfy clients.
*/
import type { NtfyAction, NtfyPublishInput } from "~/lib/ntfy";
export type TrackLikeEvent = {
name?: string;
page?: string;
label?: string;
props?: Record<string, unknown>;
ts?: number;
};
const PROP_LABEL: Record<string, string> = {
audience: "受众",
device: "设备",
browser: "浏览器",
screen: "屏幕",
lang: "语言",
tz: "时区",
href: "链接",
title: "页面标题",
text: "文案",
el: "元素",
role: "角色",
role_cn: "角色中文",
paid_type: "付费类型",
email: "邮箱",
name: "昵称",
user_id: "用户ID",
channel: "渠道",
popup: "弹窗",
offline: "离线",
amount: "金额",
orderId: "订单",
out_trade_no: "商户单号",
gateway: "网关",
plan: "套餐",
city: "城市",
roomId: "房间",
alive_ms: "停留(ms)",
};
const SKIP_PROPS = new Set(["password", "token", "secret", "authorization"]);
function esc(value: unknown): string {
return String(value ?? "")
.replace(/\|/g, "\\|")
.replace(/\n/g, " ")
.trim()
.slice(0, 180);
}
function shortUid(uid: string | undefined): string {
const u = (uid || "").trim();
if (!u) return "—";
return u.length > 12 ? `…${u.slice(-10)}` : u;
}
function fmtTime(ts?: number): string {
const d = ts && Number.isFinite(ts) ? new Date(ts) : new Date();
try {
return new Intl.DateTimeFormat("zh-CN", {
timeZone: "Asia/Shanghai",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
}).format(d);
} catch {
return d.toISOString();
}
}
function propRows(props: Record<string, unknown> | undefined): string[] {
if (!props) return [];
const rows: string[] = [];
for (const [k, v] of Object.entries(props)) {
if (SKIP_PROPS.has(k.toLowerCase())) continue;
if (v == null || v === "") continue;
if (typeof v === "object") continue;
const label = PROP_LABEL[k] || k;
let display = esc(v);
if (k === "popup" && v === "douyin") display = "抖音群";
if (k === "popup" && v === "wechat") display = "公众号";
if (k === "offline" && v) display = "是";
if (k === "alive_ms" && typeof v === "number") {
display = `${Math.round(v / 1000)}s`;
}
rows.push(`| ${label} | \`${display}\` |`);
}
return rows.slice(0, 14);
}
function eventEmoji(name: string): string {
if (name.startsWith("pay_")) return "💰";
if (name.startsWith("login_")) return "🔑";
if (name.startsWith("join_")) return "👥";
if (name.startsWith("follow_")) return "❤️";
if (name === "error") return "🚨";
if (name === "session_start") return "🌊";
if (name === "page_view") return "👀";
if (name === "book_complete") return "📚";
if (name === "feedback_submit") return "✉️";
if (name === "share_x") return "🐦";
return "📡";
}
export function adminEventsUrl(site: string): string {
if (site.includes("nomadro.com") || site === "web_intl") {
return "https://admin.nomadro.com/intl/events";
}
return "https://admin.nomadro.cn/";
}
export function buildTrackNtfyPayload(input: {
name: string;
title: string;
site: string;
openid?: string;
client?: string;
event: TrackLikeEvent;
tags?: string;
priority?: NtfyPublishInput["priority"];
topic?: string;
}): NtfyPublishInput {
const { name, title, site, openid, client, event } = input;
const props = (event.props || {}) as Record<string, unknown>;
const href =
typeof props.href === "string" && props.href.startsWith("http")
? props.href
: "";
const page = String(event.page || "").slice(0, 80);
const label = String(event.label || "").slice(0, 160);
const email =
typeof props.email === "string" ? String(props.email).slice(0, 80) : "";
const nick =
typeof props.name === "string"
? String(props.name).slice(0, 40)
: typeof props.role_cn === "string"
? String(props.role_cn).slice(0, 40)
: "";
const lines: string[] = [
`### ${eventEmoji(name)} ${esc(title)}`,
"",
`- **站点** \`${esc(site)}\``,
`- **客户端** \`${esc(client || "web")}\``,
`- **用户** \`${shortUid(openid)}\`${nick ? ` · **${esc(nick)}**` : ""}`,
];
if (email) lines.push(`- **邮箱** \`${esc(email)}\``);
if (page) lines.push(`- **页面** \`${esc(page)}\``);
if (label) lines.push(`- **标签** ${esc(label)}`);
lines.push(`- **时间** ${fmtTime(event.ts)}`);
const rows = propRows(props);
if (rows.length) {
lines.push("", "| 字段 | 值 |", "| --- | --- |", ...rows);
}
if (href) {
lines.push("", `[打开来源页](${href})`);
}
const adminUrl = adminEventsUrl(site);
lines.push("", `[打开后台事件](${adminUrl})`);
const actions: NtfyAction[] = [
{
action: "view",
label: "后台事件",
url: adminUrl,
clear: true,
},
];
if (href) {
actions.push({ action: "view", label: "来源页", url: href, clear: true });
}
if (site.includes("nomadro.com")) {
actions.push({
action: "view",
label: "门户",
url: "https://nomadro.com/",
clear: true,
});
}
return {
title: title.slice(0, 80),
message: lines.join("\n").slice(0, 3900),
tags: input.tags,
priority: input.priority,
topic: input.topic,
markdown: true,
click: href || adminUrl,
icon: "https://nomadro.com/icon-192.png",
actions: actions.slice(0, 3),
};
}
export function buildPlainRichNtfy(input: {
title: string;
headline?: string;
bullets?: Array<[string, string]>;
table?: Array<[string, string]>;
footer?: string;
click?: string;
tags?: string;
priority?: NtfyPublishInput["priority"];
actions?: NtfyAction[];
attach?: string;
}): NtfyPublishInput {
const lines: string[] = [
`### ${esc(input.headline || input.title)}`,
"",
];
for (const [k, v] of input.bullets || []) {
lines.push(`- **${esc(k)}** ${esc(v)}`);
}
if (input.table?.length) {
lines.push("", "| 字段 | 值 |", "| --- | --- |");
for (const [k, v] of input.table) {
lines.push(`| ${esc(k)} | \`${esc(v)}\` |`);
}
}
if (input.footer) {
lines.push("", esc(input.footer));
}
if (input.click) {
lines.push("", `[打开链接](${input.click})`);
}
return {
title: input.title.slice(0, 80),
message: lines.join("\n").slice(0, 3900),
markdown: true,
tags: input.tags,
priority: input.priority,
click: input.click,
icon: "https://nomadro.com/icon-192.png",
attach: input.attach,
actions: input.actions?.slice(0, 3),
};
}