backend/utils/ytdlp.js

78 lines
2.4 KiB
JavaScript
Raw Normal View History

2023-03-03 16:44:40 +00:00
const child_process = require('child_process')
2023-09-30 16:32:32 +01:00
const DOMPurify = require('isomorphic-dompurify')
const metadata = require('./metadata.js')
2023-03-03 16:44:40 +00:00
async function downloadVideo(url, ws, id) {
return new Promise(async (resolve, reject) => {
const args = ['--proxy', 'socks5://gluetun:1080', url]
const video = await metadata.getVideoMetadata(id)
if (video.lengthSeconds > 1500) {
const formats = await getFormats(url, ws)
2024-03-29 14:48:15 +00:00
if (!formats.fail && formats.includes('360p')) {
args.push('-f 18')
}
}
const child = child_process.spawn('../yt-dlp', args, {cwd: 'videos', shell: false})
2023-10-04 14:20:59 +01:00
// https://github.com/yt-dlp/yt-dlp/blob/cc8d8441524ec3442d7c0d3f8f33f15b66aa06f3/README.md?plain=1#L1500
2023-03-03 16:44:40 +00:00
child.stdout.on("data", data => {
const msg = data.toString().trim()
if (!msg) return
2023-09-30 16:32:32 +01:00
if (ws) ws.send(`DATA - ${DOMPurify.sanitize(msg)}`)
})
child.stderr.on("data", data => {
const msg = data.toString().trim()
if (!msg) return
if (ws) ws.send(`DATA - ${DOMPurify.sanitize(msg)}`)
2023-03-03 16:44:40 +00:00
})
child.on("close", async (code, signal) => {
2024-03-09 08:14:35 +00:00
if (code == 2 || code == 1) { // https://github.com/yt-dlp/yt-dlp/issues/4262
2023-03-03 16:44:40 +00:00
reject({
2024-02-15 18:04:57 +00:00
fail: true
2023-03-03 16:44:40 +00:00
})
} else {
resolve({
2024-02-15 18:04:57 +00:00
fail: false
2023-03-03 16:44:40 +00:00
})
}
})
})
}
async function getFormats(url, ws) {
return new Promise((resolve, reject) => {
2024-03-29 14:39:52 +00:00
const child = child_process.spawn('../yt-dlp', ['--proxy', 'socks5://gluetun:1080', url, '-F'], {cwd: 'videos', shell: false})
let outputs = ''
child.stdout.on("data", data => {
const msg = data.toString().trim()
if (!msg) return
outputs = outputs + msg
})
child.stderr.on("data", data => {
const msg = data.toString().trim()
if (!msg) return
if (ws) ws.send(`DATA - ${DOMPurify.sanitize(msg)}`)
})
child.on("close", async (code, signal) => {
if (code == 2 || code == 1) { // https://github.com/yt-dlp/yt-dlp/issues/4262
reject({
fail: true
})
} else {
resolve(outputs)
}
})
})
}
2023-03-03 16:44:40 +00:00
module.exports = { downloadVideo }