feat(youtube): add Assign tab as default next to OAuth manage

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-20 21:38:48 -05:00
parent c9e29cc6e6
commit 42c4a7494e
2 changed files with 598 additions and 4 deletions

View File

@ -16,16 +16,18 @@ import {
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 { fetchJson, fmtTs } from "@/lib/api";
import { shortsLiveRef } from "@/lib/youtubeLive";
type Mode = "manage" | "probe";
type Mode = "assign" | "manage" | "probe";
type ProbeTab = "channel" | "live" | "video" | "search" | "resolve";
type ManagedChannel = {
@ -55,7 +57,7 @@ type YtVideo = {
export default function YouTubePage() {
const confirm = useConfirm();
const toast = useToast();
const [mode, setMode] = useState<Mode>("manage");
const [mode, setMode] = useState<Mode>("assign");
const [channels, setChannels] = useState<ManagedChannel[]>([]);
const [channelPk, setChannelPk] = useState("");
const [dash, setDash] = useState<any>(null);
@ -250,7 +252,7 @@ export default function YouTubePage() {
<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">
已授权频道:片库 / 改元数据 / 可见性 / 定时公开 / 删除 / 播放列表只读。探测仍用 InnerTube。
分配:频道 + 直播 KEY → 抖音 URL 池 → 精选转播。频道管理:片库 / 元数据 / 可见性。探测仍用 InnerTube。
</p>
</div>
<div className="flex flex-wrap gap-2">
@ -264,6 +266,16 @@ export default function YouTubePage() {
</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")}
@ -289,7 +301,9 @@ export default function YouTubePage() {
{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 === "manage" ? (
{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">

View File

@ -0,0 +1,580 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { Eye, EyeOff, Loader2, Plus, RefreshCw, Star, Trash2 } from "lucide-react";
import { useConfirm } from "@/components/ConfirmDialog";
import { useToast } from "@/components/Toast";
import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet";
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
import { fetchJson } from "@/lib/api";
import { shortsLiveRef } from "@/lib/youtubeLive";
type ManagedChannel = {
id: string;
name?: string;
youtube_channel_id?: string;
authorized?: boolean;
};
type PoolUrl = {
id: string;
url: string;
note?: string;
};
type FeaturedUrl = {
id: string;
pool_url_id: string;
url?: string;
pool_note?: string;
};
type AssignGroup = {
id: string;
name?: string;
channel_pk?: string;
youtube_channel_id?: string;
stream_key?: string;
stream_key_masked?: string;
has_stream_key?: boolean;
note?: string;
enabled?: boolean;
pool?: PoolUrl[];
featured?: FeaturedUrl[];
};
function ManageStyleProfileCard({
profile,
channelPk,
fallbackName,
fallbackChannelId,
}: {
profile?: YtProfileSnippet | null;
channelPk?: string;
fallbackName?: string;
fallbackChannelId?: string;
}) {
const title = String(profile?.title || fallbackName || "未命名").trim() || "未命名";
const handle =
String(profile?.custom_url || "").trim() ||
String(fallbackChannelId || profile?.youtube_channel_id || "").trim();
const thumb =
String(profile?.thumb_url || "").trim() ||
String(profile?.thumbnails?.medium?.url || profile?.thumbnails?.default?.url || "").trim();
const stats = profile?.statistics;
return (
<div className="rounded-2xl border border-white/10 bg-black/30 p-4">
<div className="flex gap-3">
{thumb ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={thumb} alt="" className="h-14 w-14 rounded-full object-cover" />
) : (
<div className="h-14 w-14 rounded-full bg-white/10" />
)}
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<div className="font-display text-xl text-white">{title}</div>
{channelPk ? <YouTubeLiveBadge refKey={shortsLiveRef(channelPk)} compact /> : null}
</div>
<div className="text-xs text-slate-500">{handle || "—"}</div>
<div className="mt-1 text-xs text-slate-400">
订阅 {stats?.subscriberCount ?? "—"} · 视频 {stats?.videoCount ?? "—"} · 播放{" "}
{stats?.viewCount ?? "—"}
</div>
</div>
</div>
</div>
);
}
export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
const confirm = useConfirm();
const toast = useToast();
const [groups, setGroups] = useState<AssignGroup[]>([]);
const [groupId, setGroupId] = useState("");
const [profiles, setProfiles] = useState<Record<string, YtProfileSnippet>>({});
const [busy, setBusy] = useState(false);
const [showKey, setShowKey] = useState(false);
const [streamKeyDraft, setStreamKeyDraft] = useState("");
const [noteDraft, setNoteDraft] = useState("");
const [poolDraft, setPoolDraft] = useState("");
const [newChannelPk, setNewChannelPk] = useState("");
const [newStreamKey, setNewStreamKey] = useState("");
const selected = useMemo(() => groups.find((g) => g.id === groupId) || null, [groups, groupId]);
const featuredIds = useMemo(
() => new Set((selected?.featured || []).map((f) => String(f.pool_url_id))),
[selected]
);
const loadGroups = useCallback(async () => {
setBusy(true);
try {
const data = await fetchJson("/api/youtube/assign/groups");
const list: AssignGroup[] = data.groups || [];
setGroups(list);
setGroupId((prev) => {
if (prev && list.some((g) => g.id === prev)) return prev;
return list[0]?.id || "";
});
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}, [toast]);
const loadProfile = useCallback(async (channelPk: string) => {
if (!channelPk) return;
try {
const cached = await fetchJson("/api/youtube/manage/profiles").catch(() => ({ profiles: {} }));
const fromCache = cached?.profiles?.[channelPk];
if (fromCache) {
setProfiles((p) => ({ ...p, [channelPk]: fromCache }));
}
const live = await fetchJson(`/api/youtube/manage/${channelPk}/profile`);
setProfiles((p) => ({ ...p, [channelPk]: live }));
} catch {
// keep fallback name on card
}
}, []);
useEffect(() => {
void loadGroups();
}, [loadGroups]);
useEffect(() => {
if (!selected) {
setStreamKeyDraft("");
setNoteDraft("");
return;
}
setStreamKeyDraft(String(selected.stream_key || ""));
setNoteDraft(String(selected.note || ""));
setShowKey(false);
if (selected.channel_pk) void loadProfile(selected.channel_pk);
}, [selected, loadProfile]);
async function createGroup() {
if (!newChannelPk) {
toast.push("请选择已授权频道", "err");
return;
}
setBusy(true);
try {
const r = await fetchJson("/api/youtube/assign/groups", {
method: "POST",
body: JSON.stringify({
channel_pk: newChannelPk,
stream_key: newStreamKey,
enabled: true,
}),
});
toast.push("已新建分配分组", "ok");
setNewStreamKey("");
await loadGroups();
if (r?.group?.id) setGroupId(r.group.id);
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function saveGroupMeta() {
if (!selected) return;
setBusy(true);
try {
await fetchJson(`/api/youtube/assign/groups/${selected.id}`, {
method: "PATCH",
body: JSON.stringify({
stream_key: streamKeyDraft,
note: noteDraft,
}),
});
toast.push("已保存直播 KEY / 备注", "ok");
await loadGroups();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function removeGroup() {
if (!selected) return;
const ok = await confirm({
title: "删除分配分组",
message: `确定删除「${selected.name || selected.id}」?普通列表与精选会一并删除。`,
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
setBusy(true);
try {
await fetchJson(`/api/youtube/assign/groups/${selected.id}`, { method: "DELETE" });
toast.push("已删除", "ok");
setGroupId("");
await loadGroups();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function addPoolUrls() {
if (!selected) return;
const urls = poolDraft
.split(/[\n,]+/)
.map((s) => s.trim())
.filter(Boolean);
if (!urls.length) {
toast.push("请粘贴抖音直播间 URL", "err");
return;
}
setBusy(true);
try {
await fetchJson(`/api/youtube/assign/groups/${selected.id}/pool`, {
method: "POST",
body: JSON.stringify({ urls }),
});
setPoolDraft("");
toast.push(`已加入普通列表 ${urls.length} 条`, "ok");
await loadGroups();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function deletePool(poolId: string) {
const ok = await confirm({
title: "删除普通列表 URL",
message: "若已在精选中,会一并移除。",
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
setBusy(true);
try {
await fetchJson(`/api/youtube/assign/pool/${poolId}`, { method: "DELETE" });
await loadGroups();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function addFeatured(poolUrlId: string) {
if (!selected) return;
setBusy(true);
try {
await fetchJson(`/api/youtube/assign/groups/${selected.id}/featured`, {
method: "POST",
body: JSON.stringify({ pool_url_id: poolUrlId }),
});
await loadGroups();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
async function removeFeatured(featuredId: string) {
setBusy(true);
try {
await fetchJson(`/api/youtube/assign/featured/${featuredId}`, { method: "DELETE" });
await loadGroups();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
}
}
const usedChannelPks = useMemo(() => new Set(groups.map((g) => String(g.channel_pk || ""))), [groups]);
const availableChannels = channels.filter((c) => !usedChannelPks.has(c.id));
return (
<div className="space-y-4">
<div className="rounded-2xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<h3 className="text-sm font-medium text-slate-100">转播分配</h3>
<p className="mt-0.5 text-xs text-slate-500">
频道 + 直播 KEY → 抖音 URL 普通池 → 精选(实时转播用)。频道资料复用 OAuth 管理卡片。
</p>
</div>
<button
type="button"
onClick={() => void loadGroups()}
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>
<div className="grid gap-2 sm:grid-cols-[1.2fr_1fr_auto]">
<select
value={newChannelPk}
onChange={(e) => setNewChannelPk(e.target.value)}
className="rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm"
>
<option value="">选择已授权频道…</option>
{availableChannels.map((c) => (
<option key={c.id} value={c.id}>
{c.name} {c.youtube_channel_id ? `(${c.youtube_channel_id.slice(0, 8)}…)` : ""}
</option>
))}
</select>
<input
value={newStreamKey}
onChange={(e) => setNewStreamKey(e.target.value)}
placeholder="直播推流 KEY(可后填)"
className="rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
<button
type="button"
disabled={busy || !newChannelPk}
onClick={() => void createGroup()}
className="inline-flex items-center justify-center gap-1 rounded-xl bg-[#ff2d55] px-4 py-2 text-sm text-white disabled:opacity-40"
>
<Plus className="h-4 w-4" />
新建分组
</button>
</div>
{channels.length === 0 ? (
<p className="mt-3 text-xs text-amber-200">
还没有已授权频道。请先到{" "}
<Link href="/shorts" className="underline">
Shorts
</Link>{" "}
完成 Google 授权。
</p>
) : null}
</div>
{groups.length === 0 ? (
<div className="rounded-2xl border border-dashed border-white/10 px-4 py-12 text-center text-sm text-slate-500">
暂无分配分组。上方选择频道并新建。
</div>
) : (
<div className="grid gap-4 xl:grid-cols-[240px_1fr]">
<aside className="space-y-2">
{groups.map((g) => {
const pk = String(g.channel_pk || "");
const active = g.id === groupId;
return (
<button
key={g.id}
type="button"
onClick={() => setGroupId(g.id)}
className={`w-full 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={profiles[pk]}
fallbackName={g.name}
fallbackChannelId={g.youtube_channel_id}
liveChannelPk={pk || undefined}
/>
<div className="mt-2 flex flex-wrap gap-2 text-[10px] text-slate-500">
<span>池 {(g.pool || []).length}</span>
<span>精选 {(g.featured || []).length}</span>
<span>{g.has_stream_key ? "KEY✓" : "无 KEY"}</span>
</div>
</button>
);
})}
</aside>
{selected ? (
<div className="space-y-4">
<ManageStyleProfileCard
profile={profiles[String(selected.channel_pk || "")]}
channelPk={selected.channel_pk}
fallbackName={selected.name}
fallbackChannelId={selected.youtube_channel_id}
/>
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
<h4 className="mb-3 text-sm font-medium text-slate-100">直播 KEY / 备注</h4>
<div className="flex flex-wrap gap-2">
<div className="relative min-w-0 flex-1">
<input
type={showKey ? "text" : "password"}
value={streamKeyDraft}
onChange={(e) => setStreamKeyDraft(e.target.value)}
placeholder="YouTube 直播推流密钥"
className="w-full rounded-xl border border-white/10 bg-slate-900 px-3 py-2 pr-10 text-sm"
/>
<button
type="button"
onClick={() => setShowKey((v) => !v)}
className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400"
>
{showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
<input
value={noteDraft}
onChange={(e) => setNoteDraft(e.target.value)}
placeholder="备注"
className="w-full min-w-0 flex-1 rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm sm:max-w-xs"
/>
<button
type="button"
disabled={busy}
onClick={() => void saveGroupMeta()}
className="rounded-xl border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-100"
>
保存
</button>
<button
type="button"
disabled={busy}
onClick={() => void removeGroup()}
className="inline-flex items-center gap-1 rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-100"
>
<Trash2 className="h-3.5 w-3.5" />
删除分组
</button>
</div>
</section>
<div className="grid gap-4 lg:grid-cols-2">
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
<h4 className="mb-1 text-sm font-medium text-slate-100">
普通列表(URL 池)· {(selected.pool || []).length}
</h4>
<p className="mb-3 text-[11px] text-slate-500">分配给该频道的抖音直播间 URL,可增删。</p>
<textarea
value={poolDraft}
onChange={(e) => setPoolDraft(e.target.value)}
rows={3}
placeholder={"每行一个 URL,例如:\nhttps://live.douyin.com/123456"}
className="mb-2 w-full rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
<button
type="button"
disabled={busy}
onClick={() => void addPoolUrls()}
className="mb-3 inline-flex items-center gap-1 rounded-lg bg-white/10 px-3 py-1.5 text-xs"
>
<Plus className="h-3.5 w-3.5" />
加入普通列表
</button>
<div className="max-h-80 space-y-2 overflow-y-auto">
{(selected.pool || []).length === 0 ? (
<div className="py-6 text-center text-xs text-slate-500">池为空</div>
) : (
(selected.pool || []).map((u) => {
const inFeat = featuredIds.has(u.id);
return (
<div
key={u.id}
className="flex items-start gap-2 rounded-xl border border-white/10 bg-black/40 p-2.5"
>
<div className="min-w-0 flex-1">
<a
href={u.url}
target="_blank"
rel="noreferrer"
className="break-all text-xs text-sky-300 hover:underline"
>
{u.url}
</a>
</div>
<div className="flex shrink-0 gap-1">
<button
type="button"
disabled={busy || inFeat}
title={inFeat ? "已在精选" : "加入精选"}
onClick={() => void addFeatured(u.id)}
className={`rounded-lg px-2 py-1 text-[11px] ${
inFeat
? "bg-amber-500/20 text-amber-100"
: "bg-white/5 text-slate-300 hover:bg-amber-500/15"
}`}
>
<Star className="h-3 w-3" />
</button>
<button
type="button"
disabled={busy}
onClick={() => void deletePool(u.id)}
className="rounded-lg bg-rose-500/10 px-2 py-1 text-rose-200"
>
<Trash2 className="h-3 w-3" />
</button>
</div>
</div>
);
})
)}
</div>
</section>
<section className="rounded-2xl border border-amber-500/20 bg-amber-500/5 p-4">
<h4 className="mb-1 text-sm font-medium text-amber-50">
精选列表(实时转播)· {(selected.featured || []).length}
</h4>
<p className="mb-3 text-[11px] text-amber-100/70">
只能从普通池选出;真正用于实时转播的子集。
</p>
<div className="max-h-[28rem] space-y-2 overflow-y-auto">
{(selected.featured || []).length === 0 ? (
<div className="py-10 text-center text-xs text-amber-100/50">
从左侧普通列表点星标加入精选
</div>
) : (
(selected.featured || []).map((f, i) => (
<div
key={f.id}
className="flex items-start gap-2 rounded-xl border border-amber-500/25 bg-black/40 p-2.5"
>
<span className="mt-0.5 shrink-0 rounded bg-amber-500/20 px-1.5 text-[10px] text-amber-100">
#{i + 1}
</span>
<div className="min-w-0 flex-1">
<a
href={f.url || "#"}
target="_blank"
rel="noreferrer"
className="break-all text-xs text-sky-300 hover:underline"
>
{f.url || f.pool_url_id}
</a>
</div>
<button
type="button"
disabled={busy}
onClick={() => void removeFeatured(f.id)}
className="rounded-lg bg-rose-500/10 px-2 py-1 text-rose-200"
>
<Trash2 className="h-3 w-3" />
</button>
</div>
))
)}
</div>
</section>
</div>
</div>
) : null}
</div>
)}
</div>
);
}