Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS`
- `lunar.ts` — Chinese lunar calendar support (1900–2100)
- `currency.ts` — multi-currency / exchange rate conversion

**Notification services** (`worker/src/services/notify/`): Each channel (Telegram, Webhook, Email, Bark, Gotify, NotifyX, WeChatBot) is a separate file. `index.ts` fans out to all enabled channels, with optional per-item channel filtering via the `channels` parameter.
**Notification services** (`worker/src/services/notify/`): Each channel (Telegram, Webhook, Email, Bark, Slack, Feishu, Discord, WeChatBot) is a separate file. `index.ts` fans out to all enabled channels, with optional per-item channel filtering via the `channels` parameter.

**Scheduler** (`worker/src/services/scheduler.ts`): Runs hourly via Cloudflare Cron Trigger (`0 * * * *`). For each active user it:

Expand Down
2 changes: 1 addition & 1 deletion README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ A smart notification management system that helps you track expiry dates and exp
- **Auto-renewal** — Expired subscriptions are automatically renewed with payment history recorded
- **Payment History** — Record every payment, multi-currency with real-time exchange rates
- **Dashboard** — Monthly/yearly expense stats, expiry alerts, category analysis
- **8 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Gotify, NotifyX, Slack
- **8 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Slack, Feishu, Discord
- **Channel Management** — Dedicated page to enable and configure notification channels
- **Per-Item Channel Selection** — Each notification item can specify which channels to use; defaults to all enabled channels if unset
- **Scheduled Reminders** — Hourly auto-check with global notification hours and per-item override
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
- **自动续费** — 过期订阅自动续期并记录支付历史
- **支付历史** — 记录每笔支付,支持多币种与实时汇率转换
- **仪表盘** — 月度/年度支出统计、到期预警、分类分析
- **8 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Gotify、NotifyX、Slack
- **8 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Slack、飞书、Discord
- **渠道管理** — 独立页面统一管理通知渠道的启用与配置
- **按项选择渠道** — 每个通知项可单独指定使用哪些渠道,未指定则默认使用所有已启用渠道
- **定时提醒** — 每小时自动检查并发送到期提醒,支持全局时段配置和每项独立覆盖
Expand Down
8 changes: 6 additions & 2 deletions web/src/components/ChannelSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,13 +186,17 @@ export function ChannelSelector({
<div className="mt-2 flex flex-wrap gap-1">
{selected.map((channelId) => {
const channel = CHANNELS.find((ch) => ch.id === channelId);
if (!channel) return null;
// Unknown IDs are retired channels still stored on old items. They
// are not offered in the dropdown, but must stay removable here:
// otherwise the item could never be saved again (the API rejects
// retired IDs) and it would silently stop notifying.
return (
<span
key={channelId}
title={channel ? undefined : "Retired channel"}
className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-primary/10 text-primary text-xs"
>
{channel.label}
{channel?.label ?? channelId}
<button
type="button"
onClick={() => toggleChannel(channelId)}
Expand Down
4 changes: 2 additions & 2 deletions web/src/lib/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const CHANNELS = [
{ id: "wechatbot", label: "WeCom Bot" },
{ id: "email", label: "Email" },
{ id: "bark", label: "Bark" },
{ id: "gotify", label: "Gotify" },
{ id: "notifyx", label: "NotifyX" },
{ id: "slack", label: "Slack" },
{ id: "feishu", label: "Feishu" },
{ id: "discord", label: "Discord" },
] as const;
4 changes: 2 additions & 2 deletions web/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -344,9 +344,9 @@
"wechatbot": "WeCom Bot",
"email": "Email",
"bark": "Bark",
"gotify": "Gotify",
"notifyx": "NotifyX",
"slack": "Slack",
"feishu": "Feishu Bot",
"discord": "Discord",
"botToken": "Bot Token",
"chatId": "Chat ID",
"url": "URL",
Expand Down
4 changes: 2 additions & 2 deletions web/src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -344,9 +344,9 @@
"wechatbot": "企业微信机器人",
"email": "邮件",
"bark": "Bark",
"gotify": "Gotify",
"notifyx": "NotifyX",
"slack": "Slack",
"feishu": "飞书群机器人",
"discord": "Discord",
"botToken": "机器人令牌",
"chatId": "聊天ID",
"url": "URL",
Expand Down
37 changes: 24 additions & 13 deletions web/src/pages/channels/ChannelPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,32 +107,43 @@ const CHANNELS: ChannelDef[] = [
],
},
{
id: "gotify",
label: "Gotify",
id: "slack",
label: "Slack",
fields: [
{
key: "server_url",
label: "Server URL",
type: "text",
placeholder: "https://",
key: "webhook_url",
label: "Webhook URL",
type: "password",
placeholder: "https://hooks.slack.com/services/...",
},
{ key: "app_token", label: "App Token", type: "password" },
],
},
{
id: "notifyx",
label: "NotifyX",
fields: [{ key: "api_key", label: "API Key", type: "password" }],
id: "feishu",
label: "Feishu",
fields: [
{
key: "webhook_url",
label: "Webhook URL",
type: "password",
placeholder: "https://open.feishu.cn/open-apis/bot/v2/hook/...",
},
{
key: "secret",
label: "Sign Secret (optional)",
type: "password",
},
],
},
{
id: "slack",
label: "Slack",
id: "discord",
label: "Discord",
fields: [
{
key: "webhook_url",
label: "Webhook URL",
type: "password",
placeholder: "https://hooks.slack.com/services/...",
placeholder: "https://discord.com/api/webhooks/...",
},
],
},
Expand Down
4 changes: 2 additions & 2 deletions worker/src/db/queries/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ export async function upsertNotificationConfig(
"wechatbot_config",
"email_config",
"bark_config",
"gotify_config",
"notifyx_config",
"slack_config",
"feishu_config",
"discord_config",
"notification_hours",
];

Expand Down
4 changes: 2 additions & 2 deletions worker/src/db/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs (
wechatbot_config TEXT NOT NULL DEFAULT '{}',
email_config TEXT NOT NULL DEFAULT '{}',
bark_config TEXT NOT NULL DEFAULT '{}',
gotify_config TEXT NOT NULL DEFAULT '{}',
notifyx_config TEXT NOT NULL DEFAULT '{}',
slack_config TEXT NOT NULL DEFAULT '{}',
feishu_config TEXT NOT NULL DEFAULT '{}',
discord_config TEXT NOT NULL DEFAULT '{}',
notification_hours TEXT NOT NULL DEFAULT '[]',
updated_at TEXT NOT NULL
);
Expand Down
39 changes: 30 additions & 9 deletions worker/src/lib/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ const DEFAULT_SETTINGS: Record<string, string> = {
app_name: "eNotify",
};

// Channel IDs whose sender code has been removed. Their DB columns are kept
// (dropping them would require rebuilding the table) but any stale ID left in
// enabled_channels is stripped so it cannot fail every push.
const RETIRED_CHANNELS = ["serverchan", "pushplus", "gotify", "notifyx"];

async function runMigrations(db: D1Database, prefix: string): Promise<void> {
// Migration: add body column to notification_history
try {
Expand Down Expand Up @@ -49,10 +54,28 @@ async function runMigrations(db: D1Database, prefix: string): Promise<void> {
console.error("Migration failed for notification_configs table:", err);
}

// Migration: drop retired channels (serverchan/pushplus) from enabled_channels.
// Their sender code is gone, so a stale ID would make every push fail with
// "Unknown channel" and write a notification_history row. Idempotent: the
// second run finds nothing to strip and performs no UPDATE.
// Migration: add feishu_config / discord_config columns to notification_configs
try {
const notifCols = await db
.prepare(`PRAGMA table_info(${prefix}notification_configs)`)
.all<{ name: string }>();
for (const column of ["feishu_config", "discord_config"]) {
if (!notifCols.results.some((c) => c.name === column)) {
await db
.prepare(
`ALTER TABLE ${prefix}notification_configs ADD COLUMN ${column} TEXT NOT NULL DEFAULT '{}'`,
)
.run();
}
}
} catch (err) {
console.error("Migration failed for notification_configs table:", err);
}

// Migration: drop retired channels (serverchan/pushplus/gotify/notifyx) from
// enabled_channels. Their sender code is gone, so a stale ID would make every
// push fail with "Unknown channel" and write a notification_history row.
// Idempotent: the second run finds nothing to strip and performs no UPDATE.
try {
const rows = await db
.prepare(
Expand All @@ -67,9 +90,7 @@ async function runMigrations(db: D1Database, prefix: string): Promise<void> {
continue;
}
if (!Array.isArray(channels)) continue;
const filtered = channels.filter(
(ch) => ch !== "serverchan" && ch !== "pushplus",
);
const filtered = channels.filter((ch) => !RETIRED_CHANNELS.includes(ch));
if (filtered.length === channels.length) continue;
await db
.prepare(
Expand Down Expand Up @@ -246,9 +267,9 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs (
wechatbot_config TEXT NOT NULL DEFAULT '{}',
email_config TEXT NOT NULL DEFAULT '{}',
bark_config TEXT NOT NULL DEFAULT '{}',
gotify_config TEXT NOT NULL DEFAULT '{}',
notifyx_config TEXT NOT NULL DEFAULT '{}',
slack_config TEXT NOT NULL DEFAULT '{}',
feishu_config TEXT NOT NULL DEFAULT '{}',
discord_config TEXT NOT NULL DEFAULT '{}',
notification_hours TEXT NOT NULL DEFAULT '[]',
updated_at TEXT NOT NULL
);
Expand Down
2 changes: 2 additions & 0 deletions worker/src/routes/me.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ meRoutes.get("/notifications", async (c) => {
"device_key",
"headers",
"webhook_url",
"secret",
].some((s) => k.includes(s))
) {
redacted[k] = v ? "••••••" : "";
Expand Down Expand Up @@ -359,6 +360,7 @@ meRoutes.put("/notifications", async (c) => {
"device_key",
"headers",
"webhook_url",
"secret",
];
for (const [k, v] of Object.entries(newConfig)) {
if (secretFields.some((s) => k.includes(s)) && (!v || v === "••••••")) {
Expand Down
66 changes: 66 additions & 0 deletions worker/src/services/notify/discord.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import type { Env } from "../../types";
import type { NotifyMessage } from "./index";
import { safeErrorText, validateOutboundUrl } from "./safe-fetch";

interface DiscordConfig {
webhook_url: string;
}

const DISCORD_HOSTS = new Set(["discord.com", "discordapp.com"]);
const DISCORD_WEBHOOK_PATH = "/api/webhooks/";
const DISCORD_CONTENT_LIMIT = 2000;

export async function sendDiscord(
configJson: string,
message: NotifyMessage,
_env: Env,
): Promise<{ success: boolean; error?: string }> {
const config: DiscordConfig = JSON.parse(configJson);
if (!config.webhook_url) {
return { success: false, error: "Discord webhook URL required" };
}

const check = validateOutboundUrl(config.webhook_url);
if (check.error || !check.url) {
return {
success: false,
error: `Discord: ${check.error ?? "Invalid URL"}`,
};
}
if (!DISCORD_HOSTS.has(check.url.hostname)) {
return {
success: false,
error: "Discord: webhook URL must be on discord.com or discordapp.com",
};
}
if (!check.url.pathname.startsWith(DISCORD_WEBHOOK_PATH)) {
return {
success: false,
error: `Discord: webhook URL path must start with ${DISCORD_WEBHOOK_PATH}`,
};
}

const lines = [`**${message.title}**`, message.body];
if (message.url) lines.push(message.url);
// Discord caps `content` at 2000 characters. Slice by code point so
// multi-byte characters and surrogate pairs are never split in half.
const content = Array.from(lines.join("\n"))
.slice(0, DISCORD_CONTENT_LIMIT)
.join("");

const response = await fetch(config.webhook_url, {
method: "POST",
redirect: "manual",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content }),
});

if (response.status !== 200 && response.status !== 204) {
const err = await safeErrorText(response);
return {
success: false,
error: `Discord error (${response.status}): ${err}`,
};
}
return { success: true };
}
Loading
Loading