/** * 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(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'|'/g, "'").replace(/&/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(/([\s\S]*?)<\/entry>/g)) { const e = m[1]!; const videoId = /([\w-]{6,20})<\/yt:videoId>/.exec(e)?.[1]; const 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 }; } /** Every hour while the site runs (pg-boss comes with the other jobs). */ export function startYoutubeSync(ctx: Ctx): () => void { if (!ctx.config.jobsEnabled) return () => {}; const run = () => syncYoutube(ctx).catch((e) => console.warn('[youtube]', (e as Error).message)); const first = setTimeout(run, 30_000); const timer = setInterval(run, 60 * 60 * 1000); first.unref?.(); timer.unref?.(); return () => { clearTimeout(first); clearInterval(timer); }; }