const https = require("https"); const fs = require("fs"); const path = require("path"); function thumbnailRouteHandler(app) { const cacheDir = path.join(__dirname, "../cache"); if (!fs.existsSync(cacheDir)) { fs.mkdirSync(cacheDir); } setInterval(() => { fs.readdir(cacheDir, (err, files) => { if (err) { console.error("Error reading cache directory:", err); return; } const now = Date.now(); files.forEach(file => { const filePath = path.join(cacheDir, file); fs.stat(filePath, (err, stats) => { if (err) { console.error("Error getting file stats:", err); return; } if (now - stats.mtime.getTime() > 30 * 24 * 60 * 60 * 1000) { fs.unlink(filePath, err => { if (err) console.error("Error deleting cached file:", err); }); } }); }); }); }, 24 * 60 * 60 * 1000); app.get("/api/thumbnail/:videoId", (req, res) => { const videoId = req.params.videoId; const cachePath = path.join(cacheDir, `${videoId}.jpg`); if (fs.existsSync(cachePath)) { return fs.createReadStream(cachePath).pipe(res); } const thumbnailUrl = `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`; https.get(thumbnailUrl, (response) => { if (response.statusCode === 404) { const fallbackUrl = `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`; https.get(fallbackUrl, (fallbackResponse) => { const fileStream = fs.createWriteStream(cachePath); fallbackResponse.pipe(fileStream); fallbackResponse.pipe(res); }).on("error", (err) => { console.error(`Error fetching fallback thumbnail: ${err.message}`); res.status(500).send("Error fetching thumbnail"); }); return; } const fileStream = fs.createWriteStream(cachePath); response.pipe(fileStream); response.pipe(res); }).on("error", (err) => { console.error(`Error fetching thumbnail: ${err.message}`); res.status(500).send("Error fetching thumbnail"); }); }); } module.exports = thumbnailRouteHandler;