Files
crosscode-platform/apps/website/backend/src/site/youtube.ts
T
joshuaandClaude Opus 5.5 a3ac3da5a5 Website 1.4.0: nightly database backups and background jobs
As Accounts and Cross Events: a gzipped pg_dump every night (02:20) into
backend/backups/, the same website-*.sql.gz files crosscode makes before
updates, with Admin -> Backups (back up now, download, how many to keep).
The heartbeat, event feed and YouTube move from plain timers onto pg-boss
with the backup, and Admin -> Background jobs switches each on or off,
changes its schedule or runs it now. The heartbeat now reports the newest
backup (before: always none, so the Hub warned) and the real job state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:47:30 +02:00

102 lines
4.9 KiB
TypeScript

/**
* Messages from YouTube, automatically (WEBSITE-1.0-PLAN §7, decision 7): the church's channel or a
* playlist, read from YouTube's public feed (no API key) every hour. Each new video becomes a
* message, live at once (decision 9); admins add the speaker, series and passage afterwards, or hide
* one. A video already here (by its id, however it came in) is never added twice.
*/
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
export type YoutubeSource = { kind: 'channel' | 'playlist'; id: string };
/** A channel id (UC…), a channel or playlist address, or a playlist id (PL…, UU…, OL…). */
export function parseSource(input: string): YoutubeSource | null {
const v = input.trim();
const channel = /(?:^|\/channel\/)(UC[\w-]{22})(?:[/?#]|$)/.exec(v);
if (channel) return { kind: 'channel', id: channel[1]! };
const list = /[?&]list=([\w-]{10,64})/.exec(v) ?? /^((?:PL|UU|OL|FL)[\w-]{10,62})$/.exec(v);
if (list) return { kind: 'playlist', id: list[1]! };
return null;
}
export const feedUrl = (s: YoutubeSource) => `https://www.youtube.com/feeds/videos.xml?${s.kind === 'channel' ? 'channel_id' : 'playlist_id'}=${encodeURIComponent(s.id)}`;
export type FeedVideo = { videoId: string; title: string; published: Date; thumbnail: string | null };
const unescape = (s: string) => s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;|&apos;/g, "'").replace(/&amp;/g, '&');
/** The videos in a YouTube Atom feed. Entries without an id, title or date are left out. */
export function parseFeed(xml: string): FeedVideo[] {
const out: FeedVideo[] = [];
for (const m of xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)) {
const e = m[1]!;
const videoId = /<yt:videoId>([\w-]{6,20})<\/yt:videoId>/.exec(e)?.[1];
const title = /<title>([\s\S]*?)<\/title>/.exec(e)?.[1];
const published = /<published>([^<]+)<\/published>/.exec(e)?.[1];
const thumbnail = /<media:thumbnail url="([^"]+)"/.exec(e)?.[1] ?? null;
const date = published ? new Date(published) : null;
if (!videoId || !title || !date || Number.isNaN(date.getTime())) continue;
out.push({ videoId, title: unescape(title.trim()).slice(0, 500), published: date, thumbnail: thumbnail && thumbnail.startsWith('https://') ? thumbnail : null });
}
return out;
}
export async function getSource(ctx: Ctx): Promise<YoutubeSource | null> {
return ctx.settings.json<YoutubeSource | null>('youtube_source', null);
}
export async function setSource(ctx: Ctx, input: string | null): Promise<YoutubeSource | null> {
if (!input?.trim()) {
await ctx.settings.set('youtube_source', null);
return null;
}
const s = parseSource(input);
if (!s) throw new ApiError(400, 'VALIDATION', 'That isn\'t a YouTube channel id (UC…) or playlist address.', { youtube: 'A channel id (UC…) or a playlist link' });
await ctx.settings.set('youtube_source', JSON.stringify(s));
return s;
}
const slugify = (s: string) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'message';
export async function uniqueSlug(ctx: Ctx, title: string, model: 'message' | 'simpleEvent', except?: string) {
const base = slugify(title);
for (let n = 1; ; n++) {
const slug = n === 1 ? base : `${base}-${n}`;
const taken = model === 'message'
? await ctx.db.message.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } })
: await ctx.db.simpleEvent.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } });
if (!taken) return slug;
}
}
type Fetcher = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>;
/** The hourly job: new videos become messages. Returns how many were added. */
export async function syncYoutube(ctx: Ctx, fetcher: Fetcher = (u) => fetch(u, { signal: AbortSignal.timeout(15000), headers: { accept: 'application/atom+xml' } })) {
const source = await getSource(ctx);
if (!source) return { added: 0, skipped: 'no source' };
let videos: FeedVideo[];
try {
const res = await fetcher(feedUrl(source));
if (!res.ok) throw new Error(`YouTube answered ${res.status}`);
videos = parseFeed(await res.text());
} catch (e) {
await ctx.settings.set('youtube_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 300));
return { added: 0, error: (e as Error).message };
}
let added = 0;
for (const v of videos) {
if (await ctx.db.message.findUnique({ where: { externalId: v.videoId } })) continue;
await ctx.db.message.create({
data: {
slug: await uniqueSlug(ctx, v.title, 'message'), title: v.title, date: v.published, source: 'youtube_feed',
mediaUrl: `https://www.youtube.com/watch?v=${v.videoId}`, externalId: v.videoId, thumbnailUrl: v.thumbnail, publishedAt: ctx.now(),
},
});
added++;
}
await ctx.settings.setMany({ youtube_last_sync_at: ctx.now().toISOString(), youtube_last_error: null });
return { added };
}