From c6aabdcbcebdef6bdcd2a2f02ee7810228a65110 Mon Sep 17 00:00:00 2001 From: Z User Date: Wed, 4 Nov 2026 18:54:39 +0000 Subject: [PATCH] Add public GET /api/youtube/latest: last 3 channel uploads via RSS with 30-min cache --- src/index.js | 5 +++ src/routes/youtube.js | 78 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 src/routes/youtube.js diff --git a/src/index.js b/src/index.js index d3f3feb..10b92cb 100644 --- a/src/index.js +++ b/src/index.js @@ -9,6 +9,7 @@ import usersRouter from './routes/users.js'; import webhooksRouter from './routes/webhooks.js'; import authRouter from './routes/auth.js'; import contactRouter from './routes/contact.js'; +import youtubeRouter from './routes/youtube.js'; import { ApiResponse } from './utils/helpers.js'; import { validateAccessToken, ensureUserExists } from './middleware/auth.js'; import { initDatabase, waitForDb } from './db/database.js'; @@ -112,6 +113,9 @@ app.get('/api', (req, res) => { 'GET /api/contact/:id': 'Get contact submission (admin only)', 'PUT /api/contact/:id/status': 'Update submission status (admin only)', 'DELETE /api/contact/:id': 'Delete submission (admin only)' + }, + youtube: { + 'GET /api/youtube/latest': 'Last 3 public uploads from the Moxiegen YouTube channel (public)' } } })); @@ -135,6 +139,7 @@ app.get('/api/logout', (req, res) => res.redirect('/api/auth/logout')); app.use('/api/users', usersRouter); app.use('/api/webhooks', webhooksRouter); app.use('/api/contact', contactRouter); +app.use('/api/youtube', youtubeRouter); // ============================================ // Error Handling diff --git a/src/routes/youtube.js b/src/routes/youtube.js new file mode 100644 index 0000000..cd3d982 --- /dev/null +++ b/src/routes/youtube.js @@ -0,0 +1,78 @@ +import express from 'express'; +import { ApiResponse, asyncHandler } from '../utils/helpers.js'; + +const router = express.Router(); + +// Moxiegen YouTube channel (@RobertAbbott-v7o) +const CHANNEL_ID = 'UCG_ZDOP21i0Ah26FxiuZmkg'; +const RSS_URL = `https://www.youtube.com/feeds/videos.xml?channel_id=${CHANNEL_ID}`; +const MAX_VIDEOS = 3; +const CACHE_TTL_MS = 30 * 60 * 1000; // refresh from YouTube every 30 minutes + +// In-memory cache (also serves stale data if YouTube is unreachable) +let cache = { videos: null, fetchedAt: 0 }; + +const decodeEntities = (s) => + String(s) + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/'/g, "'"); + +function parseFeed(xml) { + const entries = xml.split('').slice(1); // chunk 0 is the feed header (channel title lives there) + const videos = []; + for (const entry of entries) { + const id = entry.match(/([^<]+)<\/yt:videoId>/)?.[1]; + const title = entry.match(/([\s\S]*?)<\/title>/)?.[1]; + const published = entry.match(/<published>([^<]+)<\/published>/)?.[1]; + if (!id || !title) continue; + videos.push({ + id, + title: decodeEntities(title.trim()), + published: published || null, + url: `https://www.youtube.com/watch?v=${id}`, + thumbnail: `https://i.ytimg.com/vi/${id}/hqdefault.jpg` + }); + if (videos.length >= MAX_VIDEOS) break; + } + return videos; +} + +async function fetchLatestVideos() { + if (cache.videos && Date.now() - cache.fetchedAt < CACHE_TTL_MS) { + return { videos: cache.videos, stale: false }; + } + const res = await fetch(RSS_URL, { + headers: { 'User-Agent': 'Mozilla/5.0 (compatible; MoxiegenSite/1.0)' }, + signal: AbortSignal.timeout(10000) + }); + if (!res.ok) throw new Error(`YouTube RSS responded ${res.status}`); + const xml = await res.text(); + const videos = parseFeed(xml); + if (!videos.length) throw new Error('No videos parsed from feed'); + cache = { videos, fetchedAt: Date.now() }; + return { videos, stale: false }; +} + +// GET /api/youtube/latest — last 3 public uploads (public, no auth) +router.get( + '/latest', + asyncHandler(async (req, res) => { + try { + const { videos, stale } = await fetchLatestVideos(); + res.json(ApiResponse(true, { channelId: CHANNEL_ID, videos, stale })); + } catch (err) { + if (cache.videos) { + // Upstream hiccup — serve the stale cached list rather than an error + return res.json(ApiResponse(true, { channelId: CHANNEL_ID, videos: cache.videos, stale: true })); + } + console.warn('[youtube] feed fetch failed:', err.message); + res.status(502).json(ApiResponse(false, null, 'Unable to load videos right now')); + } + }) +); + +export default router;