Univerter 3.0 !!!

This commit is contained in:
Bingus_Violet 2023-11-20 14:39:04 -06:00
parent 700a19bfd6
commit f9da622fbf
4 changed files with 262 additions and 201 deletions

227
index.js
View file

@ -2,32 +2,19 @@ const ytdl = require('ytdl-core'),
fs = require('fs'),
path = require('path'),
express = require('express'),
ffmpeg = require('ffmpeg'),
bodyParser = require('body-parser')
bodyParser = require('body-parser'),
cp = require("child_process"),
ffmpeg = require('ffmpeg-static')
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 })
var formats = {
"matroska": "mkv"
}
const characters = "abcdefghijklmnopqrstuvwxyz!@$%^*()[]_-=+"
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 = 30 || process.env.CACHEDUR
const characters = "abcdefghijklmnopqrstuvwxyz!@$%^*()[]_-=+ "
process.on('uncaughtException', (err, origin) => {
fs.writeSync(
@ -39,11 +26,11 @@ process.on('uncaughtException', (err, origin) => {
app.use(bodyParser.urlencoded({ extended: false }))
app.get("/getLink", async (req, res) => {
app.get("/download", async (req, res) => {
const url = req.query.url
const format = req.query.format
const quality = req.query.quality
const redir = req.query.redirect
const defin = req.query.definition
res.setHeader("X-Accel-Buffering", "no")
@ -64,158 +51,68 @@ app.get("/getLink", async (req, res) => {
if ((characters + characters.toUpperCase()).includes(letter)) {
filename += letter
}
}
if (["mp4", "webm"].includes(format)) {
var ytvid = ytdl(url, { 'quality': quality, 'format': format, 'filter': 'videoandaudio' })
var debounce = false
ytvid.on("progress", (chunk, cd, td) => {
if (!debounce) {
res.setHeader('Content-Disposition', `attachment; filename="${filename}.${format}";`)
res.setHeader('Content-Type', `video/${format}`)
console.log(`${filename}.${format}"`)
res.setHeader("Content-Length", td)
ytvid.pipe(res)
debounce = true
}
if (format in ["mp3", "ogg", "wav"]) {
var audio = ytdl(url, { filter: 'audioonly', quality: quality })
audio.pipe(res)
} else if (defin == "hd") {
var video = ytdl(url, { filter: 'videoonly', quality: quality })
var audio = ytdl(url, { filter: 'audioonly', highWaterMark: 1<<25 })
const ffmpegProcess = cp.spawn(ffmpeg, [
'-i', `pipe:3`,
'-i', `pipe:4`,
'-map','0:v',
'-map','1:a',
'-c:v', 'copy',
'-c:a', 'libmp3lame',
'-crf','27',
'-preset','veryfast',
'-movflags','frag_keyframe+empty_moov',
'-f', format,
'-loglevel','error',
'-'
], {
stdio: [
'pipe', 'pipe', 'pipe', 'pipe', 'pipe',
],
})
video.pipe(ffmpegProcess.stdio[3])
audio.pipe(ffmpegProcess.stdio[4])
res.setHeader('Content-Disposition', `attachment; filename="${filename}.${formats[format] || format}"`);
ffmpegProcess.stdio[1].pipe(res)
} else {
if (redir != "redirect") {
res.setHeader("Content-Type", "text/html");
var video = ytdl(url, { filter: 'videoandaudio', quality: quality })
res.write(`<link rel="stylesheet" href="/style.css">`)
res.write(`
<style>
p {
display: block;
}
</style>
`)
}
const ffmpegProcess = cp.spawn(ffmpeg, [
'-i', `pipe:3`,
'-c:v', 'copy',
'-c:a', 'libmp3lame',
'-crf','27',
'-preset','veryfast',
'-movflags','frag_keyframe+empty_moov',
'-f', format,
'-loglevel','error',
'-'
], {
stdio: [
'pipe', 'pipe', 'pipe', 'pipe', 'pipe',
],
})
video.pipe(ffmpegProcess.stdio[3])
// String(Math.floor(Math.random() * 100000)) +
var ytpath = path.join(__dirname, 'cached/' + ytdl.getVideoID(url) + '.mp4')
res.setHeader('Content-Disposition', `attachment; filename="${filename}.${formats[format] || format}"`);
// res.setHeader('Content-Length', fs.readFileSync(dest).length)
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" })
}
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(`
<style>
#percent${lastp} {
display: none;
}
</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>`)
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(`
<script>
window.location = "/download?path=${path.basename(file)}&filename=${filename}.${format}"
</script>
`)
}
} else {
res.redirect(`/download?path=${path.basename(file)}&filename=${filename}.${format}`)
}
setTimeout(() => {
if (fs.existsSync(ytpath)) {
fs.unlinkSync(ytpath)
}
if (fs.existsSync(file)) {
fs.unlinkSync(file)
}
}, 60 * 1000)
})
})
var count = 0
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(`
<style>
#convert${count - 1} {
display: none;
}
</style>
`)
count += 1
// }
}
if ( redir != "redirect") {
setTimeout(() => {
update()
}, 2000);
}
}
update()
})
ffmpegProcess.stdio[1].pipe(res)
}
});
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.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-Length', fs.readFileSync(dest).length)
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')))