Univerter/index.js

225 lines
7.2 KiB
JavaScript
Raw Normal View History

const ytdl = require('ytdl-core'),
fs = require('fs'),
path = require('path'),
express = require('express'),
2023-10-18 20:04:42 -05:00
ffmpeg = require('ffmpeg'),
bodyParser = require('body-parser')
2023-05-05 11:15:22 -05:00
const PORT = process.env.PORT || 8080
const app = express()
2023-10-20 18:03:54 -05:00
if (fs.existsSync(path.join(__dirname, 'cached'))) {
2023-10-23 23:31:23 -05:00
fs.rmSync(path.join(__dirname, 'cached'), { recursive: true, force: true })
2023-10-20 18:03:54 -05:00
}
2023-10-25 21:06:45 -05:00
const characters = "abcdefghijklmnopqrstuvwxyz!@$%^*()[]_-=+"
2023-10-25 20:53:18 -05:00
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]}`
}
2023-10-20 18:03:54 -05:00
fs.mkdirSync(path.join(__dirname, 'cached'))
const cacheDuration = 30 || process.env.CACHEDUR
2023-05-05 11:15:22 -05:00
2023-08-24 11:00:33 -05:00
process.on('uncaughtException', (err, origin) => {
fs.writeSync(
process.stderr.fd,
`Caught exception: ${err}\n` +
`Exception origin: ${origin}`,
);
});
2023-08-24 11:00:33 -05:00
app.use(bodyParser.urlencoded({ extended: false }))
2023-10-20 18:03:54 -05:00
app.get("/getLink", async (req, res) => {
2023-05-08 12:52:41 -05:00
const url = req.query.url
2023-05-10 12:36:26 -05:00
const format = req.query.format
2023-05-05 11:15:22 -05:00
const quality = req.query.quality
2023-10-23 23:31:23 -05:00
const redir = req.query.redirect
2023-05-10 12:36:26 -05:00
2023-10-25 22:07:48 -05:00
res.setHeader("X-Accel-Buffering", "no")
2023-08-28 08:33:16 -05:00
if (!ytdl.validateURL(url)) {
2023-10-20 18:03:54 -05:00
res.header("Content-Type", "text/html")
res.write(`<link rel="stylesheet" href="/style.css">`)
2023-10-25 16:04:42 -05:00
res.write(`<p>Invalid URL! Check the url for any errors! <br>URL: ${url}</p>`)
2023-08-24 11:00:33 -05:00
return
}
2023-10-25 18:07:54 -05:00
var vidinfo = await ytdl.getBasicInfo(url)
2023-10-25 20:53:18 -05:00
const ogname = vidinfo.videoDetails.title
var filename = ""
for (let index = 0; index < ogname.length; index++) {
const letter = ogname[index];
if ((characters + characters.toUpperCase()).includes(letter)) {
filename += letter
}
}
2023-10-25 18:07:54 -05:00
if (["mp4", "webm"].includes(format)) {
2023-10-28 22:46:49 -05:00
var ytvid = ytdl(url, { 'quality': quality, 'format': format, 'filter': 'videoandaudio' })
var debounce = false
2023-10-25 16:04:42 -05:00
ytvid.on("progress", (chunk, cd, td) => {
if (!debounce) {
2023-10-28 22:46:49 -05:00
res.setHeader('Content-Disposition', `attachment; filename="${filename}.${format}";`)
res.setHeader('Content-Type', `video/${format}`)
console.log(`${filename}.${format}"`)
2023-10-25 16:04:42 -05:00
res.setHeader("Content-Length", td)
ytvid.pipe(res)
debounce = true
}
})
} else {
if (redir != "redirect") {
res.setHeader("Content-Type", "text/html");
2023-08-24 11:00:33 -05:00
res.write(`<link rel="stylesheet" href="/style.css">`)
2023-10-25 16:04:42 -05:00
res.write(`
<style>
p {
display: block;
}
</style>
`)
}
2023-10-23 23:31:23 -05:00
// String(Math.floor(Math.random() * 100000)) +
var ytpath = path.join(__dirname, 'cached/' + ytdl.getVideoID(url) + '.mp4')
if (redir != "redirect") {
res.write(`<p>Starting download...</p>`)
}
var lastp = 0
if ("mp3 ogg wav".includes(format)) {
var ytvid = ytdl(url, { 'quality': quality, 'format': 'mp4', filter: "audioonly" })
} else {
var ytvid = ytdl(url, { 'quality': quality, 'format': 'mp4', filter: "videoandaudio" })
}
2023-10-18 20:04:42 -05:00
if (redir != "redirect") {
ytvid.on("progress", (data, ctotal, etotal) => {
var integer = 1
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(`
2023-10-20 18:03:54 -05:00
<style>
#percent${lastp} {
display: none;
2023-10-18 20:04:42 -05:00
}
2023-10-20 18:03:54 -05:00
</style>
`)
lastp = percent
}
})
}
ytvid.pipe(fs.createWriteStream(ytpath))
.on("close", () => {
if (redir != "redirect") {
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>`)
2023-10-25 18:07:54 -05:00
var endpath = ('cached/' + ytdl.getVideoID(url) + String(Math.floor(Math.random() * 10000000)) + "Converted." + format)
if (redir != "redirect") {
res.write(`<p>Starting Video Conversion... Conversion may be slow depending on instance.</p>`)
}
proc.then(function (video) {
video
.setVideoDuration(vidinfo.videoDetails.lengthSeconds)
.setVideoFormat(format)
.save(endpath, (error, file) => {
if (redir != "redirect") {
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 ${cacheDuration} minutes!)</p>`)
if (redir == "redirectjs") {
res.write(`
2023-10-23 23:31:23 -05:00
<script>
window.location = "/download?path=${path.basename(file)}&filename=${filename}.${format}"
</script>
`)
}
} else {
res.redirect(`/download?path=${path.basename(file)}&filename=${filename}.${format}`)
2023-10-23 23:31:23 -05:00
}
setTimeout(() => {
if (fs.existsSync(ytpath)) {
fs.unlinkSync(ytpath)
}
if (fs.existsSync(file)) {
fs.unlinkSync(file)
}
}, 60 * 1000)
})
})
var count = 0
2023-10-25 16:04:42 -05:00
async function update() {
if (fs.existsSync(endpath)) {
var ffile = await fs.readFileSync(endpath)
var yt = await fs.readFileSync(ytpath)
res.write(`<p class="cv" id="convert${count}">Converting... (${formatBytes(ffile.length)})</p>`)
res.write(`
2023-10-20 18:03:54 -05:00
<style>
#convert${count - 1} {
2023-10-20 18:03:54 -05:00
display: none;
}
</style>
`)
count += 1
// }
}
2023-10-25 16:04:42 -05:00
if ( redir != "redirect") {
setTimeout(() => {
update()
}, 2000);
}
2023-10-23 23:31:23 -05:00
}
update()
})
}
2023-10-20 18:03:54 -05:00
});
2023-10-20 18:03:54 -05:00
app.get('/download', (req, res) => {
var file = req.query.path
var filename = req.query.filename
var dest = path.join(__dirname, 'cached/', file)
2023-05-05 11:15:22 -05:00
2023-10-20 18:03:54 -05:00
if (fs.existsSync(dest)) {
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-Length', fs.readFileSync(dest).length)
2023-10-20 18:03:54 -05:00
fs.createReadStream(dest).pipe(res)
} else {
res.header("Content-Type", "text/html")
res.write(`<link rel="stylesheet" href="/style.css">`)
2023-10-23 23:31:23 -05:00
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>`, () => {
2023-10-20 18:03:54 -05:00
res.end()
})
}
})
2023-05-05 11:15:22 -05:00
app.use(express.static(path.join(__dirname, 'static')))
2023-05-10 12:36:26 -05:00
app.listen(PORT, function () {
2023-05-05 11:15:22 -05:00
console.log("Hosted on port " + PORT)
})