const express = require(‘express’);
const ytdl = require(‘ytdl-core’);
const app = express();
const port = 3000;
// Middleware to serve static files
app.use(express.static(‘public’));
// API to fetch video info + thumbnail
app.get(‘/video-info’, async (req, res) => {
try {
const { id } = req.query;
const info = await ytdl.getInfo(`https://www.youtube.com/watch?v=${id}`);
res.json({
title: info.videoDetails.title,
description: info.videoDetails.shortDescription || ‘No description available’,
duration: parseInt(info.videoDetails.lengthSeconds),
thumbnail: `https://img.youtube.com/vi/${id}/maxresdefault.jpg`
});
} catch (error) {
res.status(500).json({ error: ‘Failed to fetch video info. Invalid URL or private video.’ });
}
});
// Download endpoint (unchanged)
app.get(‘/download’, async (req, res) => {
const { id, quality } = req.query;
const url = `https://www.youtube.com/watch?v=${id}`;
try {
const info = await ytdl.getInfo(url);
let format;
switch (quality) {
case ‘hd’: format = ytdl.chooseFormat(info.formats, { quality: ‘136’ }); break; // 720p
case ‘4k’: format = ytdl.chooseFormat(info.formats, { quality: ‘313’ }); break; // 2160p
default: format = ytdl.chooseFormat(info.formats, { quality: ’18’ }); // 360p
}
res.header(‘Content-Disposition’, `attachment; filename=”${info.videoDetails.title}.mp4″`);
ytdl(url, { format }).pipe(res);
} catch (error) {
res.status(500).send(‘Download failed. Video may be restricted.’);
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});