douyinWEB/frontend/src/app/youtube/page.tsx
eric c9c71948cb Unify YouTube OAuth/YPP card meta and fix YPP monetize payloads.
Seed brand hints on startup, merge Shorts OAuth into yt-long board, and retry Studio monetize with corrected self-cert formats.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 01:59:36 -05:00

707 lines
29 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 Link from "next/link";
import {
Clapperboard,
Eye,
EyeOff,
Loader2,
Link2,
ListVideo,
Plus,
Radio,
RefreshCw,
Save,
Search,
Trash2,
LayoutDashboard,
Layers,
} from "lucide-react";
import { Shell } from "@/components/Shell";
import { useConfirm } from "@/components/ConfirmDialog";
import { useToast } from "@/components/Toast";
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
import { YtAssignPanel } from "@/components/YtAssignPanel";
import { YtChannelProfileSnippet } from "@/components/YtChannelProfileSnippet";
import { buildChannelMeta } from "@/lib/ytChannelMeta";
import { fetchJson, fmtTs } from "@/lib/api";
import { shortsLiveRef } from "@/lib/youtubeLive";
type Mode = "assign" | "manage" | "probe";
type ProbeTab = "channel" | "live" | "video" | "search" | "resolve";
type ManagedChannel = {
id: string;
name?: string;
youtube_channel_id?: string;
enabled?: boolean;
authorized?: boolean;
oauth_profile_id?: string;
oauth_ok?: number;
oauth_error?: string;
brand_hint?: string;
note?: string;
ypp_ok?: number;
daily_min?: number;
daily_max?: number;
title?: string;
thumb_url?: string;
custom_url?: string;
yt_profile?: any;
};
type YtVideo = {
id: string;
title?: string;
description?: string;
privacyStatus?: string;
publishAt?: string;
published_at?: string;
tags?: string[];
statistics?: Record<string, string>;
thumbnails?: any;
url?: string;
shorts_url?: string;
};
export default function YouTubePage() {
const confirm = useConfirm();
const toast = useToast();
const [mode, setMode] = useState<Mode>("assign");
const [channels, setChannels] = useState<ManagedChannel[]>([]);
const [channelPk, setChannelPk] = useState("");
const [dash, setDash] = useState<any>(null);
const [videos, setVideos] = useState<YtVideo[]>([]);
const [playlists, setPlaylists] = useState<any[]>([]);
const [edit, setEdit] = useState<YtVideo | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [msg, setMsg] = useState("");
// probe
const [tab, setTab] = useState<ProbeTab>("channel");
const [input, setInput] = useState("@MrBeast");
const [result, setResult] = useState<any>(null);
const [svc, setSvc] = useState<any>(null);
const [addBusy, setAddBusy] = useState(false);
const loadChannels = useCallback(async () => {
try {
const data = await fetchJson("/api/youtube/manage/channels");
const list = (data.channels || []).filter((c: ManagedChannel) => c.authorized);
setChannels(list);
if (!channelPk && list[0]?.id) setChannelPk(list[0].id);
} catch (e) {
setError((e as Error).message);
}
}, [channelPk]);
const loadManage = useCallback(async () => {
if (!channelPk) return;
setBusy(true);
setError("");
try {
const [d, v, p] = await Promise.all([
fetchJson(`/api/youtube/manage/${channelPk}/dashboard`),
fetchJson(`/api/youtube/manage/${channelPk}/videos?max_results=25`),
fetchJson(`/api/youtube/manage/${channelPk}/playlists`).catch(() => ({ playlists: [] })),
]);
setDash(d);
setVideos(v.videos || []);
setPlaylists(p.playlists || []);
} catch (e) {
setError((e as Error).message);
setDash(null);
setVideos([]);
} finally {
setBusy(false);
}
}, [channelPk]);
useEffect(() => {
void loadChannels();
}, [loadChannels]);
useEffect(() => {
if (mode === "manage" && channelPk) void loadManage();
}, [mode, channelPk, loadManage]);
async function saveVideo() {
if (!edit || !channelPk) return;
setBusy(true);
setError("");
setMsg("");
try {
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${edit.id}`, {
method: "PATCH",
body: JSON.stringify({
title: edit.title,
description: edit.description,
tags: edit.tags || [],
privacy_status: edit.privacyStatus,
publish_at: edit.publishAt || "",
}),
});
setMsg("视频已更新");
setEdit(null);
await loadManage();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
async function setPrivacy(videoId: string, privacy: string) {
if (!channelPk) return;
setBusy(true);
try {
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, {
method: "PATCH",
body: JSON.stringify({ privacy_status: privacy }),
});
setMsg(`已设为 ${privacy}`);
await loadManage();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
async function removeVideo(videoId: string) {
if (!channelPk) return;
const ok = await confirm({
title: "删除 YouTube 视频",
message: "确定从 YouTube 删除该视频?此操作不可恢复。",
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
setBusy(true);
try {
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, { method: "DELETE" });
toast.push("视频已删除", "ok");
await loadManage();
} catch (e) {
setError((e as Error).message);
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function checkSvc() {
try {
setSvc(await fetchJson("/api/youtube/health"));
} catch (e) {
setSvc({ ok: false, error: (e as Error).message });
}
}
async function runProbe() {
setBusy(true);
setError("");
setMsg("");
setResult(null);
try {
const q = encodeURIComponent(input.trim());
let data: any;
if (tab === "channel") data = await fetchJson(`/api/youtube/channel?url=${q}&videos=1&limit=8`);
else if (tab === "live") data = await fetchJson(`/api/youtube/channel/live?url=${q}`);
else if (tab === "video") data = await fetchJson(`/api/youtube/video?url=${q}`);
else if (tab === "search") data = await fetchJson(`/api/youtube/search?q=${q}&limit=12`);
else data = await fetchJson(`/api/youtube/resolve?url=${q}`);
setResult(data);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
async function addToGroup(channel: any) {
const channelUrl =
String(channel?.url || "").trim() ||
(channel?.handle ? `https://www.youtube.com/@${String(channel.handle).replace(/^@/, "")}` : "") ||
String(channel?.channel_id || input.trim());
if (!channelUrl) {
setError("缺少频道 URL");
return;
}
setAddBusy(true);
try {
await fetchJson("/api/groups", {
method: "POST",
body: JSON.stringify({
name: String(channel?.title || channel?.handle || "YouTube 频道").slice(0, 80),
channel_url: channelUrl,
platform: "youtube",
enabled: true,
note: "从 YouTube 探测页加入",
}),
});
setMsg("已加入分组监控");
} catch (e) {
setError((e as Error).message);
} finally {
setAddBusy(false);
}
}
const profile = dash?.profile;
const shortsToday = dash?.shorts_today?.by_status || {};
const probeChannel = result?.channel;
const live = result?.live || probeChannel?.live;
const probeVideos = result?.results || probeChannel?.videos || [];
return (
<Shell>
<div className="mb-5 flex flex-wrap items-end justify-between gap-3">
<div>
<p className="font-display text-xs uppercase tracking-[0.28em] text-rose-300/80">YouTube Studio Lite</p>
<h2 className="font-display text-3xl font-semibold">▶️ YouTube</h2>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
分配:频道 + 直播 KEY → 抖音 URL 池 → 精选转播。频道管理:片库 / 元数据 / 可见性。探测仍用 InnerTube。
</p>
</div>
<div className="flex flex-wrap gap-2">
<Link href="/shorts" className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10">
Shorts →
</Link>
<Link href="/groups" className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10">
分组监控 →
</Link>
</div>
</div>
<div className="mb-4 flex flex-wrap gap-2">
<button
type="button"
onClick={() => setMode("assign")}
className={`inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-sm ${
mode === "assign" ? "bg-amber-500/20 text-amber-50 ring-1 ring-amber-400/30" : "bg-white/5 text-slate-400"
}`}
>
<Layers className="h-3.5 w-3.5" />
分配
</button>
<button
type="button"
onClick={() => setMode("manage")}
className={`inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-sm ${
mode === "manage" ? "bg-rose-500/20 text-rose-50 ring-1 ring-rose-400/30" : "bg-white/5 text-slate-400"
}`}
>
<LayoutDashboard className="h-3.5 w-3.5" />
频道管理(OAuth)
</button>
<button
type="button"
onClick={() => setMode("probe")}
className={`inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-sm ${
mode === "probe" ? "bg-teal-500/20 text-teal-50 ring-1 ring-teal-400/30" : "bg-white/5 text-slate-400"
}`}
>
<Search className="h-3.5 w-3.5" />
公开探测(InnerTube)
</button>
</div>
{msg ? <div className="mb-3 text-sm text-teal-300">{msg}</div> : null}
{error ? <div className="mb-3 text-sm text-rose-300">{error}</div> : null}
{mode === "assign" ? (
<YtAssignPanel channels={channels} />
) : mode === "manage" ? (
<>
{channels.length === 0 ? (
<div className="rounded-2xl border border-dashed border-amber-500/30 bg-amber-500/5 px-4 py-10 text-center text-sm text-amber-100">
还没有已授权频道。请先到{" "}
<Link href="/shorts" className="underline">
Shorts
</Link>{" "}
完成 Google 授权。
</div>
) : (
<>
<div className="mb-4 grid gap-2 sm:grid-cols-2">
{channels.map((c) => {
const active = c.id === channelPk;
return (
<button
key={c.id}
type="button"
onClick={() => setChannelPk(c.id)}
className={`rounded-xl border p-3 text-left transition ${
active
? "border-rose-400/40 bg-rose-500/10"
: "border-white/10 bg-black/30 hover:bg-white/5"
}`}
>
<YtChannelProfileSnippet
profile={c.yt_profile}
fallbackName={c.title || c.name}
fallbackChannelId={c.youtube_channel_id || c.custom_url}
liveChannelPk={c.id}
meta={buildChannelMeta(c)}
/>
</button>
);
})}
</div>
<div className="mb-4 flex flex-wrap items-center gap-2">
{channelPk ? <YouTubeLiveBadge refKey={shortsLiveRef(channelPk)} /> : null}
<button
type="button"
onClick={() => void loadManage()}
className="inline-flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
>
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
刷新
</button>
</div>
{profile ? (
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<div className="rounded-2xl border border-white/10 bg-black/30 p-4 sm:col-span-2">
<div className="flex gap-3">
{profile.thumbnails?.default?.url || profile.thumbnails?.medium?.url ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={profile.thumbnails?.medium?.url || profile.thumbnails?.default?.url}
alt=""
className="h-14 w-14 rounded-full object-cover"
/>
) : (
<div className="h-14 w-14 rounded-full bg-white/10" />
)}
<div>
<div className="flex flex-wrap items-center gap-2">
<div className="font-display text-xl text-white">{profile.title}</div>
{channelPk ? <YouTubeLiveBadge refKey={shortsLiveRef(channelPk)} compact /> : null}
</div>
<div className="text-xs text-slate-500">{profile.custom_url || profile.youtube_channel_id}</div>
<div className="mt-1 text-xs text-slate-400">
订阅 {profile.statistics?.subscriberCount ?? "—"} · 视频 {profile.statistics?.videoCount ?? "—"} · 播放{" "}
{profile.statistics?.viewCount ?? "—"}
</div>
</div>
</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/30 p-4">
<div className="text-xs text-slate-500">今日 Shorts 流水</div>
<div className="mt-2 space-y-1 text-xs text-slate-300">
{Object.keys(shortsToday).length === 0 ? (
<span className="text-slate-500">无</span>
) : (
Object.entries(shortsToday).map(([k, v]) => (
<div key={k} className="flex justify-between">
<span>{k}</span>
<span>{String(v)}</span>
</div>
))
)}
</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/30 p-4">
<div className="text-xs text-slate-500">播放列表</div>
<div className="mt-2 font-display text-2xl text-white">{playlists.length}</div>
<div className="text-[11px] text-slate-500">只读(当前 OAuth scope)</div>
</div>
</div>
) : null}
<div className="mb-6 grid gap-4 xl:grid-cols-[1.5fr_1fr]">
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-3 text-sm font-medium text-slate-100">近期上传</h3>
<div className="space-y-2">
{videos.length === 0 ? (
<div className="py-8 text-center text-sm text-slate-500">暂无视频或加载失败</div>
) : (
videos.map((v) => (
<div key={v.id} className="flex gap-3 rounded-xl border border-white/10 bg-black/40 p-2.5">
{v.thumbnails?.medium?.url || v.thumbnails?.default?.url ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={v.thumbnails?.medium?.url || v.thumbnails?.default?.url}
alt=""
className="h-16 w-28 shrink-0 rounded-lg object-cover"
/>
) : (
<div className="h-16 w-28 shrink-0 rounded-lg bg-white/10" />
)}
<div className="min-w-0 flex-1">
<div className="truncate text-sm text-slate-100">{v.title}</div>
<div className="mt-0.5 text-[11px] text-slate-500">
{v.privacyStatus} · 播放 {v.statistics?.viewCount ?? 0} ·{" "}
{v.published_at ? fmtTs(Date.parse(v.published_at) / 1000) : "—"}
{v.publishAt ? ` · 定时 ${v.publishAt}` : ""}
</div>
<div className="mt-2 flex flex-wrap gap-1.5">
<button
type="button"
onClick={() => setEdit({ ...v })}
className="rounded-lg bg-white/5 px-2 py-1 text-[11px]"
>
编辑
</button>
<button
type="button"
onClick={() => void setPrivacy(v.id, "public")}
className="inline-flex items-center gap-1 rounded-lg bg-teal-500/15 px-2 py-1 text-[11px] text-teal-100"
>
<Eye className="h-3 w-3" />
公开
</button>
<button
type="button"
onClick={() => void setPrivacy(v.id, "unlisted")}
className="rounded-lg bg-amber-500/15 px-2 py-1 text-[11px] text-amber-100"
>
不公开列出
</button>
<button
type="button"
onClick={() => void setPrivacy(v.id, "private")}
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px]"
>
<EyeOff className="h-3 w-3" />
私密
</button>
<a
href={v.shorts_url || v.url}
target="_blank"
rel="noreferrer"
className="rounded-lg bg-white/5 px-2 py-1 text-[11px] text-slate-300"
>
打开
</a>
<button
type="button"
onClick={() => void removeVideo(v.id)}
className="inline-flex items-center gap-1 rounded-lg bg-rose-500/15 px-2 py-1 text-[11px] text-rose-200"
>
<Trash2 className="h-3 w-3" />
删
</button>
</div>
</div>
</div>
))
)}
</div>
</section>
<section className="space-y-4">
{edit ? (
<div className="rounded-2xl border border-rose-500/25 bg-black/40 p-4">
<h3 className="mb-3 text-sm font-medium text-slate-100">编辑视频</h3>
<label className="mb-2 block text-xs text-slate-400">
标题
<input
value={edit.title || ""}
onChange={(e) => setEdit({ ...edit, title: 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="mb-2 block text-xs text-slate-400">
描述
<textarea
value={edit.description || ""}
onChange={(e) => setEdit({ ...edit, description: e.target.value })}
rows={5}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="mb-2 block text-xs text-slate-400">
标签(逗号分隔)
<input
value={(edit.tags || []).join(", ")}
onChange={(e) =>
setEdit({
...edit,
tags: e.target.value
.split(",")
.map((t) => t.trim())
.filter(Boolean),
})
}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="mb-2 block text-xs text-slate-400">
可见性
<select
value={edit.privacyStatus || "public"}
onChange={(e) => setEdit({ ...edit, privacyStatus: 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="public">public</option>
<option value="unlisted">unlisted</option>
<option value="private">private</option>
</select>
</label>
<label className="mb-3 block text-xs text-slate-400">
定时公开(UTC ISO,如 2026-08-10T12:00:00Z;填写后会先设为 private)
<input
value={edit.publishAt || ""}
onChange={(e) => setEdit({ ...edit, publishAt: e.target.value })}
placeholder="2026-08-10T12:00:00Z"
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm"
/>
</label>
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={busy}
onClick={() => void saveVideo()}
className="inline-flex items-center gap-1 rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white"
>
<Save className="h-3.5 w-3.5" />
保存
</button>
<button type="button" onClick={() => setEdit(null)} className="rounded-lg bg-white/5 px-3 py-2 text-sm">
取消
</button>
</div>
</div>
) : (
<div className="rounded-2xl border border-dashed border-white/10 px-4 py-8 text-center text-sm text-slate-500">
选择左侧视频点「编辑」可改标题/描述/标签/可见性/定时公开
</div>
)}
<div className="rounded-2xl border border-white/10 bg-black/25 p-4">
<div className="mb-2 flex items-center gap-2 text-sm text-slate-100">
<ListVideo className="h-4 w-4 text-rose-300" />
播放列表
</div>
<div className="max-h-56 space-y-1 overflow-y-auto text-xs text-slate-400">
{playlists.length === 0 ? (
<div>无播放列表</div>
) : (
playlists.map((p) => (
<div key={p.id} className="flex justify-between gap-2 border-b border-white/5 py-1.5">
<span className="truncate text-slate-200">{p.title}</span>
<span>
{p.itemCount ?? 0} · {p.privacyStatus}
</span>
</div>
))
)}
</div>
</div>
</section>
</div>
</>
)}
</>
) : (
<>
<div className="mb-3 flex flex-wrap gap-2">
{(
[
["channel", "频道", <Radio key="a" className="h-3.5 w-3.5" />],
["live", "开播检测", <Clapperboard key="b" className="h-3.5 w-3.5" />],
["video", "视频", <Clapperboard key="c" className="h-3.5 w-3.5" />],
["search", "搜索", <Search key="d" className="h-3.5 w-3.5" />],
["resolve", "解析 URL", <Link2 key="e" className="h-3.5 w-3.5" />],
] as const
).map(([id, label, icon]) => (
<button
key={id}
type="button"
onClick={() => setTab(id)}
className={`inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-sm ${
tab === id ? "bg-teal-500/20 text-teal-50" : "bg-white/5 text-slate-400"
}`}
>
{icon}
{label}
</button>
))}
<button type="button" onClick={() => void checkSvc()} className="rounded-xl bg-white/5 px-3 py-1.5 text-sm">
检查 youtube-svc {svc ? (svc.ok ? "· 正常" : "· 异常") : ""}
</button>
</div>
<div className="mb-4 flex flex-wrap gap-2">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
className="w-full min-w-0 flex-1 rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm sm:min-w-[240px]"
placeholder="@handle / URL / 关键词"
/>
<button
type="button"
disabled={busy}
onClick={() => void runProbe()}
className="inline-flex items-center gap-1 rounded-xl bg-[#ff2d55] px-4 py-2 text-sm text-white"
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
探测
</button>
</div>
{probeChannel ? (
<div className="mb-4 rounded-2xl border border-white/10 bg-black/30 p-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<div className="flex flex-wrap items-center gap-2">
<div className="font-display text-xl">{probeChannel.title}</div>
{live?.is_live ? (
<YouTubeLiveBadge
entry={{
is_live: true,
live_url: live.url || live.watch_url,
title: live.title,
}}
/>
) : null}
</div>
<div className="text-xs text-slate-500">{probeChannel.url || probeChannel.handle}</div>
</div>
<button
type="button"
disabled={addBusy}
onClick={() => void addToGroup(probeChannel)}
className="inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100"
>
<Plus className="h-3.5 w-3.5" />
加入分组
</button>
</div>
</div>
) : null}
{probeVideos?.length ? (
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{probeVideos.map((v: any, i: number) => (
<a
key={v.id || v.url || i}
href={v.url || "#"}
target="_blank"
rel="noreferrer"
className="rounded-xl border border-white/10 bg-black/30 p-3 text-sm hover:bg-white/5"
>
<div className="font-medium text-slate-100">{v.title || "video"}</div>
<div className="mt-1 text-xs text-slate-500">{v.id}</div>
</a>
))}
</div>
) : null}
{result && !probeChannel && !probeVideos?.length ? (
<pre className="mt-4 overflow-x-auto rounded-xl border border-white/10 bg-black/40 p-3 text-xs text-slate-400">
{JSON.stringify(result, null, 2)}
</pre>
) : null}
</>
)}
</Shell>
);
}