diff --git a/CLAUDE.md b/CLAUDE.md index 8affa10..9148f49 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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, ServerChan, PushPlus, 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, 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. **Scheduler** (`worker/src/services/scheduler.ts`): Runs hourly via Cloudflare Cron Trigger (`0 * * * *`). For each active user it: diff --git a/README.en.md b/README.en.md index 54e8177..44d29b8 100644 --- a/README.en.md +++ b/README.en.md @@ -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 -- **10 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Gotify, ServerChan, PushPlus, NotifyX, Slack +- **8 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Gotify, NotifyX, Slack - **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 diff --git a/README.md b/README.md index 193bd93..102b368 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ - **自动续费** — 过期订阅自动续期并记录支付历史 - **支付历史** — 记录每笔支付,支持多币种与实时汇率转换 - **仪表盘** — 月度/年度支出统计、到期预警、分类分析 -- **10 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Gotify、Server酱、PushPlus、NotifyX、Slack +- **8 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Gotify、NotifyX、Slack - **渠道管理** — 独立页面统一管理通知渠道的启用与配置 - **按项选择渠道** — 每个通知项可单独指定使用哪些渠道,未指定则默认使用所有已启用渠道 - **定时提醒** — 每小时自动检查并发送到期提醒,支持全局时段配置和每项独立覆盖 diff --git a/web/src/lib/channels.ts b/web/src/lib/channels.ts index a4a9fee..6ff3087 100644 --- a/web/src/lib/channels.ts +++ b/web/src/lib/channels.ts @@ -5,8 +5,6 @@ export const CHANNELS = [ { id: "email", label: "Email" }, { id: "bark", label: "Bark" }, { id: "gotify", label: "Gotify" }, - { id: "serverchan", label: "ServerChan" }, - { id: "pushplus", label: "PushPlus" }, { id: "notifyx", label: "NotifyX" }, { id: "slack", label: "Slack" }, ] as const; diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 1a72c70..aed88bf 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -345,8 +345,6 @@ "email": "Email", "bark": "Bark", "gotify": "Gotify", - "serverchan": "ServerChan", - "pushplus": "PushPlus", "notifyx": "NotifyX", "slack": "Slack", "botToken": "Bot Token", @@ -361,11 +359,8 @@ "server": "Server", "serverUrl": "Server URL", "appToken": "App Token", - "sendKey": "SendKey", "apiKey": "API Key", "token": "Token", - "topic": "Topic (optional)", - "channelName": "Channel (optional)", "selectChannels": "Select Notification Channels", "allChannels": "All enabled channels", "selectedChannels": "{{count}} channels selected", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index eb98910..f0bda25 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -345,8 +345,6 @@ "email": "邮件", "bark": "Bark", "gotify": "Gotify", - "serverchan": "Server酱", - "pushplus": "PushPlus", "notifyx": "NotifyX", "slack": "Slack", "botToken": "机器人令牌", @@ -361,11 +359,8 @@ "server": "服务器", "serverUrl": "服务器 URL", "appToken": "应用令牌", - "sendKey": "SendKey", "apiKey": "API 密钥", "token": "令牌", - "topic": "主题(可选)", - "channelName": "频道(可选)", "selectChannels": "选择通知渠道", "allChannels": "所有已启用的渠道", "selectedChannels": "已选择 {{count}} 个渠道", diff --git a/web/src/pages/channels/ChannelPage.tsx b/web/src/pages/channels/ChannelPage.tsx index e97a62d..577989a 100644 --- a/web/src/pages/channels/ChannelPage.tsx +++ b/web/src/pages/channels/ChannelPage.tsx @@ -119,20 +119,6 @@ const CHANNELS: ChannelDef[] = [ { key: "app_token", label: "App Token", type: "password" }, ], }, - { - id: "serverchan", - label: "ServerChan", - fields: [{ key: "sendkey", label: "SendKey", type: "text" }], - }, - { - id: "pushplus", - label: "PushPlus", - fields: [ - { key: "token", label: "Token", type: "text" }, - { key: "topic", label: "Topic (optional)", type: "text" }, - { key: "channel", label: "Channel (optional)", type: "text" }, - ], - }, { id: "notifyx", label: "NotifyX", diff --git a/worker/src/db/queries/notifications.ts b/worker/src/db/queries/notifications.ts index 063693c..4d2ced7 100644 --- a/worker/src/db/queries/notifications.ts +++ b/worker/src/db/queries/notifications.ts @@ -36,8 +36,6 @@ export async function upsertNotificationConfig( "email_config", "bark_config", "gotify_config", - "serverchan_config", - "pushplus_config", "notifyx_config", "slack_config", "notification_hours", diff --git a/worker/src/db/schema.sql b/worker/src/db/schema.sql index c37be7f..da03079 100644 --- a/worker/src/db/schema.sql +++ b/worker/src/db/schema.sql @@ -85,8 +85,6 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( email_config TEXT NOT NULL DEFAULT '{}', bark_config TEXT NOT NULL DEFAULT '{}', gotify_config TEXT NOT NULL DEFAULT '{}', - serverchan_config TEXT NOT NULL DEFAULT '{}', - pushplus_config TEXT NOT NULL DEFAULT '{}', notifyx_config TEXT NOT NULL DEFAULT '{}', slack_config TEXT NOT NULL DEFAULT '{}', notification_hours TEXT NOT NULL DEFAULT '[]', diff --git a/worker/src/lib/setup.ts b/worker/src/lib/setup.ts index 5ef03fc..e25cace 100644 --- a/worker/src/lib/setup.ts +++ b/worker/src/lib/setup.ts @@ -49,6 +49,39 @@ async function runMigrations(db: D1Database, prefix: string): Promise { 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. + try { + const rows = await db + .prepare( + `SELECT user_id, enabled_channels FROM ${prefix}notification_configs`, + ) + .all<{ user_id: string; enabled_channels: string }>(); + for (const row of rows.results) { + let channels: unknown; + try { + channels = JSON.parse(row.enabled_channels || "[]"); + } catch { + continue; + } + if (!Array.isArray(channels)) continue; + const filtered = channels.filter( + (ch) => ch !== "serverchan" && ch !== "pushplus", + ); + if (filtered.length === channels.length) continue; + await db + .prepare( + `UPDATE ${prefix}notification_configs SET enabled_channels = ? WHERE user_id = ?`, + ) + .bind(JSON.stringify(filtered), row.user_id) + .run(); + } + } catch (err) { + console.error("Migration failed to drop retired channels:", err); + } + // Migration: items table columns (type/use_lunar -> calendar_mode, lunar_expiry_date). // Uses ALTER TABLE instead of recreating the table: DROP TABLE would cascade-delete payment_history. try { @@ -214,8 +247,6 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( email_config TEXT NOT NULL DEFAULT '{}', bark_config TEXT NOT NULL DEFAULT '{}', gotify_config TEXT NOT NULL DEFAULT '{}', - serverchan_config TEXT NOT NULL DEFAULT '{}', - pushplus_config TEXT NOT NULL DEFAULT '{}', notifyx_config TEXT NOT NULL DEFAULT '{}', slack_config TEXT NOT NULL DEFAULT '{}', notification_hours TEXT NOT NULL DEFAULT '[]', diff --git a/worker/src/services/notify/index.ts b/worker/src/services/notify/index.ts index 9438b46..3faac89 100644 --- a/worker/src/services/notify/index.ts +++ b/worker/src/services/notify/index.ts @@ -4,8 +4,6 @@ import { sendWebhook } from "./webhook"; import { sendWechatBot } from "./wechatbot"; import { sendBark } from "./bark"; import { sendGotify } from "./gotify"; -import { sendServerChan } from "./serverchan"; -import { sendPushPlus } from "./pushplus"; import { sendNotifyX } from "./notifyx"; import { sendSlack } from "./slack"; import { sendNotifyEmail } from "./email-notify"; @@ -46,8 +44,6 @@ const CHANNEL_SENDERS: Record< email: sendNotifyEmail, bark: sendBark, gotify: sendGotify, - serverchan: sendServerChan, - pushplus: sendPushPlus, notifyx: sendNotifyX, slack: sendSlack, }; diff --git a/worker/src/services/notify/pushplus.ts b/worker/src/services/notify/pushplus.ts deleted file mode 100644 index 564b484..0000000 --- a/worker/src/services/notify/pushplus.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { NotifyMessage } from "./index"; -import type { Env } from "../../types"; - -interface PushPlusConfig { - token: string; - topic?: string; - channel?: string; -} - -export async function sendPushPlus( - configJson: string, - message: NotifyMessage, - _env: Env, -): Promise<{ success: boolean; error?: string }> { - const config: PushPlusConfig = JSON.parse(configJson); - if (!config.token) { - return { success: false, error: "PushPlus token required" }; - } - - const body: Record = { - token: config.token, - title: message.title, - content: message.body, - }; - - if (config.topic) body.topic = config.topic; - if (config.channel) body.channel = config.channel; - - const response = await fetch("https://www.pushplus.plus/send", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); - - if (!response.ok) { - const err = await response.text(); - return { success: false, error: `PushPlus error: ${err}` }; - } - - return { success: true }; -} diff --git a/worker/src/services/notify/serverchan.ts b/worker/src/services/notify/serverchan.ts deleted file mode 100644 index ffd6d2e..0000000 --- a/worker/src/services/notify/serverchan.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { NotifyMessage } from "./index"; -import type { Env } from "../../types"; - -interface ServerChanConfig { - sendkey: string; -} - -export async function sendServerChan( - configJson: string, - message: NotifyMessage, - _env: Env, -): Promise<{ success: boolean; error?: string }> { - const config: ServerChanConfig = JSON.parse(configJson); - if (!config.sendkey) { - return { success: false, error: "ServerChan sendkey required" }; - } - - const response = await fetch( - `https://sctapi.ftqq.com/${config.sendkey}.send`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - title: message.title, - desp: message.body, - }), - }, - ); - - if (!response.ok) { - const err = await response.text(); - return { success: false, error: `ServerChan error: ${err}` }; - } - - return { success: true }; -} diff --git a/worker/src/types.ts b/worker/src/types.ts index 416760a..b199e16 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -83,8 +83,6 @@ export interface NotificationConfig { email_config: string; bark_config: string; gotify_config: string; - serverchan_config: string; - pushplus_config: string; notifyx_config: string; slack_config: string; notification_hours: string; @@ -131,8 +129,6 @@ export const VALID_CHANNELS: string[] = [ "email", "bark", "gotify", - "serverchan", - "pushplus", "notifyx", "slack", ]; diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts index d6ce7e7..6af02b3 100644 --- a/worker/test/migrations.test.ts +++ b/worker/test/migrations.test.ts @@ -1,7 +1,8 @@ import { DatabaseSync } from "node:sqlite"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { runSetup } from "../src/lib/setup"; -import type { Env } from "../src/types"; +import { sendNotifications } from "../src/services/notify/index"; +import type { Env, NotificationConfig } from "../src/types"; /** * Minimal D1 stand-in backed by a real in-memory SQLite database. Unlike the @@ -172,3 +173,159 @@ describe("notification_configs slack_config migration", () => { expect(rows[0].slack_config).toBe("{}"); }); }); + +/** Seed a legacy database whose enabled_channels still lists retired channels. */ +function seedLegacyChannels(d1: SqliteD1): void { + d1.db.exec(OLD_SCHEMA); + d1.db + .prepare( + `UPDATE ${PREFIX}notification_configs + SET enabled_channels = ?, telegram_config = ? + WHERE user_id = ?`, + ) + .run( + '["telegram","serverchan","pushplus"]', + '{"bot_token":"secret","chat_id":"42"}', + "u1", + ); + d1.db + .prepare( + `INSERT INTO ${PREFIX}notification_configs (user_id, enabled_channels, updated_at) + VALUES (?, ?, ?)`, + ) + .run("u2", '["bark"]', "2026-01-01T00:00:00.000Z"); + d1.db + .prepare( + `INSERT INTO ${PREFIX}users (id, email, password_hash, created_at, updated_at) + VALUES (?, ?, ?, ?, ?)`, + ) + .run( + "u3", + "u3@example.com", + "hash", + "2026-01-01T00:00:00.000Z", + "2026-01-01T00:00:00.000Z", + ); + d1.db + .prepare( + `INSERT INTO ${PREFIX}notification_configs (user_id, enabled_channels, updated_at) + VALUES (?, ?, ?)`, + ) + .run("u3", "not-json", "2026-01-01T00:00:00.000Z"); + // Inserted after the malformed row (SQLite returns rows in rowid order here), + // so this row is only cleaned if the migration skips bad rows one by one + // instead of aborting the whole loop on the first parse error. + d1.db + .prepare( + `INSERT INTO ${PREFIX}users (id, email, password_hash, created_at, updated_at) + VALUES (?, ?, ?, ?, ?)`, + ) + .run( + "u4", + "u4@example.com", + "hash", + "2026-01-01T00:00:00.000Z", + "2026-01-01T00:00:00.000Z", + ); + d1.db + .prepare( + `INSERT INTO ${PREFIX}notification_configs (user_id, enabled_channels, updated_at) + VALUES (?, ?, ?)`, + ) + .run("u4", '["telegram","serverchan"]', "2026-01-01T00:00:00.000Z"); +} + +function enabledChannelsOf(d1: SqliteD1, userId: string): unknown { + const row = d1.db + .prepare( + `SELECT enabled_channels FROM ${PREFIX}notification_configs WHERE user_id = ?`, + ) + .get(userId) as Record; + return row.enabled_channels; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("retired channel cleanup migration", () => { + it("strips serverchan and pushplus from enabled_channels", async () => { + const d1 = new SqliteD1(); + seedLegacyChannels(d1); + + await runSetup(makeEnv(d1)); + + expect(enabledChannelsOf(d1, "u1")).toBe('["telegram"]'); + // Rows without retired channels are left untouched. + expect(enabledChannelsOf(d1, "u2")).toBe('["bark"]'); + // A malformed value is skipped without aborting the migration: u4 comes + // after the bad row, so it is only stripped if processing continued. + expect(enabledChannelsOf(d1, "u3")).toBe("not-json"); + expect(enabledChannelsOf(d1, "u4")).toBe('["telegram"]'); + }); + + it("is idempotent", async () => { + const d1 = new SqliteD1(); + seedLegacyChannels(d1); + + await runSetup(makeEnv(d1)); + const second = await runSetup(makeEnv(d1)); + expect(second).toEqual({ success: true, alreadyInitialized: true }); + + expect(enabledChannelsOf(d1, "u1")).toBe('["telegram"]'); + expect(enabledChannelsOf(d1, "u2")).toBe('["bark"]'); + expect(enabledChannelsOf(d1, "u3")).toBe("not-json"); + expect(enabledChannelsOf(d1, "u4")).toBe('["telegram"]'); + }); + + it("no longer reports unknown channels after the migration", async () => { + const d1 = new SqliteD1(); + seedLegacyChannels(d1); + await runSetup(makeEnv(d1)); + + const fetchMock = vi.fn(async () => new Response("ok", { status: 200 })); + vi.stubGlobal("fetch", fetchMock); + + const config = d1.db + .prepare(`SELECT * FROM ${PREFIX}notification_configs WHERE user_id = ?`) + .get("u1") as unknown as NotificationConfig; + + const results = await sendNotifications( + config, + { title: "Renewal due", body: "Your plan expires soon." }, + makeEnv(d1), + { + db: d1 as unknown as D1Database, + prefix: PREFIX, + userId: "u1", + }, + ); + + expect(results).toEqual([{ channel: "telegram", success: true }]); + expect(fetchMock).toHaveBeenCalledTimes(1); + + const history = d1.db + .prepare(`SELECT channel, error FROM ${PREFIX}notification_history`) + .all() as { channel: string; error: string | null }[]; + expect(history).toHaveLength(1); + expect(history[0].channel).toBe("telegram"); + expect(history[0].error).toBeNull(); + }); +}); + +describe("fresh install schema", () => { + it("creates notification_configs without the retired channel columns", async () => { + const d1 = new SqliteD1(); + + const result = await runSetup(makeEnv(d1)); + expect(result).toEqual({ success: true }); + + const columns = d1.db + .prepare(`PRAGMA table_info(${PREFIX}notification_configs)`) + .all() as ColumnInfo[]; + const names = columns.map((c) => c.name); + expect(names).not.toContain("serverchan_config"); + expect(names).not.toContain("pushplus_config"); + expect(names).toContain("slack_config"); + }); +});