backend/utils/ytdlp.js

49 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-03-29 17:48:59 +00:00
const wget = require('wget-improved')
2023-09-30 16:32:32 +01:00
const DOMPurify = require('isomorphic-dompurify')
const metadata = require('./metadata.js')
2024-03-29 17:48:59 +00:00
const hr = require('@tsmx/human-readable')
2023-03-03 16:44:40 +00:00
async function downloadVideo(url, ws, id) {
return new Promise(async (resolve, reject) => {
2024-03-29 17:48:59 +00:00
let quality = '720p'
const video = await metadata.getVideoMetadata(id)
2024-03-29 17:48:59 +00:00
if (video.lengthSeconds > 1200) quality = '480p' // 20 minutes
if (video.lengthSeconds > 2100) quality = '360p' // 35 minutes
const downloadJson = await metadata.getVideoDownload(url, quality)
2024-03-29 17:48:59 +00:00
let size = ''
const alreadyPrecentages = []
2024-03-29 17:53:14 +00:00
const download = wget.download(downloadJson.url, `./videos/${id}.webm`)
2023-03-03 16:44:40 +00:00
2024-03-29 17:48:59 +00:00
download.on('start', fileSize => {
size = fileSize
if (ws) ws.send(`DATA - Download has started in ${quality}`)
2023-03-03 16:44:40 +00:00
})
2024-03-29 17:48:59 +00:00
download.on('progress', progress => {
if (alreadyPrecentages.includes((progress*100).toFixed(0))) return
alreadyPrecentages.push((progress*100).toFixed(0))
2024-03-29 17:48:59 +00:00
if (ws) ws.send(`DATA - [download] ${(progress*100).toFixed(2)}% of ${hr.fromBytes(size)}`)
})
2024-03-29 17:48:59 +00:00
download.on('error', err => {
if (ws) ws.send(`DATA - ${DOMPurify.sanitize(err)}`)
})
2024-03-29 17:48:59 +00:00
download.on('end', output => {
if (output == 'Finished writing to disk') {
ws.send(`DATA - Download has finished`)
resolve({
fail: false
})
} else {
reject({
fail: true
})
}
})
})
}
2023-03-03 16:44:40 +00:00
module.exports = { downloadVideo }