|
| 1 | +const fs = require('node:fs'); |
| 2 | +const { paths, toSlug } = require('../content-testing/content'); |
| 3 | + |
| 4 | +// Generates a JSON file that maps YouTube IDs to their challenge or track URL |
| 5 | +// Priority: challenge > canonical track > track |
| 6 | + |
| 7 | +const redirects = {}; |
| 8 | + |
| 9 | +for (const path of paths.challenges) { |
| 10 | + const slug = toSlug.videosAndChallenges(path); |
| 11 | + const video = JSON.parse(fs.readFileSync(path)); |
| 12 | + const parts = video.parts ?? [video]; |
| 13 | + |
| 14 | + parts.forEach((part, i) => { |
| 15 | + const partAnchor = i > 0 ? `#part-${i + 1}` : ''; |
| 16 | + redirects[part.videoId] = `/${slug}${partAnchor}`; |
| 17 | + }); |
| 18 | +} |
| 19 | + |
| 20 | +const slugToVideo = new Map(); |
| 21 | +for (const path of paths.videos) { |
| 22 | + const slug = toSlug.videosAndChallenges(path); |
| 23 | + const video = JSON.parse(fs.readFileSync(path)); |
| 24 | + slugToVideo.set(slug, video); |
| 25 | +} |
| 26 | + |
| 27 | +for (const path of paths.tracks) { |
| 28 | + const trackSlug = toSlug.tracks(path); |
| 29 | + const track = JSON.parse(fs.readFileSync(path)); |
| 30 | + |
| 31 | + const chaptersOrVideos = |
| 32 | + track.videos ?? track.chapters.flatMap((c) => c.videos); |
| 33 | + |
| 34 | + for (const slug of chaptersOrVideos) { |
| 35 | + if (!slugToVideo.has(slug)) continue; |
| 36 | + |
| 37 | + const video = slugToVideo.get(slug); |
| 38 | + const parts = video.parts ?? [video]; |
| 39 | + const isCanonicalTrack = video.canonicalTrack === trackSlug; |
| 40 | + |
| 41 | + parts.forEach((part, i) => { |
| 42 | + if (!redirects[part.videoId] || isCanonicalTrack) { |
| 43 | + const partAnchor = i > 0 ? `#part-${i + 1}` : ''; |
| 44 | + redirects[part.videoId] = `/tracks/${trackSlug}/${slug}${partAnchor}`; |
| 45 | + } |
| 46 | + }); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +fs.writeFileSync( |
| 51 | + 'netlify/edge-functions/yt/redirects.json', |
| 52 | + JSON.stringify(redirects) |
| 53 | +); |
| 54 | + |
| 55 | +console.log( |
| 56 | + `${Object.keys(redirects).length} YouTube redirects were generated.` |
| 57 | +); |
0 commit comments