fix(route/youtube): get subtitle for google api

This commit is contained in:
Stephen Zhou
2025-09-28 10:59:19 +08:00
parent f8da14e119
commit 41b403e92e
3 changed files with 113 additions and 57 deletions
+20 -6
View File
@@ -10,6 +10,8 @@ import NotFoundError from '@/errors/types/not-found';
import { Data } from '@/types';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration.js';
import { getSrtAttachmentBatch } from './subtitles';
dayjs.extend(duration);
let count = 0;
@@ -105,8 +107,9 @@ export const getDataByUsername = async ({ username, embed, filterShorts }: { use
if (!playlistItems) {
throw new NotFoundError("This channel doesn't have any content.");
}
const videoIds = playlistItems.data.items.map((item) => item.snippet.resourceId.videoId).join(',');
const videoDetails = await utils.getVideos(videoIds, 'contentDetails', cache);
const videoIds = playlistItems.data.items.map((item) => item.snippet.resourceId.videoId);
const videoDetails = await utils.getVideos(videoIds.join(','), 'contentDetails', cache);
const subtitlesMap = await getSrtAttachmentBatch(videoIds);
return {
title: `${userHandleData?.channelName || username} - YouTube`,
@@ -120,6 +123,8 @@ export const getDataByUsername = async ({ username, embed, filterShorts }: { use
const videoId = snippet.resourceId.videoId;
const img = utils.getThumbnail(snippet.thumbnails);
const detail = videoDetails?.data.items.find((d) => d.id === videoId);
const srtAttachments = subtitlesMap[videoId] || [];
return {
title: snippet.title,
description: utils.renderDescription(embed, videoId, img, utils.formatDescription(snippet.description)),
@@ -133,6 +138,7 @@ export const getDataByUsername = async ({ username, embed, filterShorts }: { use
mime_type: 'text/html',
duration_in_seconds: detail?.contentDetails.duration ? dayjs.duration(detail.contentDetails.duration).asSeconds() : undefined,
},
...srtAttachments,
],
};
}),
@@ -147,8 +153,9 @@ export const getDataByChannelId = async ({ channelId, embed, filterShorts }: { c
const playlistId = filterShorts ? utils.getPlaylistWithShortsFilter(channelId) : originalPlaylistId;
const data = (await utils.getPlaylistItems(playlistId, 'snippet', cache)).data.items;
const videoIds = data.map((item) => item.snippet.resourceId.videoId).join(',');
const videoDetails = await utils.getVideos(videoIds, 'contentDetails', cache);
const videoIds = data.map((item) => item.snippet.resourceId.videoId);
const videoDetails = await utils.getVideos(videoIds.join(','), 'contentDetails', cache);
const subtitlesMap = await getSrtAttachmentBatch(videoIds);
return {
title: `${data[0].snippet.channelTitle} - YouTube`,
@@ -161,6 +168,8 @@ export const getDataByChannelId = async ({ channelId, embed, filterShorts }: { c
const videoId = snippet.resourceId.videoId;
const img = utils.getThumbnail(snippet.thumbnails);
const detail = videoDetails?.data.items.find((d) => d.id === videoId);
const srtAttachments = subtitlesMap[videoId] || [];
return {
title: snippet.title,
description: utils.renderDescription(embed, videoId, img, utils.formatDescription(snippet.description)),
@@ -174,6 +183,7 @@ export const getDataByChannelId = async ({ channelId, embed, filterShorts }: { c
mime_type: 'text/html',
duration_in_seconds: detail?.contentDetails.duration ? dayjs.duration(detail.contentDetails.duration).asSeconds() : undefined,
},
...srtAttachments,
],
};
}),
@@ -184,8 +194,9 @@ export const getDataByPlaylistId = async ({ playlistId, embed }: { playlistId: s
const playlistTitle = (await utils.getPlaylist(playlistId, 'snippet', cache)).data.items[0].snippet.title;
const data = (await utils.getPlaylistItems(playlistId, 'snippet', cache)).data.items.filter((d) => d.snippet.title !== 'Private video' && d.snippet.title !== 'Deleted video');
const videoIds = data.map((item) => item.snippet.resourceId.videoId).join(',');
const videoDetails = await utils.getVideos(videoIds, 'contentDetails', cache);
const videoIds = data.map((item) => item.snippet.resourceId.videoId);
const videoDetails = await utils.getVideos(videoIds.join(','), 'contentDetails', cache);
const subtitlesMap = await getSrtAttachmentBatch(videoIds);
return {
title: `${playlistTitle} by ${data[0].snippet.channelTitle} - YouTube`,
@@ -196,6 +207,8 @@ export const getDataByPlaylistId = async ({ playlistId, embed }: { playlistId: s
const videoId = snippet.resourceId.videoId;
const img = utils.getThumbnail(snippet.thumbnails);
const detail = videoDetails?.data.items.find((d) => d.id === videoId);
const srtAttachments = subtitlesMap[videoId] || [];
return {
title: snippet.title,
description: utils.renderDescription(embed, videoId, img, utils.formatDescription(snippet.description)),
@@ -209,6 +222,7 @@ export const getDataByPlaylistId = async ({ playlistId, embed }: { playlistId: s
mime_type: 'text/html',
duration_in_seconds: detail?.contentDetails.duration ? dayjs.duration(detail.contentDetails.duration).asSeconds() : undefined,
},
...srtAttachments,
],
};
}),
+86
View File
@@ -0,0 +1,86 @@
import { getSubtitles } from 'youtube-caption-extractor';
import pMap from 'p-map';
import cache from '@/utils/cache';
function pad(n: number, width: number = 2) {
return String(n).padStart(width, '0');
}
function toSrtTime(seconds: number): string {
const totalMs = Math.floor(seconds * 1000);
const hours = Math.floor(totalMs / 3_600_000);
const minutes = Math.floor((totalMs % 3_600_000) / 60000);
const secs = Math.floor((totalMs % 60000) / 1000);
const millis = totalMs % 1000;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)},${pad(millis, 3)}`;
}
export type Subtitle = {
start: string;
dur: string;
text: string;
};
function convertToSrt(segments: Subtitle[]): string {
return segments
.map((seg, index) => {
const start = Number.parseFloat(seg.start);
const end = start + Number.parseFloat(seg.dur);
return `${index + 1}
${toSrtTime(start)} --> ${toSrtTime(end)}
${seg.text}
`;
})
.join('\n');
}
export const getSubtitlesByVideoId = (videoId: string) =>
cache.tryGet(`youtube:getSubtitlesByVideoId:${videoId}`, async () => {
try {
const subtitles = await getSubtitles({ videoID: videoId });
const srt = convertToSrt(subtitles);
return srt;
} catch {
// Return empty string if subtitles are not available
return '';
}
});
const createSubtitleDataUrl = (srt: string): string => `data:text/plain;charset=utf-8,${encodeURIComponent(srt)}`;
function createSrtAttachmentFromSrt(srt: string): Array<{ url: string; mime_type: string; title: string }> {
if (!srt || srt.trim() === '') {
return [];
}
const dataUrl = createSubtitleDataUrl(srt);
return [
{
url: dataUrl,
mime_type: 'text/srt',
title: 'Subtitles',
},
];
}
export const getSrtAttachment = async (videoId: string): Promise<Array<{ url: string; mime_type: string; title: string }>> => {
try {
const srt = await getSubtitlesByVideoId(videoId);
return createSrtAttachmentFromSrt(srt);
} catch {
return [];
}
};
export const getSrtAttachmentBatch = async (videoIds: string[]) => {
const results = await pMap(
videoIds,
async (videoId) => {
const srt = await getSubtitlesByVideoId(videoId);
return { videoId, srt: createSrtAttachmentFromSrt(srt) };
},
{ concurrency: 5 }
);
return Object.fromEntries(results.map(({ videoId, srt }) => [videoId, srt]));
};
+7 -51
View File
@@ -1,44 +1,12 @@
import { getSubtitles } from 'youtube-caption-extractor';
import { Data } from '@/types';
import cache from '@/utils/cache';
import { parseRelativeDate } from '@/utils/parse-date';
import { Innertube } from 'youtubei.js';
import utils, { getVideoUrl } from '../utils';
import { Data } from '@/types';
import { parseRelativeDate } from '@/utils/parse-date';
import { getSrtAttachmentBatch } from './subtitles';
const innertubePromise = Innertube.create();
function pad(n: number, width: number = 2) {
return String(n).padStart(width, '0');
}
function toSrtTime(seconds: number): string {
const totalMs = Math.floor(seconds * 1000);
const hours = Math.floor(totalMs / 3_600_000);
const minutes = Math.floor((totalMs % 3_600_000) / 60000);
const secs = Math.floor((totalMs % 60000) / 1000);
const millis = totalMs % 1000;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)},${pad(millis, 3)}`;
}
type Subtitle = {
start: string;
dur: string;
text: string;
};
function convertToSrt(segments: Subtitle[]): string {
return segments
.map((seg, index) => {
const start = Number.parseFloat(seg.start);
const end = start + Number.parseFloat(seg.dur);
return `${index + 1}
${toSrtTime(start)} --> ${toSrtTime(end)}
${seg.text}
`;
})
.join('\n');
}
export const getChannelIdByUsername = (username: string) =>
cache.tryGet(`youtube:getChannelIdByUsername:${username}`, async () => {
const innertube = await innertubePromise;
@@ -51,17 +19,11 @@ export const getDataByUsername = async ({ username, embed, filterShorts }: { use
return getDataByChannelId({ channelId, embed, filterShorts });
};
const getSubtitlesByVideoId = (videoId: string) =>
cache.tryGet(`youtube:getSubtitlesByVideoId:${videoId}`, async () => {
const subtitles = await getSubtitles({ videoID: videoId });
const srt = convertToSrt(subtitles);
return srt;
});
export const getDataByChannelId = async ({ channelId, embed }: { channelId: string; embed: boolean; filterShorts: boolean }): Promise<Data> => {
const innertube = await innertubePromise;
const channel = await innertube.getChannel(channelId);
const videos = await channel.getVideos();
const videoSubtitles = await getSrtAttachmentBatch(videos.videos.filter((video) => 'video_id' in video).map((video) => video.video_id));
return {
title: `${channel.metadata.title || channelId} - YouTube`,
@@ -72,10 +34,8 @@ export const getDataByChannelId = async ({ channelId, embed }: { channelId: stri
item: await Promise.all(
videos.videos
.filter((video) => 'video_id' in video)
.map(async (video) => {
const srt = await getSubtitlesByVideoId(video.video_id);
const dataUrl = `data:text/plain;charset=utf-8,${encodeURIComponent(srt)}`;
.map((video) => {
const srtAttachments = videoSubtitles[video.video_id] || [];
const img = 'best_thumbnail' in video ? video.best_thumbnail?.url : 'thumbnails' in video ? video.thumbnails?.[0]?.url : undefined;
return {
@@ -91,11 +51,7 @@ export const getDataByChannelId = async ({ channelId, embed }: { channelId: stri
mime_type: 'text/html',
duration_in_seconds: video.duration && 'seconds' in video.duration ? video.duration.seconds : undefined,
},
{
url: dataUrl,
mime_type: 'text/srt',
title: 'Subtitles',
},
...srtAttachments,
],
};
})