forked from obvtiger/repiped
55 lines
1.6 KiB
JavaScript
55 lines
1.6 KiB
JavaScript
const https = require("https");
|
|
|
|
function trendingRouteHandler(app) {
|
|
let cachedData = null;
|
|
let cacheTimestamp = null;
|
|
const CACHE_DURATION = 10 * 60 * 1000;
|
|
|
|
app.get("/api/trending", (req, res) => {
|
|
if (cachedData && cacheTimestamp && Date.now() - cacheTimestamp < CACHE_DURATION) {
|
|
return res.json(cachedData);
|
|
}
|
|
|
|
https.get("https://pipedapi.wireway.ch/trending?region=US", (response) => {
|
|
let data = "";
|
|
|
|
response.on("data", (chunk) => {
|
|
data += chunk;
|
|
});
|
|
|
|
response.on("end", () => {
|
|
try {
|
|
const jsonData = JSON.parse(data);
|
|
|
|
jsonData.forEach(item => {
|
|
if (item.url && item.url.startsWith("/watch?v=")) {
|
|
const videoId = item.url.replace("/watch?v=", "");
|
|
item.thumbnail = `/api/thumbnail/${videoId}`;
|
|
}
|
|
});
|
|
|
|
cachedData = jsonData;
|
|
cacheTimestamp = Date.now();
|
|
|
|
res.json(jsonData);
|
|
} catch (err) {
|
|
console.error(`Error parsing trending data: ${err.message}`);
|
|
if (cachedData) {
|
|
cacheTimestamp = Date.now();
|
|
return res.json(cachedData);
|
|
}
|
|
res.status(500).send("Error processing trending data");
|
|
}
|
|
});
|
|
}).on("error", (err) => {
|
|
console.error(`Error fetching trending data: ${err.message}`);
|
|
if (cachedData) {
|
|
cacheTimestamp = Date.now();
|
|
return res.json(cachedData);
|
|
}
|
|
res.status(500).send("Error fetching trending data");
|
|
});
|
|
});
|
|
}
|
|
|
|
module.exports = trendingRouteHandler;
|