feat(notifications): P4 WebUI — channel manager, per-account opt-in, deliveries widget
- API client: notifications surface (getConfig/saveConfig/recent/test) + types. - Settings → 通知 tab: global channel CRUD (id/name/url/body-template/enabled) + global debounce window, per-channel test-send, dirty-tracked save; invalid channels (bad slug / non-http URL) are dropped server-side and surfaced. - Per-account 通用设置: opt-in toggles bound to notifications.channelIds, riding the ConfigPage's existing debounced autosave; stale opt-ins preserved. - Overview: opt-in 最近投递 widget (polls /api/notifications/recent, read-only). Hidden-by-default set is now DERIVED from the catalogue (defaultVisible) and shared by desktop + mobile reconcile — replaces the hardcoded STATIC_WIDGET_IDS so a new opt-in widget can't reappear unbidden on existing mobile dashboards. Typecheck + build green. Adversarial review: 1 should-fix (mobile hidden-set) + 2 nits found, fixed/triaged, and re-verified clean.
This commit is contained in:
@@ -6,6 +6,7 @@
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { NotificationOptIn } from '@/components/config/notification-opt-in';
|
||||
import type { OneBotConfig, StatusCommandConfig } from '@/types';
|
||||
|
||||
interface GeneralSettingsTabProps {
|
||||
@@ -83,6 +84,11 @@ export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NotificationOptIn
|
||||
selectedIds={config.notifications?.channelIds ?? []}
|
||||
onChange={(channelIds) => onChange({ ...config, notifications: { channelIds } })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// Per-account opt-in to the GLOBAL notification channels. Renders the channels
|
||||
// defined in 设置 → 通知 as toggles; the selection maps to
|
||||
// OneBotConfig.notifications.channelIds. Lives inside the account's 通用设置 tab,
|
||||
// so toggling marks the config dirty and rides the parent's debounced autosave.
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { useApi } from '@/lib/api';
|
||||
import type { NotificationChannel } from '@/types';
|
||||
|
||||
interface NotificationOptInProps {
|
||||
selectedIds: string[];
|
||||
onChange: (channelIds: string[]) => void;
|
||||
}
|
||||
|
||||
export function NotificationOptIn({ selectedIds, onChange }: NotificationOptInProps) {
|
||||
const api = useApi();
|
||||
const [channels, setChannels] = useState<NotificationChannel[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
const cfg = await api.notifications.getConfig();
|
||||
if (!cancelled) setChannels(cfg.channels);
|
||||
} catch {
|
||||
if (!cancelled) setChannels([]);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
const toggle = (id: string, on: boolean) => {
|
||||
const set = new Set(selectedIds);
|
||||
if (on) set.add(id);
|
||||
else set.delete(id);
|
||||
// Order known channels by the global list; keep any stale ids (channel
|
||||
// deleted globally but still opted-in) at the end rather than dropping them.
|
||||
const known = (channels ?? []).map((c) => c.id).filter((cid) => set.has(cid));
|
||||
const extra = selectedIds.filter((sid) => set.has(sid) && !known.includes(sid));
|
||||
onChange([...known, ...extra]);
|
||||
};
|
||||
|
||||
const selected = new Set(selectedIds);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 rounded-lg border bg-card/40 p-4">
|
||||
<div>
|
||||
<Label>上下线通知渠道</Label>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
|
||||
该账号上线 / 下线时向选中的渠道推送通知。渠道在「设置 → 通知」中全局定义。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{channels === null ? (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Loader2 className="size-3.5 animate-spin" /> 加载渠道…
|
||||
</div>
|
||||
) : channels.length === 0 ? (
|
||||
<p className="text-[11px] text-muted-foreground">还没有全局渠道——先到「设置 → 通知」添加。</p>
|
||||
) : (
|
||||
<div className="flex flex-col divide-y">
|
||||
{channels.map((ch) => (
|
||||
<div key={ch.id} className="flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0">
|
||||
<div className="min-w-0">
|
||||
<span className="text-sm">{ch.name || ch.id}</span>
|
||||
{!ch.enabled && <span className="ml-2 text-[10px] text-muted-foreground">(已全局禁用)</span>}
|
||||
<p className="truncate text-[11px] text-muted-foreground">{ch.url}</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={selected.has(ch.id)}
|
||||
onChange={(v) => toggle(ch.id, v)}
|
||||
ariaLabel={`为该账号启用渠道 ${ch.name || ch.id}`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// Overview widget: the notification subsystem's in-memory delivery history
|
||||
// (most-recent-first, lost on restart). Opt-in (hidden by default); polls
|
||||
// /api/notifications/recent. No per-widget config.
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Bell, CheckCircle2, XCircle } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { useTheme } from '@/contexts/ThemeContext';
|
||||
import type { NotificationDeliveryRecord } from '@/types';
|
||||
|
||||
const POLL_MS = 15_000;
|
||||
|
||||
export function DeliveriesWidget() {
|
||||
const api = useApi();
|
||||
const { formatClock } = useTheme();
|
||||
const [records, setRecords] = useState<NotificationDeliveryRecord[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
const pull = () =>
|
||||
api.notifications
|
||||
.recent(50)
|
||||
.then((r) => {
|
||||
if (active) setRecords(r);
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) setRecords((prev) => prev ?? []);
|
||||
});
|
||||
void pull();
|
||||
const id = window.setInterval(() => void pull(), POLL_MS);
|
||||
return () => {
|
||||
active = false;
|
||||
window.clearInterval(id);
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
return (
|
||||
<Card className="flex h-full flex-col">
|
||||
<CardHeader className="flex flex-row items-center gap-2 space-y-0">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Bell className="size-4 text-primary" /> 最近投递
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="min-h-0 flex-1 overflow-auto">
|
||||
{records === null ? (
|
||||
<p className="py-10 text-center text-sm text-muted-foreground">加载中…</p>
|
||||
) : records.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 rounded-xl border border-dashed py-10 text-muted-foreground">
|
||||
<Bell className="size-8 opacity-40" strokeWidth={1.5} />
|
||||
<p className="text-sm">暂无投递记录</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1 text-[11px]">
|
||||
{records.map((r, i) => (
|
||||
<div key={i} className="flex items-center gap-2 rounded px-2 py-1 hover:bg-accent/30">
|
||||
{r.ok ? (
|
||||
<CheckCircle2 className="size-3.5 shrink-0 text-emerald-500" />
|
||||
) : (
|
||||
<XCircle className="size-3.5 shrink-0 text-destructive" />
|
||||
)}
|
||||
<span className="shrink-0 font-mono tabular-nums text-muted-foreground">{formatClock(r.time)}</span>
|
||||
<span
|
||||
className={cn(
|
||||
'shrink-0 font-medium',
|
||||
r.event === 'online' ? 'text-emerald-600' : 'text-amber-600',
|
||||
)}
|
||||
>
|
||||
{r.event === 'online' ? '上线' : '下线'}
|
||||
</span>
|
||||
<span className="shrink-0 font-mono">{r.uin}</span>
|
||||
<span className="ml-auto min-w-0 truncate text-muted-foreground" title={r.error ?? r.channelId}>
|
||||
{r.channelId}
|
||||
{!r.ok && r.error ? ` · ${r.error}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import { useTheme } from '@/contexts/ThemeContext';
|
||||
import { reconcileLayoutItems, useLayout } from '@/contexts/LayoutContext';
|
||||
import { useMediaQuery } from '@/hooks/use-media-query';
|
||||
import {
|
||||
CONFIGURABLE_WIDGETS, GRID_COLS, GRID_WIDGETS, MOBILE_WIDGET_IDS, STATIC_WIDGET_IDS, mobileHeightOf,
|
||||
CONFIGURABLE_WIDGETS, GRID_COLS, GRID_WIDGETS, HIDDEN_BY_DEFAULT_IDS, MOBILE_WIDGET_IDS, mobileHeightOf,
|
||||
parseAccountConfig, parseAlertsConfig, parseConnectionsConfig, parseHostConfig,
|
||||
parseLinkConfig, parseNoteConfig, parseSessionsConfig, widgetLabel,
|
||||
type AccountConfig, type AlertsConfig, type ConnectionsConfig, type HostConfig,
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
AccountConfigForm, AlertsConfigForm, ConnectionsConfigForm, HostConfigForm,
|
||||
LinkConfigForm, LINK_ICON_COMPONENTS, NoteConfigForm, SessionsConfigForm,
|
||||
} from '@/components/pages/widget-config-forms';
|
||||
import { DeliveriesWidget } from '@/components/overview/deliveries-widget';
|
||||
|
||||
function qqAvatarUrl(uin: string) {
|
||||
return `/avatar/${encodeURIComponent(uin)}`;
|
||||
@@ -49,6 +50,7 @@ function renderWidget(block: UiLayoutItem): ReactNode {
|
||||
case 'note': return <NoteWidget config={parseNoteConfig(block.config)} />;
|
||||
case 'link': return <LinkWidget config={parseLinkConfig(block.config)} />;
|
||||
case 'account': return <AccountWidget config={parseAccountConfig(block.config)} />;
|
||||
case 'deliveries': return <DeliveriesWidget />;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
@@ -78,7 +80,7 @@ export function OverviewPage() {
|
||||
// Reconcile the mobile order against the live widget catalogue (drop unknown,
|
||||
// append new as visible) — so a widget added later just appears on phones too.
|
||||
const mobileItems = useMemo(
|
||||
() => reconcileLayoutItems(overviewMobile, MOBILE_WIDGET_IDS, [], STATIC_WIDGET_IDS),
|
||||
() => reconcileLayoutItems(overviewMobile, MOBILE_WIDGET_IDS, [], HIDDEN_BY_DEFAULT_IDS),
|
||||
[overviewMobile],
|
||||
);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createContext, useContext, useId, useRef, useState, type ReactNode } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import {
|
||||
Accessibility, AlertTriangle, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon,
|
||||
Accessibility, AlertTriangle, Bell, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon,
|
||||
Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, ShieldCheck,
|
||||
Sparkles, Star, Sun, Tag, Upload, Trash2,
|
||||
} from 'lucide-react';
|
||||
@@ -40,12 +40,14 @@ import { useApi } from '@/lib/api';
|
||||
import { useAppState } from '@/contexts/AppStateContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { settingsRoute, type SettingsTab } from '@/router';
|
||||
import { NotificationsPanel } from '@/components/settings/notifications-panel';
|
||||
|
||||
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
|
||||
{ key: 'appearance', label: '外观', icon: Palette },
|
||||
{ key: 'data', label: '数据与格式', icon: RefreshCw },
|
||||
{ key: 'advanced', label: '高级', icon: Code2 },
|
||||
{ key: 'account', label: '账号安全', icon: ShieldCheck },
|
||||
{ key: 'notifications', label: '通知', icon: Bell },
|
||||
{ key: 'about', label: '关于', icon: Info },
|
||||
];
|
||||
|
||||
@@ -76,6 +78,7 @@ export function SettingsPage() {
|
||||
{tab === 'data' && <DataPanel />}
|
||||
{tab === 'advanced' && <AdvancedPanel />}
|
||||
{tab === 'account' && <AccountPanel />}
|
||||
{tab === 'notifications' && <NotificationsPanel />}
|
||||
{tab === 'about' && <AboutPanel />}
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
// Settings → 通知 tab. Global webhook-channel store (CRUD + per-channel test
|
||||
// send) and the global debounce window. Channels are global; each account opts
|
||||
// in from its own Config page. The server total-normalizes on save (a channel
|
||||
// with an invalid slug id or a non-http(s) URL is dropped), so after 保存 the
|
||||
// list reflects exactly what was accepted.
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Bell, Loader2, Plus, Send, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { NotificationChannel, NotificationsConfig } from '@/types';
|
||||
|
||||
const DEFAULT_TEMPLATE = '{nickname}({uin}) {event} @ {time}';
|
||||
|
||||
function blankChannel(n: number): NotificationChannel {
|
||||
return { id: `channel-${n}`, name: '', url: '', bodyTemplate: DEFAULT_TEMPLATE, enabled: true };
|
||||
}
|
||||
|
||||
export function NotificationsPanel() {
|
||||
const api = useApi();
|
||||
const [config, setConfig] = useState<NotificationsConfig | null>(null);
|
||||
const [saved, setSaved] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [testing, setTesting] = useState<string | null>(null);
|
||||
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
const cfg = await api.notifications.getConfig();
|
||||
if (cancelled) return;
|
||||
setConfig(cfg);
|
||||
setSaved(JSON.stringify(cfg));
|
||||
} catch {
|
||||
if (!cancelled) setMsg({ kind: 'err', text: '加载通知配置失败' });
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
const dirty = useMemo(() => (config ? JSON.stringify(config) !== saved : false), [config, saved]);
|
||||
|
||||
if (loading || !config) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 rounded-lg border bg-card/40 p-6 text-sm text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" /> 加载中…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const patch = (p: Partial<NotificationsConfig>) => setConfig({ ...config, ...p });
|
||||
const patchChannel = (i: number, p: Partial<NotificationChannel>) =>
|
||||
setConfig({ ...config, channels: config.channels.map((c, idx) => (idx === i ? { ...c, ...p } : c)) });
|
||||
const addChannel = () => {
|
||||
// Avoid a default id colliding with an existing one (e.g. after deletes),
|
||||
// which the server would dedup-drop on save.
|
||||
const used = new Set(config.channels.map((c) => c.id));
|
||||
let n = config.channels.length + 1;
|
||||
while (used.has(`channel-${n}`)) n += 1;
|
||||
setConfig({ ...config, channels: [...config.channels, blankChannel(n)] });
|
||||
};
|
||||
const removeChannel = (i: number) =>
|
||||
setConfig({ ...config, channels: config.channels.filter((_, idx) => idx !== i) });
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
const result = await api.notifications.saveConfig(config);
|
||||
setConfig(result);
|
||||
setSaved(JSON.stringify(result));
|
||||
const dropped = config.channels.length - result.channels.length;
|
||||
setMsg({
|
||||
kind: 'ok',
|
||||
text: dropped > 0 ? `已保存(${dropped} 个无效渠道被丢弃,需有效 slug id + http(s) URL)` : '已保存',
|
||||
});
|
||||
} catch {
|
||||
setMsg({ kind: 'err', text: '保存失败,请检查服务器日志' });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const test = async (id: string) => {
|
||||
setTesting(id);
|
||||
setMsg(null);
|
||||
try {
|
||||
const res = await api.notifications.test(id);
|
||||
setMsg({ kind: res.success ? 'ok' : 'err', text: res.message ?? (res.success ? '测试发送成功' : '测试发送失败') });
|
||||
} catch {
|
||||
setMsg({ kind: 'err', text: '测试请求失败' });
|
||||
} finally {
|
||||
setTesting(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-start gap-2 rounded-lg border bg-card/40 p-4 text-[11px] leading-relaxed text-muted-foreground">
|
||||
<Bell className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>
|
||||
账号上线 / 下线时,向启用的渠道 POST 一条渲染后的通知(机械转发,仅去抖防刷屏)。渠道在此全局定义,
|
||||
每个账号在其「配置」页勾选启用哪些。模板变量:
|
||||
<code className="font-mono">{'{uin}'}</code> <code className="font-mono">{'{nickname}'}</code>{' '}
|
||||
<code className="font-mono">{'{event}'}</code>(offline/online) <code className="font-mono">{'{time}'}</code>。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Global debounce */}
|
||||
<div className="flex flex-col gap-1.5 rounded-lg border bg-card/40 p-4">
|
||||
<Label>去抖窗口(秒)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={3600}
|
||||
className="w-32 tabular-nums"
|
||||
value={config.debounceSeconds}
|
||||
onChange={(e) => {
|
||||
const n = Math.trunc(Number(e.target.value));
|
||||
patch({ debounceSeconds: Number.isFinite(n) ? Math.min(3600, Math.max(0, n)) : 0 });
|
||||
}}
|
||||
/>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
下线后在该秒数内自愈则不发(抑制闪断);超时才发「下线」,恢复时再发「上线」。<code className="font-mono">0</code> 表示不去抖、立即发。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Channels */}
|
||||
<div className="flex flex-col gap-3">
|
||||
{config.channels.length === 0 && (
|
||||
<p className="rounded-lg border border-dashed bg-card/20 p-6 text-center text-sm text-muted-foreground">
|
||||
还没有渠道。点下方「新增渠道」添加一个 webhook。
|
||||
</p>
|
||||
)}
|
||||
|
||||
{config.channels.map((ch, i) => (
|
||||
<div key={i} className="flex flex-col gap-3 rounded-lg border bg-card/40 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<ToggleSwitch
|
||||
value={ch.enabled}
|
||||
onChange={(v) => patchChannel(i, { enabled: v })}
|
||||
ariaLabel={`启用渠道 ${ch.name || ch.id}`}
|
||||
/>
|
||||
<span className={cn('text-sm font-medium', ch.enabled ? undefined : 'text-muted-foreground')}>
|
||||
{ch.name || ch.id || '未命名渠道'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={dirty || testing === ch.id}
|
||||
title={dirty ? '请先保存再测试' : '向该渠道发送一条测试消息'}
|
||||
onClick={() => void test(ch.id)}
|
||||
>
|
||||
{testing === ch.id ? <Loader2 className="size-3.5 animate-spin" /> : <Send className="size-3.5" />}
|
||||
测试
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label="删除渠道"
|
||||
onClick={() => removeChannel(i)}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-xs">渠道 ID(slug,账号据此勾选)</Label>
|
||||
<Input
|
||||
value={ch.id}
|
||||
placeholder="dingtalk"
|
||||
onChange={(e) => patchChannel(i, { id: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-xs">显示名</Label>
|
||||
<Input
|
||||
value={ch.name}
|
||||
placeholder="钉钉群机器人"
|
||||
onChange={(e) => patchChannel(i, { name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-xs">Webhook URL(http/https)</Label>
|
||||
<Input
|
||||
type="url"
|
||||
value={ch.url}
|
||||
placeholder="https://oapi.dingtalk.com/robot/send?access_token=…"
|
||||
onChange={(e) => patchChannel(i, { url: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-xs">Body 模板</Label>
|
||||
<textarea
|
||||
value={ch.bodyTemplate}
|
||||
rows={3}
|
||||
spellCheck={false}
|
||||
onChange={(e) => patchChannel(i, { bodyTemplate: e.target.value })}
|
||||
className={cn(
|
||||
'w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-xs leading-relaxed shadow-xs outline-none transition-[color,box-shadow]',
|
||||
'placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<Button type="button" variant="outline" size="sm" className="self-start" onClick={addChannel}>
|
||||
<Plus className="size-3.5" /> 新增渠道
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Save bar */}
|
||||
<div className="flex items-center gap-3 border-t pt-4">
|
||||
<Button type="button" disabled={!dirty || saving} onClick={() => void save()}>
|
||||
{saving && <Loader2 className="size-3.5 animate-spin" />} 保存
|
||||
</Button>
|
||||
{dirty && <span className="text-[11px] text-muted-foreground">有未保存的更改</span>}
|
||||
{msg && (
|
||||
<span className={cn('text-xs', msg.kind === 'ok' ? 'text-emerald-500' : 'text-destructive')}>{msg.text}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AccountConnections, HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo, UiAppearance, UiConfig, UpdateInfo } from '@/types';
|
||||
import type { AccountConnections, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, UiAppearance, UiConfig, UpdateInfo } from '@/types';
|
||||
import type { PasswordRule } from '@/components/pages/change-password-page';
|
||||
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
||||
import {
|
||||
@@ -44,6 +44,7 @@ class HttpApiClient implements ApiClient {
|
||||
readonly logs: ApiClient['logs'];
|
||||
readonly update: ApiClient['update'];
|
||||
readonly ui: ApiClient['ui'];
|
||||
readonly notifications: ApiClient['notifications'];
|
||||
|
||||
constructor(opts: CreateApiClientOptions = {}) {
|
||||
this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
|
||||
@@ -136,6 +137,26 @@ class HttpApiClient implements ApiClient {
|
||||
return data.config;
|
||||
},
|
||||
};
|
||||
|
||||
this.notifications = {
|
||||
getConfig: () =>
|
||||
this.getJson<{ config: NotificationsConfig }>('/api/notifications/config').then((d) => d.config),
|
||||
saveConfig: async (config) => {
|
||||
const data = await this.postJson<{ success: boolean; config: NotificationsConfig }>(
|
||||
'/api/notifications/config',
|
||||
config,
|
||||
);
|
||||
return data.config;
|
||||
},
|
||||
recent: (limit) =>
|
||||
this.getJson<{ recent: NotificationDeliveryRecord[] }>(
|
||||
`/api/notifications/recent${limit ? `?limit=${limit}` : ''}`,
|
||||
).then((d) => d.recent ?? []),
|
||||
test: (channelId) =>
|
||||
this.postJson<{ success: boolean; message?: string; status?: number }>('/api/notifications/test', {
|
||||
channelId,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- HTTP helpers ----------
|
||||
|
||||
@@ -3,6 +3,8 @@ import type {
|
||||
HookProcessInfo,
|
||||
LogEntry,
|
||||
LogLevel,
|
||||
NotificationDeliveryRecord,
|
||||
NotificationsConfig,
|
||||
OneBotConfig,
|
||||
QQInfo,
|
||||
SystemInfo,
|
||||
@@ -72,6 +74,18 @@ export interface ApiClient {
|
||||
save(uin: string, config: OneBotConfig): Promise<OneBotConfig>;
|
||||
};
|
||||
|
||||
// ---- notifications (account up/down webhooks) ----
|
||||
notifications: {
|
||||
/** Global channel store (channels + debounce). Bearer-gated. */
|
||||
getConfig(): Promise<NotificationsConfig>;
|
||||
/** Persist the global store (whole-config; server normalizes). */
|
||||
saveConfig(config: Partial<NotificationsConfig>): Promise<NotificationsConfig>;
|
||||
/** Recent in-memory delivery history, most-recent-first (≤100). */
|
||||
recent(limit?: number): Promise<NotificationDeliveryRecord[]>;
|
||||
/** Fire a one-off test to a single channel by id. */
|
||||
test(channelId: string): Promise<{ success: boolean; message?: string; status?: number }>;
|
||||
};
|
||||
|
||||
// ---- update check ----
|
||||
update: {
|
||||
/** Advisory check for a newer stable release. Read-only — never downloads. */
|
||||
|
||||
@@ -45,10 +45,16 @@ export const GRID_WIDGETS: GridWidgetSpec[] = [
|
||||
{ id: 'note', label: '便签', minW: 2, minH: 2, def: { x: 0, y: 14, w: 4, h: 2 }, defaultVisible: false },
|
||||
{ id: 'link', label: '链接卡', minW: 2, minH: 1, def: { x: 4, y: 14, w: 4, h: 1 }, defaultVisible: false },
|
||||
{ id: 'account', label: '账号快捷卡', minW: 2, minH: 1, def: { x: 8, y: 14, w: 4, h: 1 }, defaultVisible: false },
|
||||
{ id: 'deliveries', label: '最近投递', minW: 3, minH: 3, def: { x: 0, y: 16, w: 6, h: 3 }, defaultVisible: false },
|
||||
];
|
||||
|
||||
/** The opt-in static widgets — appended hidden when reconciling forward. */
|
||||
export const STATIC_WIDGET_IDS: ReadonlySet<string> = new Set(['note', 'link', 'account']);
|
||||
/** Widgets hidden on first sight (opt-in) — derived from the catalogue's
|
||||
* `defaultVisible:false` so a new opt-in widget is hidden on BOTH desktop
|
||||
* (migrateOverviewBlocks) and mobile (reconcileLayoutItems) from a single
|
||||
* source of truth — no second registration to forget. */
|
||||
export const HIDDEN_BY_DEFAULT_IDS: ReadonlySet<string> = new Set(
|
||||
GRID_WIDGETS.filter((w) => w.defaultVisible === false).map((w) => w.id),
|
||||
);
|
||||
|
||||
const WIDGET_BY_ID = new Map(GRID_WIDGETS.map((w) => [w.id, w]));
|
||||
|
||||
|
||||
@@ -16,6 +16,15 @@ function normalizeStatusCommand(raw: unknown): StatusCommandConfig {
|
||||
};
|
||||
}
|
||||
|
||||
/** Keep only string channel ids (the server re-validates slugs on save). */
|
||||
function normalizeNotifications(raw: unknown): { channelIds: string[] } {
|
||||
const src = (raw ?? {}) as Record<string, unknown>;
|
||||
const channelIds = Array.isArray(src.channelIds)
|
||||
? src.channelIds.filter((x): x is string => typeof x === 'string')
|
||||
: [];
|
||||
return { channelIds };
|
||||
}
|
||||
|
||||
/**
|
||||
* Anti-corruption layer for the per-UIN config payload. Older backends emit
|
||||
* `messageFormat` / `reportSelfMessage` at the top level instead of per
|
||||
@@ -47,5 +56,6 @@ export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
|
||||
},
|
||||
musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined,
|
||||
statusCommand: normalizeStatusCommand(cfg.statusCommand),
|
||||
notifications: normalizeNotifications(cfg.notifications),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ const logsRoute = createRoute({
|
||||
});
|
||||
|
||||
/** Settings sub-tabs — also the contract for the `?tab=` deep link. */
|
||||
export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'about'] as const;
|
||||
export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'notifications', 'about'] as const;
|
||||
export type SettingsTab = (typeof SETTINGS_TABS)[number];
|
||||
|
||||
export const settingsRoute = createRoute({
|
||||
|
||||
@@ -108,6 +108,35 @@ export interface OneBotConfig {
|
||||
networks: OneBotNetworks;
|
||||
musicSignUrl?: string;
|
||||
statusCommand: StatusCommandConfig;
|
||||
/** Per-account opt-in to global notification channels (by channel id). */
|
||||
notifications?: { channelIds: string[] };
|
||||
}
|
||||
|
||||
// ─── Notifications (account up/down webhooks) ───────────────────────────────
|
||||
export type NotificationEventKind = 'offline' | 'online';
|
||||
|
||||
export interface NotificationChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
bodyTemplate: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface NotificationsConfig {
|
||||
version: number;
|
||||
debounceSeconds: number;
|
||||
channels: NotificationChannel[];
|
||||
}
|
||||
|
||||
export interface NotificationDeliveryRecord {
|
||||
time: number;
|
||||
uin: string;
|
||||
event: NotificationEventKind;
|
||||
channelId: string;
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export type NetworkKind = keyof OneBotNetworks;
|
||||
|
||||
Reference in New Issue
Block a user