diff --git a/web/src/features/home/HomeHeader.tsx b/web/src/features/home/HomeHeader.tsx index 7fc85a0..79a28ef 100644 --- a/web/src/features/home/HomeHeader.tsx +++ b/web/src/features/home/HomeHeader.tsx @@ -10,7 +10,7 @@ const views = new Intl.NumberFormat("en", { }); export async function HomeHeader() { - const upload = await latestUpload().catch(() => null); + const upload = await latestUpload(); const hasRun = upload?.map && upload.player && upload.time; return ( diff --git a/web/src/features/home/latestUpload.test.ts b/web/src/features/home/latestUpload.test.ts index 3f2394c..2b60b9c 100644 --- a/web/src/features/home/latestUpload.test.ts +++ b/web/src/features/home/latestUpload.test.ts @@ -61,15 +61,63 @@ it("uses a standard thumbnail when a high-resolution version is unavailable", as .mockResolvedValueOnce(new Response(null, { status: 404 })); vi.stubGlobal("fetch", fetch); const upload = await latestUpload(); - expect(upload.thumbnail).toBe( + expect(upload!.thumbnail).toBe( "https://i.ytimg.com/vi/v7AFSKcOvSE/hqdefault.jpg", ); }); -it("surfaces feed failures so the component can show its channel fallback", async () => { +const channelPage = ``; +const watchPage = (channel = "UCyEAWx-xBlI-uP2RkqaG43A") => + ``; + +it("reads the latest channel upload when YouTube's feed returns 404", async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce(new Response(null, { status: 404 })) + .mockResolvedValueOnce(new Response(channelPage)) + .mockResolvedValueOnce(new Response(watchPage())) + .mockResolvedValueOnce(new Response(null)); + vi.stubGlobal("fetch", fetch); + const upload = await latestUpload(); + expect(upload).toMatchObject({ + id: "v7AFSKcOvSE", + player: "A & B", + time: "1:15.784", + views: 1749, + publishedAt: "2026-11-08T14:21:09-08:00", + }); + expect(fetch.mock.calls[2]![0]).toBe( + "https://www.youtube.com/watch?v=v7AFSKcOvSE", + ); +}); + +it("rejects a channel-page video that belongs to another channel", async () => { + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(new Response(null, { status: 404 })) + .mockResolvedValueOnce(new Response(channelPage)) + .mockResolvedValueOnce(new Response(watchPage("another-channel"))), + ); + expect(await latestUpload()).toBeNull(); +}); + +it("gives no upload when YouTube is unavailable, so a prerender never fails on it", async () => { vi.stubGlobal( "fetch", vi.fn().mockResolvedValue(new Response(null, { status: 503 })), ); - await expect(latestUpload()).rejects.toThrow("503"); + expect(await latestUpload()).toBeNull(); }); diff --git a/web/src/features/home/latestUpload.ts b/web/src/features/home/latestUpload.ts index 03163de..9c748a8 100644 --- a/web/src/features/home/latestUpload.ts +++ b/web/src/features/home/latestUpload.ts @@ -4,6 +4,14 @@ import { formatSince } from "../runs/time"; export const youtubeChannel = "https://www.youtube.com/@SourceJump"; const channelId = "UCyEAWx-xBlI-uP2RkqaG43A"; +function runDetails(description: string) { + return { + map: description.match(/^Map:\s*(.+)$/m)?.[1]?.trim(), + player: description.match(/^Player:\s*(.+)$/m)?.[1]?.trim(), + time: description.match(/^Time:\s*(\d+(?::\d{2}){0,2}\.\d{3})\s*$/m)?.[1], + }; +} + function text(xml: string, tag: string): string | undefined { const value = xml.match(new RegExp(`<${tag}>([\\s\\S]*?)`))?.[1]; if (!value) return undefined; @@ -53,11 +61,7 @@ export function parseUploadFeed(xml: string) { title, publishedAt, views: views === undefined ? undefined : Number(views), - map: description.match(/^Map:\s*(.+)$/m)?.[1]?.trim(), - player: description.match(/^Player:\s*(.+)$/m)?.[1]?.trim(), - time: description.match( - /^Time:\s*(\d+(?::\d{2}){0,2}\.\d{3})\s*$/m, - )?.[1], + ...runDetails(description), }; }) .filter((upload) => upload !== null) @@ -69,12 +73,77 @@ export function parseUploadFeed(xml: string) { export async function latestUpload() { "use cache"; cacheLife({ stale: 300, revalidate: 900, expire: 86400 }); - const response = await fetch( - `https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, - { signal: AbortSignal.timeout(8000) }, - ); - if (!response.ok) throw new Error(`YouTube feed returned ${response.status}`); - const upload = parseUploadFeed(await response.text()); + // An error thrown here while the homepage is prerendered fails the whole build, so a YouTube outage yields no upload instead. + try { + return await findLatestUpload(); + } catch { + return null; + } +} + +async function findLatestUpload() { + const signal = AbortSignal.timeout(8000); + let upload; + try { + const response = await fetch( + `https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, + { signal }, + ); + if (!response.ok) + throw new Error(`YouTube feed returned ${response.status}`); + upload = parseUploadFeed(await response.text()); + } catch { + // YouTube's public feed can return 404 while the channel and videos remain available. + const channel = await fetch(`${youtubeChannel}/videos`, { signal }); + if (!channel.ok) + throw new Error(`YouTube channel returned ${channel.status}`); + const html = await channel.text(); + const id = + html.match( + /"contentId":"([\w-]{11})","contentType":"LOCKUP_CONTENT_TYPE_VIDEO"/, + )?.[1] ?? html.match(/"videoRenderer":\{"videoId":"([\w-]{11})"/)?.[1]; + if (!id) throw new Error("YouTube channel contains no upload"); + const watch = await fetch(`https://www.youtube.com/watch?v=${id}`, { + signal, + }); + if (!watch.ok) throw new Error(`YouTube video returned ${watch.status}`); + const player = (await watch.text()).match( + /var ytInitialPlayerResponse = (.*?);<\/script>/, + )?.[1]; + if (!player) throw new Error("YouTube video details are unavailable"); + const data = JSON.parse(player) as { + videoDetails?: { + videoId: string; + channelId: string; + title: string; + viewCount?: string; + shortDescription?: string; + }; + microformat?: { playerMicroformatRenderer?: { publishDate?: string } }; + }; + const details = data.videoDetails; + const publishedAt = + data.microformat?.playerMicroformatRenderer?.publishDate; + if ( + details?.channelId !== channelId || + details.videoId !== id || + typeof details.title !== "string" || + !details.title || + !publishedAt || + !Number.isFinite(Date.parse(publishedAt)) + ) + throw new Error("YouTube upload details are invalid"); + upload = { + id, + title: details.title, + publishedAt, + views: + details.viewCount && /^\d+$/.test(details.viewCount) + ? Number(details.viewCount) + : undefined, + ...runDetails(details.shortDescription ?? ""), + }; + } const highResolution = `https://i.ytimg.com/vi/${upload.id}/maxresdefault.jpg`; // Some uploads have no maximum-resolution thumbnail; keep the standard version available. const image = await fetch(highResolution, {