douyinWEB/frontend/src/components/YtAssignPanel.tsx
eric 9b2eef646c feat(youtube-assign): show KEY, parse title/cover, copy/export lists
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 01:22:44 -05:00

767 lines
28 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

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, useMemo, useState } from "react";
import Link from "next/link";
import {
Copy,
Download,
Eye,
EyeOff,
Loader2,
Plus,
RefreshCw,
Star,
Trash2,
} from "lucide-react";
import { useConfirm } from "@/components/ConfirmDialog";
import { ImageLightbox } from "@/components/ImageLightbox";
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;
title?: string;
room_id?: string;
cover_url?: string;
};
type FeaturedUrl = {
id: string;
pool_url_id: string;
url?: string;
pool_note?: string;
title?: string;
room_id?: string;
cover_url?: 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 formatExportLine(url: string, title?: string): string {
const u = String(url || "").trim();
const t = String(title || "").trim();
if (!u) return "";
return t ? `${u},主播: ${t},` : `${u},`;
}
function exportText(rows: Array<{ url?: string; title?: string }>): string {
return rows
.map((r) => formatExportLine(String(r.url || ""), r.title))
.filter(Boolean)
.join("\n");
}
async function copyText(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
try {
const ta = document.createElement("textarea");
ta.value = text;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
return true;
} catch {
return false;
}
}
}
function downloadText(filename: string, text: string) {
const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
URL.revokeObjectURL(a.href);
}
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>
);
}
function CoverThumb({
cover,
title,
onOpen,
}: {
cover?: string;
title?: string;
onOpen: (src: string) => void;
}) {
const src = String(cover || "").trim();
if (!src) {
return <div className="h-8 w-8 shrink-0 rounded bg-white/10" title="无封面" />;
}
return (
<button
type="button"
onClick={() => onOpen(src)}
className="h-8 w-8 shrink-0 overflow-hidden rounded border border-white/10 bg-black/40 hover:ring-1 hover:ring-sky-400/40"
title="点击查看封面"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={src} alt={title || "cover"} className="h-full w-full object-cover" />
</button>
);
}
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(true);
const [streamKeyDraft, setStreamKeyDraft] = useState("");
const [noteDraft, setNoteDraft] = useState("");
const [poolDraft, setPoolDraft] = useState("");
const [newChannelPk, setNewChannelPk] = useState("");
const [newStreamKey, setNewStreamKey] = useState("");
const [lightbox, setLightbox] = useState<{ src: string; title?: string; subtitle?: string } | null>(
null
);
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
}
}, []);
useEffect(() => {
void loadGroups();
}, [loadGroups]);
useEffect(() => {
if (!selected) {
setStreamKeyDraft("");
setNoteDraft("");
return;
}
setStreamKeyDraft(String(selected.stream_key || ""));
setNoteDraft(String(selected.note || ""));
setShowKey(true);
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 text = poolDraft.trim();
if (!text) {
toast.push("请粘贴抖音直播间(支持 URL,主播: 名称,)", "err");
return;
}
setBusy(true);
try {
const r = await fetchJson(`/api/youtube/assign/groups/${selected.id}/pool`, {
method: "POST",
body: JSON.stringify({ text }),
});
setPoolDraft("");
const n = Array.isArray(r?.added) ? r.added.length : 0;
toast.push(`已加入普通列表 ${n} 条`, "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);
}
}
async function copyList(kind: "pool" | "featured") {
if (!selected) return;
const rows =
kind === "pool"
? selected.pool || []
: (selected.featured || []).map((f) => ({ url: f.url, title: f.title }));
const text = exportText(rows);
if (!text) {
toast.push("列表为空", "err");
return;
}
const ok = await copyText(text);
toast.push(ok ? `已复制${kind === "pool" ? "普通" : "精选"}列表 ${rows.length} 条` : "复制失败", ok ? "ok" : "err");
}
function exportList(kind: "pool" | "featured") {
if (!selected) return;
const rows =
kind === "pool"
? selected.pool || []
: (selected.featured || []).map((f) => ({ url: f.url, title: f.title }));
const text = exportText(rows);
if (!text) {
toast.push("列表为空", "err");
return;
}
const tag = kind === "pool" ? "pool" : "featured";
const name = String(selected.name || "assign").replace(/[\\/:*?"<>|]+/g, "_").slice(0, 40);
downloadText(`${name}-${tag}.txt`, text);
toast.push(`已导出 ${rows.length} 条`, "ok");
}
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 普通池 → 精选(实时转播)。支持粘贴「URL,主播: 名称,」。
</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 font-mono text-sm"
/>
<button
type="button"
onClick={() => setShowKey((v) => !v)}
className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400"
title={showKey ? "隐藏" : "显示"}
>
{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">
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
<h4 className="text-sm font-medium text-slate-100">
普通列表(URL 池)· {(selected.pool || []).length}
</h4>
<div className="flex flex-wrap gap-1.5">
<button
type="button"
onClick={() => void copyList("pool")}
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px] text-slate-200"
>
<Copy className="h-3 w-3" />
复制
</button>
<button
type="button"
onClick={() => exportList("pool")}
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px] text-slate-200"
>
<Download className="h-3 w-3" />
导出
</button>
</div>
</div>
<p className="mb-3 text-[11px] text-slate-500">
支持:https://live.douyin.com/房间号,主播: 名称,
</p>
<textarea
value={poolDraft}
onChange={(e) => setPoolDraft(e.target.value)}
rows={3}
placeholder={
"每行一条,例如:\nhttps://live.douyin.com/343450949840,主播: 街角早安三明治,"
}
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-center gap-2 rounded-xl border border-white/10 bg-black/40 p-2"
>
<CoverThumb
cover={u.cover_url}
title={u.title}
onOpen={(src) =>
setLightbox({ src, title: u.title || "封面", subtitle: u.url })
}
/>
<div className="min-w-0 flex-1">
<div className="truncate text-sm text-slate-100">{u.title || "未命名主播"}</div>
<a
href={u.url}
target="_blank"
rel="noreferrer"
className="block truncate text-[11px] 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">
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
<h4 className="text-sm font-medium text-amber-50">
精选列表(实时转播)· {(selected.featured || []).length}
</h4>
<div className="flex flex-wrap gap-1.5">
<button
type="button"
onClick={() => void copyList("featured")}
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px] text-amber-50"
>
<Copy className="h-3 w-3" />
复制
</button>
<button
type="button"
onClick={() => exportList("featured")}
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px] text-amber-50"
>
<Download className="h-3 w-3" />
导出
</button>
</div>
</div>
<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-center gap-2 rounded-xl border border-amber-500/25 bg-black/40 p-2"
>
<span className="shrink-0 rounded bg-amber-500/20 px-1.5 text-[10px] text-amber-100">
#{i + 1}
</span>
<CoverThumb
cover={f.cover_url}
title={f.title}
onOpen={(src) =>
setLightbox({ src, title: f.title || "封面", subtitle: f.url })
}
/>
<div className="min-w-0 flex-1">
<div className="truncate text-sm text-amber-50">{f.title || "未命名主播"}</div>
<a
href={f.url || "#"}
target="_blank"
rel="noreferrer"
className="block truncate text-[11px] 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>
)}
{lightbox ? (
<ImageLightbox
src={lightbox.src}
title={lightbox.title}
subtitle={lightbox.subtitle}
onClose={() => setLightbox(null)}
/>
) : null}
</div>
);
}