import React, { useEffect, useState } from 'react'; import { createPortal } from 'react-dom'; import { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../types'; import { getNotificationChannels, createNotificationChannel, updateNotificationChannel, deleteNotificationChannel, testNotificationChannel, getSystemSettings, updateSystemSettings, } from '../services/api'; import { Bell, Plus, Edit2, Trash2, X, Send, RefreshCw, Loader2, Check, MessageCircle, Mail, Webhook, Send as Telegram, Eye, EyeOff, Save, } from 'lucide-react'; import { normalizeSMTPSettings } from '../smtpSettings'; import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../notificationEmailConfig'; type ChannelTypeMeta = { label: string; icon: React.ElementType; fields: { key: string; label: string; placeholder?: string; type?: 'text' | 'password' | 'number'; required?: boolean; help?: string }[]; guide: { steps: string[]; urlFormat?: string; note?: string }; }; const CHANNEL_TYPES: Record = { bark: { label: 'Bark', icon: Bell, fields: [ { key: 'server_url', label: 'Bark 服务器', placeholder: 'https://api.day.app', required: true }, { key: 'device_key', label: 'Device Key', placeholder: '你的 Bark 设备 Key', required: true }, { key: 'title', label: '标题(可选)', placeholder: 'Ydisks闲鱼助手' }, { key: 'sound', label: '铃声(可选)', placeholder: 'default' }, { key: 'group', label: '分组(可选)', placeholder: 'xianyu' }, ], guide: { steps: [ 'App Store 搜索并安装 Bark(免费)', '打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容', 'URL 路径里 那一段就是 Device Key,复制填入', '服务器地址默认 https://api.day.app,自建服务端则填自建域名', ], urlFormat: 'https://api.day.app/<你的key>/测试内容', note: '不需要 secret,Device Key 本身就是唯一凭证。', }, }, dingtalk: { label: '钉钉机器人', icon: MessageCircle, fields: [ { key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://oapi.dingtalk.com/robot/send?access_token=...', required: true }, { key: 'secret', label: '加签密钥', placeholder: 'SEC...', help: '安全设置勾选「加签」后生成,SEC 开头' }, ], guide: { steps: [ '钉钉进入一个群(可建单人群)→ 右上角 群设置', '机器人 → 添加机器人 → 选择「自定义机器人」', '安全设置勾选「加签」', '完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制', 'Webhook URL 填上面,Secret 填加签密钥', ], urlFormat: 'https://oapi.dingtalk.com/robot/send?access_token=XXX', note: '加签密钥可选,但强烈建议启用,否则机器人可能被滥用。', }, }, feishu: { label: '飞书机器人', icon: MessageCircle, fields: [ { key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://open.feishu.cn/open-apis/bot/v2/hook/...', required: true }, { key: 'secret', label: '签名校验密钥', placeholder: 'sec-...', help: '安全设置选「签名校验」后生成' }, ], guide: { steps: [ '飞书进入目标群 → 右上角 更多 → 设置', '群机器人 → 添加机器人 → 自定义机器人', '安全设置选择「签名校验」,复制生成的秘钥', '完成会给 Webhook 地址,复制', 'Webhook URL 填上面,秘钥填签名校验密钥', ], urlFormat: 'https://open.feishu.cn/open-apis/bot/v2/hook/xxx', note: '签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。', }, }, wechat: { label: '企业微信机器人', icon: MessageCircle, fields: [ { key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...', required: true }, ], guide: { steps: [ '企业微信进入一个内部群 → 右上角 … → 群设置', '找到「群机器人」(新版可能叫「消息推送」)', '添加 → 选择自定义机器人', '完成给 Webhook 地址(含 ?key=),复制填入', ], urlFormat: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX', note: '不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。', }, }, webhook: { label: '自定义 Webhook', icon: Webhook, fields: [ { key: 'webhook_url', label: 'Webhook URL', placeholder: 'https://your-server/notify', required: true }, ], guide: { steps: [ '仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON', '系统会 POST 这个 URL,Content-Type: application/json', '请求体固定为右侧 JSON 格式,按需解析 message 字段', ], urlFormat: '{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}', note: '若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。', }, }, telegram: { label: 'Telegram', icon: Telegram, fields: [ { key: 'bot_token', label: 'Bot Token', placeholder: '123456:ABC-DEF...', required: true }, { key: 'chat_id', label: 'Chat ID', placeholder: '-1001234567890 或你的用户 ID', required: true }, ], guide: { steps: [ '在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token', '把你的 Bot 拉进一个群,或私聊它发一条消息', '浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates', '从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)', ], urlFormat: 'Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890', note: '群聊需先把 Bot 设为管理员才能发消息。', }, }, email: { label: '邮件', icon: Mail, fields: [ { key: 'to_email', label: '收件邮箱', placeholder: 'receiver@example.com', required: true }, ], guide: { steps: [ '通常先保存页面中的系统 SMTP 配置', '邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP', '只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置', ], note: '继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。', }, }, }; const NOTIFICATION_EVENTS: { value: NotificationEventType; label: string; description: string }[] = [ { value: 'account_offline', label: '掉线通知', description: '账号过期、断线或登录态失效' }, { value: 'account_recovered', label: '恢复通知', description: '自动恢复成功并重新在线' }, { value: 'account_disabled', label: '禁用通知', description: '连续失败、账密错误等导致账号停用' }, { value: 'security_verification', label: '风控验证', description: '滑块、人脸、扫码验证等安全校验' }, { value: 'delivery_result', label: '交易通知', description: '订单发货、卡密发送等交易结果' }, { value: 'token_renewal', label: '续期通知', description: 'Cookie/token 续期和自动恢复过程' }, { value: 'system_error', label: '系统错误', description: '后台任务或系统级异常' }, ]; const notificationEventSummary = (events?: NotificationEventType[]) => { if (!events || events.length === 0) return '全部事件'; const labels = events.map(event => NOTIFICATION_EVENTS.find(item => item.value === event)?.label || event); return labels.join('、'); }; interface NotificationsProps { isAdmin?: boolean; } const Notifications: React.FC = ({ isAdmin = false }) => { const [channels, setChannels] = useState([]); const [loading, setLoading] = useState(true); const [showModal, setShowModal] = useState(false); const [editing, setEditing] = useState(null); const [saving, setSaving] = useState(false); const [testingId, setTestingId] = useState(''); const [toast, setToast] = useState<{ type: 'success' | 'error'; text: string } | null>(null); // SMTP 系统级邮件配置(从系统设置加载/保存) const [smtp, setSmtp] = useState({}); const [smtpSaving, setSmtpSaving] = useState(false); const [showSmtpPassword, setShowSmtpPassword] = useState(false); const [showChannelSmtpPassword, setShowChannelSmtpPassword] = useState(false); const [form, setForm] = useState({ name: '', type: 'bark' as NotificationChannelType, enabled: true, config: {} as Record, event_types: [] as NotificationEventType[], }); const load = async () => { setLoading(true); try { const res = await getNotificationChannels(); setChannels(res.data || []); } catch (e) { console.error('加载通知渠道失败', e); } finally { setLoading(false); } }; const loadSmtp = async () => { try { const s = await getSystemSettings(); setSmtp(normalizeSMTPSettings(s || {})); } catch (e) { console.error('加载 SMTP 配置失败', e); } }; const handleSaveSmtp = async () => { setSmtpSaving(true); try { await updateSystemSettings({ smtp_server: smtp.smtp_server || '', smtp_port: smtp.smtp_port || 587, smtp_user: smtp.smtp_user || '', smtp_password: smtp.smtp_password || '', smtp_from_name: smtp.smtp_from_name || '', smtp_from_address: smtp.smtp_from_address || smtp.smtp_user || '', smtp_use_tls: smtp.smtp_use_tls !== false, smtp_use_ssl: smtp.smtp_use_ssl === true, }); showToast('success', 'SMTP 配置已保存'); } catch (e: any) { showToast('error', e?.message || '保存失败'); } finally { setSmtpSaving(false); } }; useEffect(() => { load(); if (isAdmin) { loadSmtp(); } else { setSmtp({}); } }, [isAdmin]); const showToast = (type: 'success' | 'error', text: string) => { setToast({ type, text }); window.setTimeout(() => setToast(null), 3000); }; const openCreate = () => { setEditing(null); setForm({ name: '', type: 'bark', enabled: true, config: {}, event_types: [] }); setShowChannelSmtpPassword(false); setShowModal(true); }; const openEdit = (ch: NotificationChannel) => { setEditing(ch); const normalizedEmailConfig = ch.type === 'email' ? normalizeEmailChannelConfig({ ...(ch.config || {}) }) : null; const config = normalizedEmailConfig ? (normalizedEmailConfig.use_custom_smtp === true ? enableCustomSMTP(normalizedEmailConfig, smtp) : normalizedEmailConfig) : { ...(ch.config || {}) }; setForm({ name: ch.name, type: ch.type, enabled: ch.enabled, config, event_types: ch.event_types || [], }); setShowChannelSmtpPassword(false); setShowModal(true); }; const handleSave = async () => { const meta = CHANNEL_TYPES[form.type]; for (const f of meta.fields) { if (f.required && !String(form.config[f.key] || '').trim()) { showToast('error', `请填写 ${f.label}`); return; } } if (!form.name.trim()) { showToast('error', '请填写渠道名称'); return; } let config = form.config; if (form.type === 'email') { config = buildEmailChannelConfig(form.config); if (config.use_custom_smtp) { const required = [ ['smtp_server', '独立 SMTP 服务器'], ['smtp_port', '独立 SMTP 端口'], ['smtp_user', '独立 SMTP 登录邮箱'], ['smtp_password', '独立 SMTP 密码 / 授权码'], ['smtp_from_address', '独立 SMTP 发件地址'], ] as const; const missing = required.find(([key]) => !String(config[key] || '').trim()); if (missing) { showToast('error', `请填写 ${missing[1]}`); return; } } } setSaving(true); try { const payload = { name: form.name.trim(), type: form.type, config, event_types: form.event_types, enabled: form.enabled }; if (editing) { await updateNotificationChannel(editing.id, payload); } else { await createNotificationChannel(payload); } setShowModal(false); await load(); showToast('success', editing ? '已更新' : '已创建'); } catch (e: any) { console.error('保存失败', e); showToast('error', e?.message || '保存失败'); } finally { setSaving(false); } }; const handleDelete = async (ch: NotificationChannel) => { if (!confirm(`确认删除渠道「${ch.name}」吗?已绑定该渠道的账号会自动解绑。`)) return; try { await deleteNotificationChannel(ch.id); await load(); showToast('success', '已删除'); } catch (e: any) { showToast('error', e?.message || '删除失败'); } }; const handleToggleEnabled = async (ch: NotificationChannel) => { try { await updateNotificationChannel(ch.id, { enabled: !ch.enabled, }); setChannels(prev => prev.map(c => c.id === ch.id ? { ...c, enabled: !c.enabled } : c)); } catch (e: any) { showToast('error', e?.message || '切换失败'); } }; const handleTest = async (ch: NotificationChannel) => { setTestingId(ch.id); try { await testNotificationChannel(ch.id); showToast('success', '测试通知已发送,请检查对应渠道'); } catch (e: any) { showToast('error', e?.message || '发送失败'); } finally { setTestingId(''); } }; const meta = CHANNEL_TYPES[form.type]; return (
{/* Header */}

通知设置

配置通知渠道,账号异常时主动推送告警

{/* 说明 */}
配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:
  • • 账号 session 失效:系统正在尝试自动恢复(警告)
  • • 自动恢复失败:账号已停止,需人工处理(严重)
  • • 触发风控验证:可能需要扫码完成验证(警告)
{/* 渠道列表 */} {loading ? (
) : channels.length === 0 ? (

还没有配置任何通知渠道

点击右上角「新建渠道」开始配置

) : (
{channels.map(ch => { const tMeta = CHANNEL_TYPES[ch.type] || CHANNEL_TYPES.webhook; const Icon = tMeta.icon; return (
{ch.name} {tMeta.label} {!ch.enabled && ( 已停用 )}
{tMeta.fields.map(f => ch.config?.[f.key]).filter(Boolean).map((v, i) => ( {String(v).length > 40 ? String(v).slice(0, 40) + '…' : String(v)} ))}
订阅:{notificationEventSummary(ch.event_types)}
); })}
)} {/* SMTP 邮件配置(系统级,用于邮件通知渠道) */} {isAdmin && (

SMTP 邮件配置

系统级邮件发送服务,供邮件通知渠道复用

setSmtp({ ...smtp, smtp_server: e.target.value })} placeholder="smtp.qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
setSmtp({ ...smtp, smtp_port: parseInt(e.target.value) || 587 })} placeholder="587" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
setSmtp({ ...smtp, smtp_user: e.target.value })} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
setSmtp({ ...smtp, smtp_password: e.target.value })} placeholder="输入密码或授权码" className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm" />

QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)

setSmtp({ ...smtp, smtp_from_name: e.target.value })} placeholder="闲鱼自动回复系统" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
setSmtp({ ...smtp, smtp_from_address: e.target.value })} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
)} {/* 新建/编辑弹窗 */} {showModal && createPortal(

{editing ? '编辑通知渠道' : '新建通知渠道'}

setForm({ ...form, name: e.target.value })} placeholder="例如:我的 Bark" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
{(Object.keys(CHANNEL_TYPES) as NotificationChannelType[]).map(t => { const m = CHANNEL_TYPES[t]; const TIcon = m.icon; const selected = form.type === t; return ( ); })}
{/* 配置指南:选中类型后显示对应获取步骤 */}
如何获取 {meta.label} 配置?
    {meta.guide.steps.map((step, i) => (
  1. {step}
  2. ))}
{meta.guide.urlFormat && (
格式示例: {meta.guide.urlFormat}
)} {meta.guide.note && (

💡 {meta.guide.note}

)}
{meta.fields.map(f => (
setForm({ ...form, config: { ...form.config, [f.key]: e.target.value } })} placeholder={f.placeholder} className="w-full ios-input px-4 py-3 rounded-xl text-sm" /> {f.help &&

{f.help}

}
))}
{form.type === 'email' && (
SMTP 来源

{form.config.use_custom_smtp === true ? '当前渠道使用一套完整、独立的发件配置。' : '当前渠道完整继承系统 SMTP,只单独设置收件邮箱。'}

{form.config.use_custom_smtp === true && (
setForm({ ...form, config: { ...form.config, smtp_server: e.target.value } })} placeholder="smtp.qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
setForm({ ...form, config: { ...form.config, smtp_port: e.target.value } })} placeholder="587" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
setForm({ ...form, config: { ...form.config, smtp_user: e.target.value } })} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
setForm({ ...form, config: { ...form.config, smtp_password: e.target.value } })} placeholder="输入密码或授权码" className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm" />
setForm({ ...form, config: { ...form.config, smtp_from_name: e.target.value } })} placeholder="闲鱼自动回复系统" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
setForm({ ...form, config: { ...form.config, smtp_from_address: e.target.value } })} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" />
)}
)}

不选择表示接收全部通知;选择后仅接收勾选类型。

{NOTIFICATION_EVENTS.map(event => { const checked = form.event_types.includes(event.value); return ( ); })}
, document.body )} {/* Toast */} {toast && (
{toast.type === 'success' ? : } {toast.text}
)}
); }; export default Notifications;