"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 { 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 (
{thumb ? ( // eslint-disable-next-line @next/next/no-img-element ) : (
)}
{title}
{channelPk ? : null}
{handle || "—"}
订阅 {stats?.subscriberCount ?? "—"} · 视频 {stats?.videoCount ?? "—"} · 播放{" "} {stats?.viewCount ?? "—"}
); } function CoverThumb({ cover, title, onOpen, }: { cover?: string; title?: string; onOpen: (src: string) => void; }) { const src = String(cover || "").trim(); if (!src) { return
; } return ( ); } export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { const confirm = useConfirm(); const toast = useToast(); const [groups, setGroups] = useState([]); const [groupId, setGroupId] = useState(""); const [profiles, setProfiles] = useState>({}); 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 (

转播分配

频道 + 直播 KEY → 抖音 URL 普通池 → 精选(实时转播)。支持粘贴「URL,主播: 名称,」。

setNewStreamKey(e.target.value)} placeholder="直播推流 KEY(可后填)" className="rounded-xl border border-white/10 bg-slate-900 px-3 py-2 text-sm" />
{channels.length === 0 ? (

还没有已授权频道。请先到{" "} Shorts {" "} 完成 Google 授权。

) : null}
{groups.length === 0 ? (
暂无分配分组。上方选择频道并新建。
) : (
{selected ? (

直播 KEY / 备注

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" />
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" />

普通列表(URL 池)· {(selected.pool || []).length}

支持:https://live.douyin.com/房间号,主播: 名称,