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 = 15 * 60 * 1000; // refresh from YouTube every 15 min (matches YouTube RSS own max-age=900) // 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;