diff --git a/extension/src/pages/youtube-page.ts b/extension/src/pages/youtube-page.ts index c6980172..447680d6 100644 --- a/extension/src/pages/youtube-page.ts +++ b/extension/src/pages/youtube-page.ts @@ -1,6 +1,8 @@ import { VideoData } from '@project/common'; import { trackFromDef } from './util'; +const TLANG = 'ja'; + declare global { interface Window { trustedTypes?: any; @@ -37,6 +39,29 @@ const adaptYtTrack = (track: any) => { }); }; +const appendTranslatedTracks = (tracks: any, tlang: string) => { + const translatedTracks = [...tracks]; + + for (const track of tracks) { + // Ignore subtitles that are already in the target language + if (track.languageCode !== tlang) { + const translatedTrack = { + ...track, + name: { + simpleText: `${track.name?.simpleText} >> ${tlang}`, + runs: track.name?.runs?.map((run: any) => ({ ...run, text: `${run.text} >> ${tlang}` })), + }, + languageCode: tlang, + baseUrl: `${track.baseUrl}&tlang=${tlang}`, // YouTube API param for translation + }; + + translatedTracks.push(translatedTrack); + } + } + + return translatedTracks; +}; + document.addEventListener( 'asbplayer-get-synced-data', async () => { @@ -89,9 +114,10 @@ document.addEventListener( } response.basename = playerContext.videoDetails?.title || document.title; - response.subtitles = (playerContext?.captions?.playerCaptionsTracklistRenderer?.captionTracks || []).map( - adaptYtTrack - ); + response.subtitles = appendTranslatedTracks( + playerContext?.captions?.playerCaptionsTracklistRenderer?.captionTracks || [], + TLANG + ).map(adaptYtTrack); } catch (error) { if (error instanceof Error) { response.error = error.message; @@ -137,7 +163,7 @@ JSON.parse = function () { if (typeof tracks === 'object' && Array.isArray(tracks) && typeof value?.videoDetails?.videoId === 'string') { const videoId = value.videoDetails.videoId; - const subtitles = tracks.map(adaptYtTrack); + const subtitles = appendTranslatedTracks(tracks, TLANG).map(adaptYtTrack); const basename = value.videoDetails?.title || document.title; dataByVideoId[videoId] = { subtitles,