Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion web/src/features/home/HomeHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
54 changes: 51 additions & 3 deletions web/src/features/home/latestUpload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `<script>var ytInitialData = {"contentId":"v7AFSKcOvSE","contentType":"LOCKUP_CONTENT_TYPE_VIDEO"};</script>`;
const watchPage = (channel = "UCyEAWx-xBlI-uP2RkqaG43A") =>
`<script>var ytInitialPlayerResponse = ${JSON.stringify({
videoDetails: {
videoId: "v7AFSKcOvSE",
channelId: channel,
title: "bhop_test in 1:15 by A & B",
viewCount: "1749",
shortDescription: "Player: A & B\nMap: bhop_test\nTime: 1:15.784",
},
microformat: {
playerMicroformatRenderer: { publishDate: "2026-11-08T14:21:09-08:00" },
},
})};</script>`;

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();
});
91 changes: 80 additions & 11 deletions web/src/features/home/latestUpload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]*?)</${tag}>`))?.[1];
if (!value) return undefined;
Expand Down Expand Up @@ -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)
Expand All @@ -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, {
Expand Down