"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; thumbnails?: any; url?: string; shorts_url?: string; }; export default function YouTubePage() { const confirm = useConfirm(); const toast = useToast(); const [mode, setMode] = useState("assign"); const [channels, setChannels] = useState([]); const [channelPk, setChannelPk] = useState(""); const [dash, setDash] = useState(null); const [videos, setVideos] = useState([]); const [playlists, setPlaylists] = useState([]); const [edit, setEdit] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const [msg, setMsg] = useState(""); // probe const [tab, setTab] = useState("channel"); const [input, setInput] = useState("@MrBeast"); const [result, setResult] = useState(null); const [svc, setSvc] = useState(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 (

YouTube Studio Lite

▶️ YouTube

分配:频道 + 直播 KEY → 抖音 URL 池 → 精选转播。频道管理:片库 / 元数据 / 可见性。探测仍用 InnerTube。

Shorts → 分组监控 →
{msg ?
{msg}
: null} {error ?
{error}
: null} {mode === "assign" ? ( ) : mode === "manage" ? ( <> {channels.length === 0 ? (
还没有已授权频道。请先到{" "} Shorts {" "} 完成 Google 授权。
) : ( <>
{channels.map((c) => { const active = c.id === channelPk; return ( ); })}
{channelPk ? : null}
{profile ? (
{profile.thumbnails?.default?.url || profile.thumbnails?.medium?.url ? ( // eslint-disable-next-line @next/next/no-img-element ) : (
)}
{profile.title}
{channelPk ? : null}
{profile.custom_url || profile.youtube_channel_id}
订阅 {profile.statistics?.subscriberCount ?? "—"} · 视频 {profile.statistics?.videoCount ?? "—"} · 播放{" "} {profile.statistics?.viewCount ?? "—"}
今日 Shorts 流水
{Object.keys(shortsToday).length === 0 ? ( 无 ) : ( Object.entries(shortsToday).map(([k, v]) => (
{k} {String(v)}
)) )}
播放列表
{playlists.length}
只读(当前 OAuth scope)
) : null}

近期上传

{videos.length === 0 ? (
暂无视频或加载失败
) : ( videos.map((v) => (
{v.thumbnails?.medium?.url || v.thumbnails?.default?.url ? ( // eslint-disable-next-line @next/next/no-img-element ) : (
)}
{v.title}
{v.privacyStatus} · 播放 {v.statistics?.viewCount ?? 0} ·{" "} {v.published_at ? fmtTs(Date.parse(v.published_at) / 1000) : "—"} {v.publishAt ? ` · 定时 ${v.publishAt}` : ""}
打开
)) )}
{edit ? (

编辑视频