| |
| import express from "express"; |
| import bodyParser from "body-parser"; |
| import { ytmp4 } from "ruhend-scraper"; |
| import yts from "youtube-yts"; |
| import axios from "axios"; |
|
|
| const app = express(); |
| const PORT = 7860; |
| const HOST = "0.0.0.0"; |
|
|
| |
| app.use(bodyParser.json()); |
|
|
| |
| const isUrl = (input) => { |
| try { |
| new URL(input); |
| return true; |
| } catch { |
| return false; |
| } |
| }; |
|
|
| |
| 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; |
| } |
| }; |
|
|
| |
| app.get("/download", async (req, res) => { |
| const { input } = req.query; |
|
|
| if (!input) { |
| return res |
| .status(400) |
| .json({ error: "'input' query parameter must be provided." }); |
| } |
|
|
| try { |
| let videoData; |
|
|
| if (isUrl(input)) { |
| |
| videoData = await ytmp4(input); |
| } else { |
| |
| 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); |
| } |
|
|
| |
| const videoSize = await getVideoSize(videoData.video); |
|
|
| |
| 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", |
| }); |
| } 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}`); |
| }); |
|
|