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
29 changes: 0 additions & 29 deletions packages/starpod/src/lib/feed-media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ export interface FeedPerson {
}

const HLS_TYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
const FETCH_TIMEOUT_MS = 10_000;

// Attribute names are fixed by this module, never taken from the feed.
const ATTRIBUTE_PATTERNS = {
Expand Down Expand Up @@ -133,31 +132,3 @@ export function extractPeopleByGuid(

return people;
}

/**
* Fetch the feed and extract its videos and people. A failure here must never
* break the build: the site simply falls back to audio-first everywhere, and
* to whoever the guests database names.
*/
export async function fetchFeedExtras(feedUrl: string): Promise<{
videos: Map<string, FeedVideo>;
people: Map<string, Array<FeedPerson>>;
}> {
try {
// A deadline on the whole request, body included: a stalled response
// must not hold up the build, which then falls back to audio.
const response = await fetch(feedUrl, {
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
});
if (!response.ok) {
return { videos: new Map(), people: new Map() };
}
const xml = await response.text();
return {
videos: extractVideosByGuid(xml),
people: extractPeopleByGuid(xml)
};
} catch {
return { videos: new Map(), people: new Map() };
}
}
84 changes: 60 additions & 24 deletions packages/starpod/src/lib/rss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import { htmlToText } from 'html-to-text';
import parseFeed from 'rss-to-json';
import { array, number, object, optional, parse, string, union } from 'valibot';

import { fetchFeedExtras, type FeedPerson, type FeedVideo } from './feed-media';
import {
extractPeopleByGuid,
extractVideosByGuid,
type FeedPerson,
type FeedVideo
} from './feed-media';
import { optimizeImage } from './optimize-episode-image';
import type { StarpodConfig } from '../utils/config';
import { dasherize } from '../utils/dasherize';
Expand All @@ -12,13 +17,56 @@ import { truncate } from '../utils/truncate';
// `exports.default` pointing at the same function, so what the default import
// yields depends on whether the bundler externalized it. Normalize both
// shapes to the parse function.
type ParseFeedFn = (url: string) => Promise<unknown>;
type ParseFeedFn = (
url: string,
config: { adapter: (config: unknown) => Promise<unknown> }
) => Promise<unknown>;
const parseFeedModule: unknown = parseFeed;
const parseRssFeed: ParseFeedFn =
typeof parseFeedModule === 'function'
? (parseFeedModule as ParseFeedFn)
: (parseFeedModule as { parse: ParseFeedFn }).parse;

// Shares one load among every caller in the process, concurrent ones
// included. A failed load is forgotten so the next call tries again.
function once<Args extends Array<unknown>, T>(
load: (...args: Args) => Promise<T>
): (...args: Args) => Promise<T> {
let pending: Promise<T> | undefined;
return (...args) => {
if (!pending) {
pending = load(...args);
pending.catch(() => (pending = undefined));
}
return pending;
};
}

const fetchFeedXml = once(async (url: string) => {
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`[starpod] Fetching the feed ${url} failed: ${response.status}`
);
}
return response.text();
});

// rss-to-json only takes a URL and fetches it with axios; an axios adapter
// hands it the shared feed text instead.
function parseFeedXml(url: string) {
return parseRssFeed(url, {
adapter: async (config) => ({
data: await fetchFeedXml(url),
status: 200,
statusText: 'OK',
headers: {},
config,
request: {}
})
});
}

// Inside Astro (dev, build, vitest) the config comes from the integration's
// virtual module. Standalone scripts (e.g. `db/seed.ts` under tsx) have no
// Vite, so they must pass their config explicitly and the dynamic import is
Expand Down Expand Up @@ -96,29 +144,16 @@ function pickTranscript(
);
}

let showInfoCache: Show | null = null;

export async function getShowInfo(config?: StarpodConfig) {
if (showInfoCache) {
return showInfoCache;
}

const showInfo = (await parseRssFeed(await resolveRssFeed(config))) as Show;
export const getShowInfo = once(async (config?: StarpodConfig) => {
const showInfo = (await parseFeedXml(await resolveRssFeed(config))) as Show;
showInfo.image = (await optimizeImage(showInfo.image, {
height: 640,
width: 640
})) as string;

showInfoCache = showInfo;
return showInfo;
}

let episodesCache: Array<Episode> | null = null;
});

export async function getAllEpisodes(config?: StarpodConfig) {
if (episodesCache) {
return episodesCache;
}
export const getAllEpisodes = once(async (config?: StarpodConfig) => {
let FeedSchema = object({
items: array(
object({
Expand Down Expand Up @@ -147,10 +182,12 @@ export async function getAllEpisodes(config?: StarpodConfig) {
});

const feedUrl = await resolveRssFeed(config);
const [feed, { videos, people }] = await Promise.all([
parseRssFeed(feedUrl) as Promise<Show>,
fetchFeedExtras(feedUrl)
const [feed, xml] = await Promise.all([
parseFeedXml(feedUrl),
fetchFeedXml(feedUrl)
]);
const videos = extractVideosByGuid(xml);
const people = extractPeopleByGuid(xml);
let items = parse(FeedSchema, feed).items;

let episodes: Array<Episode> = await Promise.all(
Expand Down Expand Up @@ -204,6 +241,5 @@ export async function getAllEpisodes(config?: StarpodConfig) {
)
);

episodesCache = episodes;
return episodes;
}
});
69 changes: 69 additions & 0 deletions packages/starpod/src/lib/sponsors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* Each episode's sponsors, for the episode pages. Server-only.
*/
import { count, eq } from 'drizzle-orm';
import { database } from 'virtual:starpod/config';

import { createDb } from '../db';
import { Episode, Sponsor, SponsorForEpisode } from '../db/schema';

export interface EpisodeSponsor {
id: string;
img: string | null;
name: string;
url: string;
}

interface Sponsors {
bySlug: Map<string, Array<EpisodeSponsor>>;
/** How many episodes each sponsor presented. */
presented: Map<string, number>;
}

let sponsors: Promise<Sponsors> | undefined;

/**
* Every episode's sponsors keyed by episode slug, and each sponsor's episode
* count. Empty when the database is off. Gathered once.
*/
export function episodeSponsors(): Promise<Sponsors> {
sponsors ??= (async () => {
if (!database) {
return { bySlug: new Map(), presented: new Map() };
}
const db = createDb(
import.meta.env.ASTRO_DB_REMOTE_URL,
import.meta.env.ASTRO_DB_APP_TOKEN
);
const [rows, counts] = await Promise.all([
db
.select({
slug: SponsorForEpisode.episodeSlug,
id: Sponsor.id,
img: Sponsor.img,
name: Sponsor.name,
url: Sponsor.url
})
.from(SponsorForEpisode)
.innerJoin(
Episode,
eq(SponsorForEpisode.episodeSlug, Episode.episodeSlug)
)
.innerJoin(Sponsor, eq(SponsorForEpisode.sponsorId, Sponsor.id))
.orderBy(SponsorForEpisode.episodeSlug, SponsorForEpisode.sponsorId),
db
.select({ id: SponsorForEpisode.sponsorId, episodes: count() })
.from(SponsorForEpisode)
.groupBy(SponsorForEpisode.sponsorId)
]);
const bySlug = new Map<string, Array<EpisodeSponsor>>();
for (const { slug, ...sponsor } of rows) {
bySlug.set(slug, [...(bySlug.get(slug) ?? []), sponsor]);
}
return {
bySlug,
presented: new Map(counts.map((row) => [row.id, row.episodes]))
};
})();
return sponsors;
}
52 changes: 4 additions & 48 deletions packages/starpod/src/pages/[episode].astro
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
---
import { getEntry, render } from 'astro:content';
import { count, eq, inArray } from 'drizzle-orm';

import { createDb } from '../db';
import { Episode as DbEpisode, Sponsor, SponsorForEpisode } from '../db/schema';

import { Schema } from 'astro-seo-schema';

import BarPlay from '../components/episode/BarPlay';
Expand All @@ -19,7 +14,7 @@ import ShowNotes from '../components/episode/ShowNotes';
import UFOIllustration from '../components/illustrations/UFOIllustration.astro';
import { generateDocumentLinkTag } from '@bryanguffey/astro-standard-site';

import starpodConfig, { database } from 'virtual:starpod/config';
import starpodConfig from 'virtual:starpod/config';

import Layout from '../layouts/Layout.astro';
import '../styles/episode.css';
Expand All @@ -28,6 +23,7 @@ import { getEpisodeCues } from '../lib/episode-cues';
import { optimizeImage } from '../lib/optimize-episode-image';
import { faceOf, peopleBySlug } from '../lib/people';
import { getAllEpisodes, getShowInfo, type Episode } from '../lib/rss';
import { episodeSponsors } from '../lib/sponsors';
import {
getRssTranscriptParagraphs,
type TranscriptParagraph
Expand Down Expand Up @@ -113,35 +109,12 @@ const playerEpisode = toPlayable(episode, show);

const canonicalURL = new URL(`/${episode.episodeSlug}`, Astro.url);

// The guests/sponsors database is opt-in via the integration's `database`
// option; without it the page renders with those sections absent.
const db = database
? createDb(
import.meta.env.ASTRO_DB_REMOTE_URL,
import.meta.env.ASTRO_DB_APP_TOKEN
)
: null;

// Its hosts and guests: the database's, else the feed's (src/lib/people.ts).
const castBySlug = await peopleBySlug();
const hostsAndGuests = castBySlug.get(episode.episodeSlug) ?? [];

const sponsors = !db
? []
: await db
.select({
id: Sponsor.id,
img: Sponsor.img,
name: Sponsor.name,
url: Sponsor.url
})
.from(SponsorForEpisode)
.innerJoin(
DbEpisode,
eq(SponsorForEpisode.episodeSlug, DbEpisode.episodeSlug)
)
.innerJoin(Sponsor, eq(SponsorForEpisode.sponsorId, Sponsor.id))
.where(eq(DbEpisode.episodeSlug, episode.episodeSlug));
const { bySlug: sponsorsBySlug, presented } = await episodeSponsors();
const sponsors = sponsorsBySlug.get(episode.episodeSlug) ?? [];

const title = `${episode.title} - ${show.title} - Episode ${episode.episodeNumber}`;

Expand All @@ -160,23 +133,6 @@ const episodesOf = (personId: string) =>
.filter((item): item is Episode => Boolean(item))
.sort((a, b) => b.published - a.published);

const presented = new Map(
!db || !sponsors.length
? []
: (
await db
.select({ id: SponsorForEpisode.sponsorId, episodes: count() })
.from(SponsorForEpisode)
.where(
inArray(
SponsorForEpisode.sponsorId,
sponsors.map((sponsor) => sponsor.id)
)
)
.groupBy(SponsorForEpisode.sponsorId)
).map((row) => [row.id, row.episodes])
);

const numberOf = (item: Episode) =>
item.episodeNumber === 'Bonus' ? 'Bonus' : `Ep ${item.episodeNumber}`;
const card = async (item: Episode, reason?: string, face?: string) => ({
Expand Down
Loading
Loading