ytdl / server.js
Akane710's picture
Update server.js
f3ff21d verified
// Import required modules
import express from "express";
import bodyParser from "body-parser";
import { ytmp4 } from "ruhend-scraper";
import yts from "youtube-yts";
import axios from "axios"; // Add axios for making HTTP requests
const app = express();
const PORT = 7860;
const HOST = "0.0.0.0";
// Middleware
app.use(bodyParser.json());
// Function to check if input is a URL
const isUrl = (input) => {
try {
new URL(input);
return true;
} catch {
return false;
}
};
// Function to get the size of a video file from its URL
const getVideoSize = async (url) => {
try {
const response = await axios.head(url);
const contentLength = response.headers["content-length"];
return contentLength ? parseInt(contentLength, 10) : null;
} catch (error) {
console.error("Failed to fetch video size:", error.message);
return null;
}
};
// GET endpoint for downloading YouTube videos
app.get("/download", async (req, res) => {
const { input } = req.query; // Extract single input parameter
if (!input) {
return res
.status(400)
.json({ error: "'input' query parameter must be provided." });
}
try {
let videoData;
if (isUrl(input)) {
// Input is a URL
videoData = await ytmp4(input);
} else {
// Input is a query, perform YouTube search
const searchResults = await yts(input);
if (!searchResults.videos || searchResults.videos.length === 0) {
return res.status(404).json({ error: "No videos found for the query." });
}
const firstResult = searchResults.videos[0];
videoData = await ytmp4(firstResult.url);
}
// Get video size
const videoSize = await getVideoSize(videoData.video);
// Respond with video details
const { title, video, author, description, duration, views, upload, thumbnail } = videoData;
res.json({
title,
videoUrl: video,
author,
description,
duration,
views,
uploadDate: upload,
thumbnail,
size: videoSize ? `${(videoSize / 1048576).toFixed(2)} MB` : "Unknown", // Convert bytes to MB
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to process the request." });
}
});
app.listen(PORT, HOST, () => {
console.log(`Running on http://${HOST}:${PORT}`);
});