Univerter/index.js
2023-10-23 16:02:13 +00:00

167 lines
5.4 KiB
JavaScript

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()
if (fs.existsSync(path.join(__dirname, 'cached'))) {
fs.rmSync(path.join(__dirname, 'cached'), { recursive: true, force: true})
}
function formatBytes(bytes, decimals = 2) {
if (!+bytes) return '0 Bytes'
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
}
fs.mkdirSync(path.join(__dirname, 'cached'))
const cacheDuration = 15 || process.env.CACHEDUR
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("/getLink", 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.header("Content-Type", "text/html")
res.write(`<link rel="stylesheet" href="/style.css">`)
res.write(`<p>Invalid URL! Check the url for any errors! <br> ${url}</p>`)
return
}
res.setHeader("Content-Type", "text/html");
res.write(`<link rel="stylesheet" href="/style.css">`)
// String(Math.floor(Math.random() * 100000)) +
var ytpath = path.join(__dirname, 'cached/' + ytdl.getVideoID(url) + '.mp4')
var vidinfo = await ytdl.getBasicInfo(url)
res.write(`<p>Beginning download...</p>`)
var lastp = 0
var ytvid = ytdl(url, { 'quality': quality, 'format': 'mp4' })
.on("progress", (data, ctotal, etotal) => {
var integer = 5
var percent = (Math.ceil(ctotal / etotal * 100))
if (percent % integer == 0 && lastp != percent) {
res.write(`<p class="percent" id="percent${percent}">Downloading... ${percent}% (${formatBytes(ctotal)})</p>`)
res.write(`
<style>
#percent${lastp} {
display: none;
}
</style>
`)
lastp = percent
}
})
.pipe(fs.createWriteStream(ytpath))
.on("close", () => {
res.write("<p>Downloaded!</p>")
var proc = new ffmpeg(ytpath)
// res.write(`<p>Converting... (May take a while, <a href="https://github.com/Violets-puragtory/NoJS-YTConverter"> doesn't support progress updates yet</a>)</p>`)
var endpath = ('cached/' + ytdl.getVideoID(url) + String(Math.floor(Math.random() * 100000)) + "Converted." + format)
res.write(`<p>Beginning conversion... Conversion may be slow depending on instance.</p>`)
proc.then(function (video) {
video
.setVideoDuration(vidinfo.videoDetails.lengthSeconds)
.setVideoFormat(format)
.save(endpath, (error, file)=>{
res.write(`<p>Converted! (<a href="https://github.com/damianociarla/node-ffmpeg/issues/33">Why doesn't conversion support %s?</a>)</p>`)
res.write(`
<style>
.cv {
display: none;
}
</style>
`)
res.write(`<p><a href="/download?path=${path.basename(file)}&filename=${filename}.${format}" target="_blank">Link to video download!</a> (Link is deleted after 15 minutes!)</p>`)
setTimeout(()=>{
if (fs.existsSync(ytpath)) {
fs.unlinkSync(ytpath)
}
if (fs.existsSync(file)) {
fs.unlinkSync(file)
}
}, 60 * 1000)
})
})
var count = 0
var integer = 1
var lastc = 0
var percent = 0
async function update() {
if (fs.existsSync(endpath)) {
var ffile = await fs.readFileSync(endpath)
var yt = await fs.readFileSync(ytpath)
percent = (Math.round(ffile.length / yt.length * (100 / integer))) * integer
// console.log(ffile.length)
// if (ffile.length != lastc) {
res.write(`<p class="cv" id="convert${count}">Converting... (${formatBytes(ffile.length)})</p>`)
res.write(`
<style>
#convert${count - 1} {
display: none;
}
</style>
`)
lastc = percent
count += 1
// }
}
if (percent < 100) {
setTimeout(() => {
update()
}, 1500);
}
}
update()
})
});
app.get('/download', (req, res) => {
var file = req.query.path
var filename = req.query.filename
var dest = path.join(__dirname, 'cached/', file)
if (fs.existsSync(dest)) {
res.header('Content-Disposition', `attachment; filename="${filename}"`);
fs.createReadStream(dest).pipe(res)
} else {
res.header("Content-Type", "text/html")
res.write(`<link rel="stylesheet" href="/style.css">`)
res.write(`<p>Uh oh! It seems that video couldn't be found... Maybe the URL expired? Or, the link was invalid. <br>If you believe this was a mistake, please put a issue on <a href="https://github.com/Violets-puragtory/NoJS-YTConverter/">Github</a></p>`, ()=>{
res.end()
})
}
})
app.use(express.static(path.join(__dirname, 'static')))
app.listen(PORT, function () {
console.log("Hosted on port " + PORT)
})