douyinWEB/youtube-svc/src/youtube.mjs
2026-08-10 20:11:23 -05:00

310 lines
9.3 KiB
JavaScript

import { Innertube, YTNodes } from "youtubei.js";
let ytPromise = null;
export async function getYt() {
if (!ytPromise) {
ytPromise = Innertube.create().catch((err) => {
ytPromise = null;
throw err;
});
}
return ytPromise;
}
export function resetYt() {
ytPromise = null;
}
async function withYtRetry(fn) {
try {
return await fn(await getYt());
} catch (err) {
const msg = String(err?.message || err);
if (/status 400|status 429|failed with status/i.test(msg)) {
resetYt();
return await fn(await getYt());
}
throw err;
}
}
export function textOf(v) {
if (v == null) return "";
if (typeof v === "string") return v;
if (typeof v.toString === "function") {
const s = v.toString();
return s === "[object Object]" ? "" : s;
}
return String(v);
}
export function thumbUrl(thumbs) {
if (!thumbs) return "";
const list = Array.isArray(thumbs) ? thumbs : thumbs?.length != null ? [...thumbs] : [];
if (!list.length) return "";
const best = list[list.length - 1];
return best?.url || best?.url || "";
}
export function serializeVideo(v) {
if (!v) return null;
const id = v.id || v.video_id || "";
return {
id,
title: textOf(v.title),
url: id ? `https://www.youtube.com/watch?v=${id}` : "",
published: textOf(v.published),
duration: textOf(v.duration) || (v.duration?.text ? textOf(v.duration.text) : ""),
view_count: textOf(v.view_count_text || v.short_view_count) || null,
is_live: Boolean(v.is_live),
is_upcoming: Boolean(v.is_upcoming),
is_live_content: Boolean(v.is_live_content ?? v.is_live ?? v.is_upcoming),
thumbnail: thumbUrl(v.thumbnails || v.best_thumbnail),
author: v.author?.name || textOf(v.author) || "",
};
}
/**
* Resolve channel / video / playlist URLs (or bare UC… / @handle) to a useful identity.
*/
export async function resolveInput(raw) {
const text = String(raw || "").trim();
if (!text) throw new Error("url / id 不能为空");
// bare channel id
if (/^UC[\w-]{20,}$/.test(text)) {
return { kind: "channel", channel_id: text, url: `https://www.youtube.com/channel/${text}` };
}
// bare video id
if (/^[\w-]{11}$/.test(text) && !text.startsWith("@")) {
return { kind: "video", video_id: text, url: `https://www.youtube.com/watch?v=${text}` };
}
let url = text;
if (text.startsWith("@")) {
url = `https://www.youtube.com/${text}`;
} else if (!/^https?:\/\//i.test(text) && /youtube\.com|youtu\.be/i.test(text)) {
url = `https://${text.replace(/^\/+/, "")}`;
} else if (!/^https?:\/\//i.test(text)) {
url = `https://www.youtube.com/@${text.replace(/^@/, "")}`;
}
return withYtRetry(async (yt) => {
const endpoint = await yt.resolveURL(url);
const payload = endpoint?.payload || {};
const browseId = payload.browseId || "";
const videoId = payload.videoId || "";
const playlistId = payload.playlistId || "";
if (browseId?.startsWith("UC")) {
return { kind: "channel", channel_id: browseId, url: `https://www.youtube.com/channel/${browseId}`, raw: payload };
}
if (videoId) {
return { kind: "video", video_id: videoId, url: `https://www.youtube.com/watch?v=${videoId}`, raw: payload };
}
if (playlistId) {
return { kind: "playlist", playlist_id: playlistId, url: `https://www.youtube.com/playlist?list=${playlistId}`, raw: payload };
}
if (browseId) {
return { kind: "browse", browse_id: browseId, url, raw: payload };
}
throw new Error(`无法解析:${text}`);
});
}
export async function getChannelBundle(raw, { includeLive = true, includeVideos = false, videoLimit = 8 } = {}) {
const resolved = await resolveInput(raw);
let channelId = resolved.channel_id;
if (!channelId && resolved.kind === "video") {
const info = await getVideoInfo(resolved.video_id);
channelId = info?.channel_id || "";
}
if (!channelId) throw new Error("未能得到频道 ID");
const channel = await withYtRetry((client) => client.getChannel(channelId));
const header = channel.header;
let title = "";
let handle = "";
let subscribers = "";
let avatar = "";
let banner = "";
if (header) {
if (typeof header.is === "function" && header.is(YTNodes.C4TabbedHeader)) {
title = header.author?.name || textOf(header.title) || "";
handle = textOf(header.channel_handle);
subscribers = textOf(header.subscribers?.text || header.subscriber_count);
avatar = thumbUrl(header.author?.thumbnails || header.avatar);
banner = thumbUrl(header.banner);
} else {
title = textOf(header.title) || header.author?.name || "";
handle = textOf(header.channel_handle || header.handle);
subscribers = textOf(header.subscribers?.text || header.subscriber_count);
avatar = thumbUrl(header.author?.thumbnails || header.avatar);
}
}
const meta = channel.metadata || {};
if (!title) title = textOf(meta.title) || "";
if (!avatar) avatar = thumbUrl(meta.avatar);
const about = {
description: textOf(meta.description),
is_family_safe: Boolean(meta.is_family_safe),
rss_url: meta.rss_url || "",
keywords: Array.isArray(meta.keywords) ? meta.keywords : [],
};
let live = null;
let upcoming = [];
let lives = [];
async function confirmLive(item) {
if (!item?.id) return null;
if (item.is_live) return item;
try {
const basic = await withYtRetry((client) => client.getBasicInfo(item.id));
const bi = basic?.basic_info || {};
if (bi.is_live) {
return {
...item,
title: bi.title || item.title,
is_live: true,
is_upcoming: Boolean(bi.is_upcoming),
is_live_content: Boolean(bi.is_live_content),
view_count: bi.view_count != null ? String(bi.view_count) : item.view_count,
};
}
} catch {
/* ignore */
}
return null;
}
async function scanFeedVideos(videos, limit = 12) {
for (const v of (videos || []).slice(0, limit)) {
const item = serializeVideo(v);
if (!item) continue;
lives.push(item);
if (item.is_upcoming) upcoming.push(item);
if (item.is_live && !live) {
live = item;
return;
}
if ((item.is_live_content || item.is_live) && !live) {
const confirmed = await confirmLive(item);
if (confirmed) {
live = confirmed;
return;
}
}
}
}
if (includeLive) {
// 1) Live tab
try {
const feed = await channel.getLiveStreams();
await scanFeedVideos(feed?.videos, 20);
if (!live && lives[0]?.id) {
const confirmed = await confirmLive(lives[0]);
if (confirmed) live = confirmed;
}
} catch {
/* some channels have no live tab */
}
// 2) Home tab — active streams often pinned here
if (!live) {
try {
const home = await channel.getHome();
await scanFeedVideos(home?.videos, 10);
} catch {
/* ignore */
}
}
// 3) Videos tab — recent live may appear as first upload
if (!live) {
try {
const feed = await channel.getVideos();
await scanFeedVideos(feed?.videos, 8);
} catch {
/* ignore */
}
}
}
let videos = [];
if (includeVideos) {
try {
const feed = await channel.getVideos();
videos = (feed?.videos || []).slice(0, videoLimit).map(serializeVideo).filter(Boolean);
} catch {
/* ignore */
}
}
return {
channel_id: channelId,
title,
handle: handle ? String(handle).replace(/^@/, "") : "",
url: `https://www.youtube.com/channel/${channelId}`,
handle_url: handle ? `https://www.youtube.com/@${String(handle).replace(/^@/, "")}` : "",
subscribers,
avatar,
banner,
about,
is_live: Boolean(live),
live,
upcoming,
live_streams: lives,
videos,
resolved,
};
}
export async function getVideoInfo(raw) {
let videoId = String(raw || "").trim();
if (!/^[\w-]{11}$/.test(videoId)) {
const resolved = await resolveInput(raw);
if (resolved.kind !== "video" || !resolved.video_id) throw new Error("不是有效的视频");
videoId = resolved.video_id;
}
const info = await withYtRetry((yt) => yt.getBasicInfo(videoId));
const bi = info.basic_info || {};
return {
id: videoId,
title: bi.title || "",
description: (bi.short_description || "").slice(0, 2000),
channel_id: bi.channel_id || "",
channel: bi.author || "",
url: `https://www.youtube.com/watch?v=${videoId}`,
duration: bi.duration ?? null,
view_count: bi.view_count ?? null,
is_live: Boolean(bi.is_live),
is_upcoming: Boolean(bi.is_upcoming),
is_live_content: Boolean(bi.is_live_content),
is_private: Boolean(bi.is_private),
thumbnail: thumbUrl(bi.thumbnail),
};
}
export async function searchVideos(query, limit = 12) {
const q = String(query || "").trim();
if (!q) throw new Error("搜索词不能为空");
const res = await withYtRetry((yt) => yt.search(q));
const results = [];
for (const item of res.results || []) {
if (results.length >= limit) break;
if (item?.type === "Video" || (typeof item?.is === "function" && item.is(YTNodes.Video))) {
results.push(serializeVideo(item));
} else if (item?.id && item?.title) {
results.push(serializeVideo(item));
}
}
return { query: q, results, estimated_results: res.estimated_results ?? null };
}