const { randomInt } = require('crypto'); const ytdl = require('ytdl-core'), fs = require('fs'), path = require('path'), express = require('express'), ffmpeg = require('ffmpeg'), bodyParser = require('body-parser') const PORT = process.env.PORT || 8080 const app = express() process.on('uncaughtException', (err, origin) => { fs.writeSync( process.stderr.fd, `Caught exception: ${err}\n` + `Exception origin: ${origin}`, ); }); app.use(bodyParser.urlencoded({ extended: false })) app.get("/download", async (req, res) => { const filename = req.query.filename const url = req.query.url const format = req.query.format const quality = req.query.quality if (!ytdl.validateURL(url)) { res.send("Invalid URL!") return } res.header('Content-Disposition', `attachment; filename="${filename}.${format}"`); var ytpath = path.join(__dirname, 'cached/' + ytdl.getVideoID(url) + String(Math.floor(Math.random() * 100000)) + '.mp4') var vidinfo = await ytdl.getBasicInfo(url) var ytvid = ytdl(url, { 'quality': quality }) .pipe(fs.createWriteStream(ytpath)) .on("close", ()=> { console.log("Downloaded!") var proc = new ffmpeg(ytpath) proc.then(function(video) { video .setVideoDuration(vidinfo.videoDetails.lengthSeconds) .setVideoFormat(format) .save('cached/' + ytdl.getVideoID(url) + String(Math.floor(Math.random() * 100000)) + "Converted." + format,function (err, file) { console.log("Converted!") fs.createReadStream(file).pipe(res) .on("close", () => { console.log("Freed!") fs.unlinkSync(file) if (fs.existsSync(ytpath)) { fs.unlinkSync(ytpath) } }) }) }) }) }); app.use(express.static(path.join(__dirname, 'static'))) app.listen(PORT, function () { console.log("Hosted on port " + PORT) })