Add public GET /api/youtube/latest: last 3 channel uploads via RSS with 30-min cache
This commit is contained in:
parent
648446271f
commit
c6aabdcbce
@ -9,6 +9,7 @@ import usersRouter from './routes/users.js';
|
|||||||
import webhooksRouter from './routes/webhooks.js';
|
import webhooksRouter from './routes/webhooks.js';
|
||||||
import authRouter from './routes/auth.js';
|
import authRouter from './routes/auth.js';
|
||||||
import contactRouter from './routes/contact.js';
|
import contactRouter from './routes/contact.js';
|
||||||
|
import youtubeRouter from './routes/youtube.js';
|
||||||
import { ApiResponse } from './utils/helpers.js';
|
import { ApiResponse } from './utils/helpers.js';
|
||||||
import { validateAccessToken, ensureUserExists } from './middleware/auth.js';
|
import { validateAccessToken, ensureUserExists } from './middleware/auth.js';
|
||||||
import { initDatabase, waitForDb } from './db/database.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)',
|
'GET /api/contact/:id': 'Get contact submission (admin only)',
|
||||||
'PUT /api/contact/:id/status': 'Update submission status (admin only)',
|
'PUT /api/contact/:id/status': 'Update submission status (admin only)',
|
||||||
'DELETE /api/contact/:id': 'Delete submission (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/users', usersRouter);
|
||||||
app.use('/api/webhooks', webhooksRouter);
|
app.use('/api/webhooks', webhooksRouter);
|
||||||
app.use('/api/contact', contactRouter);
|
app.use('/api/contact', contactRouter);
|
||||||
|
app.use('/api/youtube', youtubeRouter);
|
||||||
|
|
||||||
// ============================================
|
// ============================================
|
||||||
// Error Handling
|
// Error Handling
|
||||||
|
|||||||
78
src/routes/youtube.js
Normal file
78
src/routes/youtube.js
Normal file
@ -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('<entry>').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>([^<]+)<\/yt:videoId>/)?.[1];
|
||||||
|
const title = entry.match(/<title>([\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;
|
||||||
Loading…
Reference in New Issue
Block a user