2024-06-29 12:19:50 +01:00
|
|
|
const WebSocket = require('ws')
|
2024-03-29 14:32:12 +00:00
|
|
|
const metadata = require('./metadata.js')
|
2024-06-29 10:22:55 +01:00
|
|
|
|
2024-03-29 14:32:12 +00:00
|
|
|
async function downloadVideo(url, ws, id) {
|
|
|
|
return new Promise(async (resolve, reject) => {
|
2024-03-30 17:04:00 +00:00
|
|
|
let quality = '720'
|
2024-03-29 14:32:12 +00:00
|
|
|
const video = await metadata.getVideoMetadata(id)
|
2024-03-30 10:11:49 +00:00
|
|
|
if (video.error) {
|
2024-03-30 13:32:37 +00:00
|
|
|
return resolve({
|
2024-03-30 10:11:49 +00:00
|
|
|
message: `Failed to request Youtube with error ${video.error}. Please retry...`,
|
|
|
|
fail: true
|
|
|
|
})
|
|
|
|
}
|
2024-03-30 17:04:00 +00:00
|
|
|
if (video.basic_info.duration >= 900) quality = '360' // 15 minutes
|
2024-03-30 10:11:49 +00:00
|
|
|
|
2024-06-29 12:19:50 +01:00
|
|
|
let isDownloading = true
|
|
|
|
const downloader = new WebSocket(`ws://${process.env.METADATA.replace('http://', '')}/download/${id}/${quality}p`)
|
|
|
|
downloader.on('message', async function message(data) {
|
|
|
|
const text = data.toString()
|
|
|
|
if (text == 'done') {
|
|
|
|
isDownloading = false
|
2024-03-30 13:32:37 +00:00
|
|
|
return resolve({
|
2024-06-29 10:22:55 +01:00
|
|
|
fail: false
|
2024-03-29 14:32:12 +00:00
|
|
|
})
|
2024-06-29 12:19:50 +01:00
|
|
|
} else {
|
|
|
|
ws.send(text)
|
2024-03-29 14:32:12 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2024-06-29 12:19:50 +01:00
|
|
|
downloader.on('close', function close(code, reason) {
|
|
|
|
if (!isDownloading) return
|
2024-06-29 10:22:55 +01:00
|
|
|
|
2024-06-29 12:19:50 +01:00
|
|
|
return resolve({
|
|
|
|
fail: true,
|
|
|
|
message: 'The metadata server unexpectedly closed the websocket. Please try again.'
|
|
|
|
})
|
|
|
|
})
|
|
|
|
})
|
2024-03-29 18:30:04 +00:00
|
|
|
}
|
|
|
|
|
2023-03-03 16:44:40 +00:00
|
|
|
module.exports = { downloadVideo }
|