douyinWEB/frontend/src/app/settings/page.tsx
eric 4f144f3daf Support per-channel Google OAuth Client for multi-account YouTube auth.
Existing channels keep using the global Client; optional per-channel Client ID/Secret isolates A/B/C/D OAuth apps without changing Douyin monitor paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 18:40:58 -05:00

912 lines
41 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useCallback, useEffect, useState } from "react";
import { Loader2, Save, ShieldOff } from "lucide-react";
import { Shell } from "@/components/Shell";
import { useToast } from "@/components/Toast";
import { fetchJson, fmtTs } from "@/lib/api";
type Settings = Record<string, number | boolean | string>;
const FIELDS: Array<{ key: string; label: string; hint: string; step?: number }> = [
{ key: "max_concurrency", label: "最大并发", hint: "同时检查的直播间数,建议 1–3", step: 1 },
{ key: "min_request_gap_sec", label: "最小请求间隔(秒)", hint: "任意两次请求之间的最小间隔", step: 0.1 },
{ key: "request_jitter_sec", label: "随机抖动(秒)", hint: "在间隔上叠加随机延迟", step: 0.1 },
{ key: "offline_interval_sec", label: "未开播复查间隔(秒)", hint: "离线房间下次检查等待", step: 1 },
{ key: "live_interval_sec", label: "在播复查间隔(秒)", hint: "直播中更勤,便于捕捉停播", step: 1 },
{ key: "error_backoff_base_sec", label: "错误退避基数(秒)", hint: "失败后指数退避", step: 1 },
{ key: "error_backoff_max_sec", label: "错误退避上限(秒)", hint: "退避封顶", step: 1 },
{ key: "global_pause_on_risk_sec", label: "风控全局暂停(秒)", hint: "触发验证码后全体停检", step: 1 },
];
export default function SettingsPage() {
const toast = useToast();
const [settings, setSettings] = useState<Settings>({});
const [status, setStatus] = useState<Record<string, unknown> | null>(null);
const [ytStatus, setYtStatus] = useState<Record<string, unknown> | null>(null);
const [shortsStatus, setShortsStatus] = useState<Record<string, unknown> | null>(null);
const [loading, setLoading] = useState(false);
const [msg, setMsg] = useState("");
const [error, setError] = useState("");
const [notifPerm, setNotifPerm] = useState("default");
const load = useCallback(async () => {
setLoading(true);
try {
const [s, m, yt, sh] = await Promise.all([
fetchJson("/api/settings"),
fetchJson("/api/monitor/status"),
fetchJson("/api/youtube-monitor/status").catch(() => null),
fetchJson("/api/shorts/status").catch(() => null),
]);
setSettings(s);
setStatus(m);
setYtStatus(yt);
setShortsStatus(sh);
if (typeof window !== "undefined" && "Notification" in window) {
setNotifPerm(Notification.permission);
}
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
async function save() {
setMsg("");
setError("");
try {
const body: Record<string, unknown> = {};
for (const f of FIELDS) body[f.key] = Number(settings[f.key]);
body.capture_cover_on_start = Boolean(settings.capture_cover_on_start);
body.monitor_enabled = Boolean(settings.monitor_enabled);
body.dy_cookie = String(settings.dy_cookie || "");
body.http_proxy = String(settings.http_proxy || "");
body.notify_webhook_url = String(settings.notify_webhook_url || "");
body.notify_on_live = Boolean(settings.notify_on_live);
body.notify_on_offline = Boolean(settings.notify_on_offline);
body.notify_on_risk = Boolean(settings.notify_on_risk);
body.notify_on_shorts_fail = settings.notify_on_shorts_fail !== false;
body.notify_on_shorts_ok = Boolean(settings.notify_on_shorts_ok);
body.notify_on_shorts_quota = settings.notify_on_shorts_quota !== false;
body.quiet_hours_enabled = Boolean(settings.quiet_hours_enabled);
body.quiet_hours_start = Number(settings.quiet_hours_start ?? 2);
body.quiet_hours_end = Number(settings.quiet_hours_end ?? 7);
body.quiet_hours_allow_priority = settings.quiet_hours_allow_priority !== false;
body.priority_interval_sec = Number(settings.priority_interval_sec ?? 25);
body.yt_monitor_enabled = Boolean(settings.yt_monitor_enabled);
body.yt_offline_interval_sec = Number(settings.yt_offline_interval_sec ?? 180);
body.yt_live_interval_sec = Number(settings.yt_live_interval_sec ?? 90);
body.yt_batch_size = Number(settings.yt_batch_size ?? 8);
body.yt_request_gap_sec = Number(settings.yt_request_gap_sec ?? 2);
body.shorts_enabled = Boolean(settings.shorts_enabled);
body.shorts_clip_sec = Number(settings.shorts_clip_sec ?? 15);
body.shorts_trigger = String(settings.shorts_trigger || "tagged");
body.shorts_tag = String(settings.shorts_tag || "shorts");
body.shorts_dedupe_room_day = settings.shorts_dedupe_room_day !== false;
body.shorts_max_concurrent = Number(settings.shorts_max_concurrent ?? 1);
body.shorts_auto_upload = settings.shorts_auto_upload !== false;
body.shorts_live_sample = settings.shorts_live_sample !== false;
body.shorts_live_sample_interval_sec = Number(settings.shorts_live_sample_interval_sec ?? 180);
body.shorts_live_sample_batch = Number(settings.shorts_live_sample_batch ?? 1);
body.shorts_sample_any_live = settings.shorts_sample_any_live !== false;
body.shorts_upload_spread = settings.shorts_upload_spread !== false;
body.shorts_upload_min_gap_sec = Number(settings.shorts_upload_min_gap_sec ?? 720);
body.shorts_channel_min_gap_sec = Number(settings.shorts_channel_min_gap_sec ?? 2400);
body.shorts_delete_clip_after_upload = settings.shorts_delete_clip_after_upload !== false;
body.shorts_auto_retry_failed = settings.shorts_auto_retry_failed !== false;
body.shorts_auto_retry_max_attempts = Number(settings.shorts_auto_retry_max_attempts ?? 3);
body.shorts_auto_retry_interval_sec = Number(settings.shorts_auto_retry_interval_sec ?? 300);
body.shorts_oauth_check_interval_sec = Number(settings.shorts_oauth_check_interval_sec ?? 3600);
body.shorts_oauth_client_id = String(settings.shorts_oauth_client_id || "");
body.shorts_oauth_client_secret = String(settings.shorts_oauth_client_secret || "");
body.shorts_oauth_redirect_uri = String(
settings.shorts_oauth_redirect_uri || "https://dylive.nomadro.com/api/shorts/oauth/callback"
);
const next = await fetchJson("/api/settings", { method: "PATCH", body: JSON.stringify(body) });
setSettings(next);
setMsg("已保存");
if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("dy-settings-changed"));
}
await load();
} catch (e) {
setError((e as Error).message);
}
}
async function toggleMonitor(enabled: boolean) {
try {
await fetchJson(enabled ? "/api/monitor/start" : "/api/monitor/stop", { method: "POST" });
toast.push(enabled ? "抖音监控已启用" : "抖音监控已暂停", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "err");
}
}
async function toggleYtMonitor(enabled: boolean) {
try {
await fetchJson(enabled ? "/api/youtube-monitor/start" : "/api/youtube-monitor/stop", { method: "POST" });
toast.push(enabled ? "YouTube 分组轮询已开启" : "YouTube 分组轮询已暂停", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "err");
}
}
async function toggleShorts(enabled: boolean) {
try {
await fetchJson(enabled ? "/api/shorts/start" : "/api/shorts/stop", { method: "POST" });
toast.push(enabled ? "Shorts 旁路已启用" : "Shorts 旁路已关闭", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "err");
}
}
async function clearRisk() {
try {
await fetchJson("/api/monitor/clear-risk", { method: "POST" });
setMsg("已清除风控暂停");
toast.push("已清除风控暂停", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "err");
}
}
return (
<Shell>
<div className="mb-4">
<h2 className="font-display text-2xl font-semibold">⚙️ 设置中心</h2>
<p className="text-sm text-slate-400">防风控参数、Cookie/代理、Webhook 通知。</p>
</div>
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-white/10 bg-black/30 p-4 text-sm">
<span>监控开关:</span>
<button type="button" onClick={() => void toggleMonitor(true)} className={`rounded-lg px-3 py-1.5 ${settings.monitor_enabled ? "bg-teal-500/20 text-teal-100" : "bg-white/5"}`}>启用</button>
<button type="button" onClick={() => void toggleMonitor(false)} className={`rounded-lg px-3 py-1.5 ${!settings.monitor_enabled ? "bg-rose-500/20 text-rose-100" : "bg-white/5"}`}>暂停</button>
<button type="button" onClick={() => void clearRisk()} className="inline-flex items-center gap-1 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-amber-100">
<ShieldOff className="h-3.5 w-3.5" />
清除风控暂停
</button>
<span className="text-slate-400">
状态:{status?.running ? "循环运行中" : "未运行"} · 上次检查 {fmtTs(Number(status?.last_check_at || 0))}
</span>
</div>
<div className="mb-4 space-y-3 rounded-xl border border-white/10 bg-black/30 p-4 text-sm">
<div className="flex flex-wrap items-center gap-3">
<span>YouTube 分组轮询:</span>
<button
type="button"
onClick={() => void toggleYtMonitor(true)}
className={`rounded-lg px-3 py-1.5 ${settings.yt_monitor_enabled !== false ? "bg-teal-500/20 text-teal-100" : "bg-white/5"}`}
>
启用
</button>
<button
type="button"
onClick={() => void toggleYtMonitor(false)}
className={`rounded-lg px-3 py-1.5 ${settings.yt_monitor_enabled === false ? "bg-rose-500/20 text-rose-100" : "bg-white/5"}`}
>
暂停
</button>
<span className="text-slate-400">
{ytStatus?.running ? "循环运行中" : "未运行"} · 直播 {String((ytStatus?.groups as any)?.live ?? "—")} · 启用{" "}
{String((ytStatus?.groups as any)?.enabled ?? "—")} · 上次 {fmtTs(Number(ytStatus?.last_check_at || 0))}
</span>
</div>
<div className="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
{(
[
["yt_offline_interval_sec", "离线复查(秒)", 180],
["yt_live_interval_sec", "在播复查(秒)", 90],
["yt_batch_size", "每批数量", 8],
["yt_request_gap_sec", "请求间隔(秒)", 2],
] as const
).map(([key, label, fallback]) => (
<label key={key} className="block text-xs text-slate-400">
{label}
<input
type="number"
value={Number(settings[key] ?? fallback)}
onChange={(e) => setSettings((prev) => ({ ...prev, [key]: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
))}
</div>
<p className="text-xs text-slate-500">开播/停播沿用上方「Webhook / 浏览器通知」开关;静默时段内暂停 YouTube 轮询。</p>
</div>
<div className="mb-4 space-y-3 rounded-xl border border-dashed border-amber-500/25 bg-black/30 p-4 text-sm">
<div className="flex flex-wrap items-center gap-3">
<span>Shorts 旁路(默认关,不影响监控):</span>
<button
type="button"
onClick={() => void toggleShorts(true)}
className={`rounded-lg px-3 py-1.5 ${settings.shorts_enabled ? "bg-amber-500/20 text-amber-100" : "bg-white/5"}`}
>
启用
</button>
<button
type="button"
onClick={() => void toggleShorts(false)}
className={`rounded-lg px-3 py-1.5 ${!settings.shorts_enabled ? "bg-rose-500/20 text-rose-100" : "bg-white/5"}`}
>
关闭
</button>
<a href="/shorts" className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300 hover:bg-white/10">
管理频道 / 任务 →
</a>
<span className="text-slate-400">
{shortsStatus?.running ? "worker 运行中" : "worker 未运行"} ·{" "}
{shortsStatus?.enabled ? "已启用" : "已关闭"} · 今日{" "}
{JSON.stringify((shortsStatus?.stats as any)?.by_status || {})}
</span>
</div>
<div className="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
<label className="block text-xs text-slate-400">
触发方式
<select
value={String(settings.shorts_trigger || "tagged")}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_trigger: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
>
<option value="tagged">带标签(默认 shorts)</option>
<option value="favorite">收藏/重点</option>
<option value="all">全部开播(慎用)</option>
</select>
</label>
<label className="block text-xs text-slate-400">
标签名
<input
value={String(settings.shorts_tag || "shorts")}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_tag: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
成片时长
<select
value={Number(settings.shorts_clip_sec ?? 15)}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_clip_sec: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
>
<option value={15}>15 秒(默认)</option>
<option value={30}>30 秒</option>
<option value={60}>60 秒</option>
<option value={90}>90 秒</option>
</select>
</label>
<label className="block text-xs text-slate-400">
并发
<input
type="number"
value={Number(settings.shorts_max_concurrent ?? 1)}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_max_concurrent: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
</div>
<div className="flex flex-wrap gap-4 text-xs text-slate-400">
<label className="inline-flex items-center gap-2">
<input
type="checkbox"
checked={settings.shorts_dedupe_room_day !== false}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_dedupe_room_day: e.target.checked }))}
/>
同房间每日只入队一次
</label>
<label className="inline-flex items-center gap-2">
<input
type="checkbox"
checked={settings.shorts_auto_upload !== false}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_auto_upload: e.target.checked }))}
/>
录完自动进入上传排程
</label>
<label className="inline-flex items-center gap-2">
<input
type="checkbox"
checked={settings.shorts_upload_spread !== false}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_upload_spread: e.target.checked }))}
/>
24h 不定时错峰上传(防规律/密集)
</label>
<label className="inline-flex items-center gap-2">
<input
type="checkbox"
checked={settings.shorts_delete_clip_after_upload !== false}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_delete_clip_after_upload: e.target.checked }))}
/>
上传成功后删除本地成片
</label>
<label className="inline-flex items-center gap-2">
<input
type="checkbox"
checked={settings.shorts_auto_retry_failed !== false}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_auto_retry_failed: e.target.checked }))}
/>
失败任务自动重试(跳过 OAuth 永久错误)
</label>
<label className="inline-flex items-center gap-2">
<input
type="checkbox"
checked={settings.shorts_live_sample !== false}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_live_sample: e.target.checked }))}
/>
从当前在播随机取样(不必等开播瞬间)
</label>
<label className="inline-flex items-center gap-2">
<input
type="checkbox"
checked={settings.shorts_sample_any_live !== false}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_sample_any_live: e.target.checked }))}
/>
取样不限标签(任意在播房间,同房当天只一次)
</label>
</div>
<div className="grid gap-3 md:grid-cols-2">
<label className="block text-xs text-slate-400">
随机取样间隔(秒)
<input
type="number"
value={Number(settings.shorts_live_sample_interval_sec ?? 180)}
onChange={(e) =>
setSettings((prev) => ({ ...prev, shorts_live_sample_interval_sec: Number(e.target.value) }))
}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
每次取样条数
<input
type="number"
value={Number(settings.shorts_live_sample_batch ?? 1)}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_live_sample_batch: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
全局最小上传间隔(秒)
<input
type="number"
value={Number(settings.shorts_upload_min_gap_sec ?? 720)}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_upload_min_gap_sec: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
同频道最小间隔(秒)
<input
type="number"
value={Number(settings.shorts_channel_min_gap_sec ?? 2400)}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_channel_min_gap_sec: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
自动重试最大次数
<input
type="number"
value={Number(settings.shorts_auto_retry_max_attempts ?? 3)}
onChange={(e) =>
setSettings((prev) => ({ ...prev, shorts_auto_retry_max_attempts: Number(e.target.value) }))
}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
自动重试扫描间隔(秒)
<input
type="number"
value={Number(settings.shorts_auto_retry_interval_sec ?? 300)}
onChange={(e) =>
setSettings((prev) => ({ ...prev, shorts_auto_retry_interval_sec: Number(e.target.value) }))
}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
</div>
<div className="grid gap-3 md:grid-cols-2">
<label className="block text-xs text-slate-400 md:col-span-2">
Google OAuth Client ID(Google Cloud 控制台 → 凭据 → OAuth 客户端)
<input
value={String(settings.shorts_oauth_client_id || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_oauth_client_id: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
placeholder="xxxx.apps.googleusercontent.com"
/>
</label>
<label className="block text-xs text-slate-400 md:col-span-2">
Google OAuth Client Secret
<input
type="password"
value={String(settings.shorts_oauth_client_secret || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_oauth_client_secret: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
placeholder="GOCSPX-..."
/>
</label>
<label className="block text-xs text-slate-400 md:col-span-2">
授权回调 URI(须原样加到 Google 控制台「已授权的重定向 URI」)
<input
value={String(
settings.shorts_oauth_redirect_uri || "https://dylive.nomadro.com/api/shorts/oauth/callback"
)}
onChange={(e) => setSettings((prev) => ({ ...prev, shorts_oauth_redirect_uri: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm font-mono"
/>
</label>
</div>
<p className="text-xs text-slate-500">
全局只需配置一次默认 Client。各上传频道可在编辑里覆盖专属 Client ID/Secret(谷歌账号 A/B/C/D /
不同 Cloud 项目),再点「Google 授权」写入该频道的 refresh_token。
</p>
</div>
<div className="mb-6 grid gap-3 md:grid-cols-2">
{FIELDS.map((f) => (
<label key={f.key} className="rounded-xl border border-white/10 bg-black/25 p-4 text-sm">
<div className="font-medium text-slate-200">{f.label}</div>
<div className="mt-1 text-xs text-slate-500">{f.hint}</div>
<input
type="number"
step={f.step || 1}
value={Number(settings[f.key] ?? 0)}
onChange={(e) => setSettings((prev) => ({ ...prev, [f.key]: Number(e.target.value) }))}
className="mt-2 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2"
/>
</label>
))}
</div>
<div className="mb-6 space-y-3 rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="text-sm font-medium text-slate-200">🌙 静默时段 / 重点加速(北京时间)</h3>
<label className="inline-flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={Boolean(settings.quiet_hours_enabled)}
onChange={(e) => setSettings((prev) => ({ ...prev, quiet_hours_enabled: e.target.checked }))}
/>
启用静默时段(按北京时间;普通房暂停轮询;重点房可继续探测)
</label>
<label className="inline-flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={settings.quiet_hours_allow_priority !== false}
onChange={(e) => setSettings((prev) => ({ ...prev, quiet_hours_allow_priority: e.target.checked }))}
/>
静默时段仍探测「收藏 / 重点 / priority / vip / 高优」
</label>
<div className="grid gap-3 sm:grid-cols-3">
<label className="block text-xs text-slate-400">
开始小时 (0-23)
<input
type="number"
min={0}
max={23}
value={Number(settings.quiet_hours_start ?? 2)}
onChange={(e) => setSettings((prev) => ({ ...prev, quiet_hours_start: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2"
/>
</label>
<label className="block text-xs text-slate-400">
结束小时 (0-23)
<input
type="number"
min={0}
max={23}
value={Number(settings.quiet_hours_end ?? 7)}
onChange={(e) => setSettings((prev) => ({ ...prev, quiet_hours_end: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2"
/>
</label>
<label className="block text-xs text-slate-400">
重点标签复查间隔(秒)
<input
type="number"
value={Number(settings.priority_interval_sec ?? 25)}
onChange={(e) => setSettings((prev) => ({ ...prev, priority_interval_sec: Number(e.target.value) }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2"
/>
</label>
</div>
<p className="text-xs text-slate-500">点「收藏」会打上「收藏 + 重点」标签,优先检查、间隔更短;也可在各页快捷拉黑。</p>
</div>
<div className="mb-6 space-y-3 rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="text-sm font-medium text-slate-200">Cookie / 代理(降低风控)</h3>
<label className="block text-xs text-slate-400">
抖音 Cookie(浏览器登录后复制)
<textarea
value={String(settings.dy_cookie || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, dy_cookie: e.target.value }))}
rows={3}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
placeholder="ttwid=...; ..."
/>
</label>
<label className="block text-xs text-slate-400">
HTTP 代理(可选,如 http://127.0.0.1:7890)
<input
value={String(settings.http_proxy || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, http_proxy: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
</div>
<div className="mb-6 space-y-3 rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="text-sm font-medium text-slate-200">Webhook 通知</h3>
<label className="block text-xs text-slate-400">
Webhook URL(开播/停播/风控 POST JSON)
<input
value={String(settings.notify_webhook_url || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, notify_webhook_url: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
placeholder="https://hooks.example.com/..."
/>
</label>
<div className="flex flex-wrap gap-4 text-sm">
{[
["notify_on_live", "开播通知"],
["notify_on_offline", "停播通知"],
["notify_on_risk", "风控通知"],
["notify_on_shorts_fail", "Shorts 失败"],
["notify_on_shorts_ok", "Shorts 成功"],
["notify_on_shorts_quota", "Shorts 配额落后"],
["capture_cover_on_start", "开播截图"],
].map(([key, label]) => (
<label key={key} className="inline-flex items-center gap-2">
<input
type="checkbox"
checked={Boolean(settings[key])}
onChange={(e) => setSettings((prev) => ({ ...prev, [key]: e.target.checked }))}
/>
{label}
</label>
))}
</div>
<div className="flex flex-wrap gap-2 pt-1">
<button
type="button"
onClick={async () => {
try {
await fetchJson("/api/notify/test", { method: "POST" });
setMsg("已发送 Webhook 测试");
} catch (e) {
setError((e as Error).message);
}
}}
className="rounded-lg border border-sky-500/30 bg-sky-500/10 px-3 py-1.5 text-xs text-sky-100"
>
发送 Webhook 测试
</button>
<button
type="button"
onClick={async () => {
if (!("Notification" in window)) {
setError("当前浏览器不支持系统通知");
return;
}
const perm = await Notification.requestPermission();
setNotifPerm(perm);
setMsg(perm === "granted" ? "已开启浏览器开播/风控通知" : `通知权限:${perm}`);
}}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs"
>
开启浏览器通知
</button>
<span
className={`rounded-lg border px-2.5 py-1.5 text-xs ${
notifPerm === "granted"
? "border-teal-500/30 bg-teal-500/10 text-teal-100"
: notifPerm === "denied"
? "border-rose-500/30 bg-rose-500/10 text-rose-100"
: "border-white/10 bg-white/5 text-slate-400"
}`}
>
浏览器权限:{notifPerm === "granted" ? "已授权" : notifPerm === "denied" ? "已拒绝" : "未请求"}
</span>
</div>
</div>
<OpsPanel />
<ApiKeyPanel />
<ChangePasswordPanel />
<div className="flex items-center gap-3">
<button type="button" onClick={() => void save()} className="inline-flex items-center gap-2 rounded-lg bg-[#ff2d55] px-4 py-2 text-sm font-medium text-white hover:bg-[#ff4d6d]">
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
保存设置
</button>
{msg ? <span className="text-sm text-teal-300">{msg}</span> : null}
{error ? <span className="text-sm text-rose-300">{error}</span> : null}
</div>
</Shell>
);
}
function ChangePasswordPanel() {
const [current, setCurrent] = useState("");
const [newPw, setNewPw] = useState("");
const [confirm, setConfirm] = useState("");
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState("");
const [error, setError] = useState("");
async function submit() {
setBusy(true);
setMsg("");
setError("");
try {
const data = await fetchJson("/api/auth/change-password", {
method: "POST",
body: JSON.stringify({
current_password: current,
new_password: newPw,
confirm_password: confirm,
}),
});
setMsg(data.message || "密码已更新");
setCurrent("");
setNewPw("");
setConfirm("");
await fetchJson("/api/auth/logout", { method: "POST" });
window.location.href = "/login";
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
return (
<div className="mb-6 rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-2 text-sm font-medium text-slate-100">修改登录密码</h3>
<p className="mb-3 text-xs text-slate-500">密码保存在服务器数据库(哈希存储)。修改成功后将退出登录,请用新密码重新登录。</p>
<div className="grid gap-3 sm:grid-cols-3">
<label className="block text-xs text-slate-400">
当前密码
<input
type="password"
value={current}
onChange={(e) => setCurrent(e.target.value)}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
autoComplete="current-password"
/>
</label>
<label className="block text-xs text-slate-400">
新密码(≥8 位)
<input
type="password"
value={newPw}
onChange={(e) => setNewPw(e.target.value)}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
autoComplete="new-password"
/>
</label>
<label className="block text-xs text-slate-400">
确认新密码
<input
type="password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
autoComplete="new-password"
/>
</label>
</div>
<div className="mt-3 flex flex-wrap items-center gap-2">
<button
type="button"
disabled={busy || !current || !newPw || !confirm}
onClick={() => void submit()}
className="rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white hover:bg-[#ff4d6d] disabled:opacity-50"
>
{busy ? "保存中…" : "更新密码"}
</button>
{msg ? <span className="text-xs text-teal-300">{msg}</span> : null}
{error ? <span className="text-xs text-rose-300">{error}</span> : null}
</div>
</div>
);
}
function ApiKeyPanel() {
const [required, setRequired] = useState(false);
const [key, setKey] = useState("");
const [saved, setSaved] = useState(false);
useEffect(() => {
void fetchJson("/api/auth/status")
.then((d) => setRequired(Boolean(d.api_key_required)))
.catch(() => setRequired(false));
if (typeof window !== "undefined") {
setKey(window.localStorage.getItem("dy_api_key") || "");
}
}, []);
function saveKey() {
if (typeof window === "undefined") return;
window.localStorage.setItem("dy_api_key", key.trim());
setSaved(true);
window.setTimeout(() => setSaved(false), 2000);
}
return (
<div className="mb-6 rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-2 text-sm font-medium text-slate-100">API Key(写操作保护)</h3>
<p className="mb-3 text-xs text-slate-500">
服务端设置环境变量 <code className="text-slate-400">DY_API_KEY</code> 后,所有 POST/PATCH/DELETE 需携带请求头{" "}
<code className="text-slate-400">X-API-Key</code>。密钥仅存浏览器本地,不会写入服务器设置。
{required ? (
<span className="ml-1 text-amber-300">当前服务端已启用 Key 校验。</span>
) : (
<span className="ml-1 text-slate-600">当前服务端未启用(留空即无限制)。</span>
)}
</p>
<div className="flex flex-wrap items-center gap-2">
<input
type="password"
value={key}
onChange={(e) => setKey(e.target.value)}
placeholder="输入与 DY_API_KEY 相同的密钥"
className="min-w-[240px] flex-1 rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm"
/>
<button type="button" onClick={saveKey} className="rounded-lg bg-white/10 px-3 py-2 text-sm hover:bg-white/15">
保存到浏览器
</button>
{saved ? <span className="text-xs text-teal-300">已保存</span> : null}
</div>
</div>
);
}
function OpsPanel() {
const [health, setHealth] = useState<Record<string, any> | null>(null);
const [pbHealth, setPbHealth] = useState<Record<string, any> | null>(null);
const [busy, setBusy] = useState("");
const [log, setLog] = useState("");
const refresh = useCallback(async () => {
try {
const [h, pb] = await Promise.all([
fetchJson("/api/health"),
fetchJson("/api/pb/health").catch(() => null),
]);
setHealth(h);
setPbHealth(pb);
} catch (e) {
setLog((e as Error).message);
}
}, []);
useEffect(() => {
void refresh();
}, [refresh]);
async function run(label: string, path: string, method: string = "POST") {
setBusy(label);
setLog("");
try {
const data = await fetchJson(path, { method });
setLog(`${label} → ${JSON.stringify(data).slice(0, 280)}`);
await refresh();
} catch (e) {
setLog(`${label} 失败:${(e as Error).message}`);
} finally {
setBusy("");
}
}
const pbOk = Boolean(health?.pocketbase?.ok);
const pbSync = Boolean(pbHealth?.in_sync);
const s3Ok = Boolean(health?.s3?.ok);
const s3Enabled = Boolean(health?.s3?.enabled);
return (
<div className="mb-6 space-y-3 rounded-xl border border-teal-500/20 bg-teal-500/5 p-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-sm font-medium text-teal-100">运维:PocketBase / S3 / 封面</h3>
<button type="button" onClick={() => void refresh()} className="text-xs text-slate-400 hover:text-white">
刷新状态
</button>
</div>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-5 text-xs">
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
<div className="text-slate-500">PocketBase</div>
<div className={pbOk ? "text-teal-200" : "text-rose-200"}>{pbOk ? "正常" : "异常"}</div>
</div>
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
<div className="text-slate-500">PB 同步漂移</div>
<div className={pbSync ? "text-teal-200" : "text-amber-200"}>
{pbHealth ? (pbSync ? "一致" : `Δ≤${pbHealth.max_abs_delta}`) : "—"}
</div>
</div>
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
<div className="text-slate-500">S3 媒体库</div>
<div className={s3Enabled && s3Ok ? "text-teal-200" : "text-amber-200"}>
{!s3Enabled ? "未启用" : s3Ok ? "正常" : "异常"}
</div>
<div className="mt-0.5 truncate text-[10px] text-slate-500">{health?.s3?.public_base || health?.s3?.bucket || ""}</div>
</div>
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
<div className="text-slate-500">抖音监控</div>
<div className="text-slate-200">{health?.monitor?.running ? "运行中" : "未运行"}</div>
</div>
<div className="rounded-lg border border-white/10 bg-black/20 px-3 py-2">
<div className="text-slate-500">YouTube</div>
<div className={health?.youtube?.ok ? "text-teal-200" : "text-amber-200"}>
{health?.youtube?.ok ? "svc 正常" : "svc 异常"}
{health?.youtube_monitor?.running ? " · 轮询中" : " · 已停"}
</div>
</div>
</div>
{pbHealth?.drift ? (
<div className="overflow-x-auto rounded-lg border border-white/10 bg-black/20">
<table className="w-full text-left text-[11px]">
<thead className="text-slate-500">
<tr>
<th className="px-3 py-2">集合</th>
<th className="px-3 py-2">SQLite</th>
<th className="px-3 py-2">PocketBase</th>
<th className="px-3 py-2">差值</th>
</tr>
</thead>
<tbody>
{Object.entries(pbHealth.drift as Record<string, { sqlite?: number; pocketbase?: number; delta?: number }>).map(
([name, row]) => (
<tr key={name} className="border-t border-white/5 text-slate-300">
<td className="px-3 py-1.5">{name}</td>
<td className="px-3 py-1.5 font-mono">{row.sqlite ?? "—"}</td>
<td className="px-3 py-1.5 font-mono">{row.pocketbase ?? "—"}</td>
<td className={`px-3 py-1.5 font-mono ${Math.abs(Number(row.delta) || 0) > 0 ? "text-amber-300" : "text-teal-300"}`}>
{row.delta ?? "—"}
</td>
</tr>
),
)}
</tbody>
</table>
</div>
) : null}
<div className="flex flex-wrap gap-2">
{[
["同步 Cookie", "/api/settings/sync-cookie"],
["PB 初始化字段", "/api/pb/bootstrap"],
["同步房间→PB", "/api/pb/sync-rooms"],
["同步分组→PB", "/api/pb/sync-groups"],
["同步场次→PB", "/api/pb/sync-sessions?limit=500"],
["补抓在播封面", "/api/sessions/active/recapture-covers"],
["补历史缺图", "/api/sessions/backfill-covers?limit=30"],
["对账僵尸场次", "/api/sessions/reconcile-stale"],
].map(([label, path]) => (
<button
key={path}
type="button"
disabled={Boolean(busy)}
onClick={() => void run(label, path)}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs hover:bg-white/10 disabled:opacity-50"
>
{busy === label ? "…" : label}
</button>
))}
</div>
{log ? <pre className="max-h-28 overflow-auto rounded-lg bg-black/40 p-2 text-[11px] text-slate-400 whitespace-pre-wrap">{log}</pre> : null}
</div>
);
}