Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function (err, info) {
// Emit info about download
self.emit("started", {
info: info
});
if (parseInt(info.length_seconds) > MAX_LENGTH) {
callback(`Video is too long, max seconds is ${MAX_LENGTH}`, resultObj);
} else {
// Stream setup
var stream = ytdl.downloadFromInfo(info, {
quality: self.youtubeVideoQuality,
requestOptions: self.requestOptions
});
stream.on("response", function (httpResponse) {
// Setup of progress module
var str = progress({
length: parseInt(
httpResponse.headers["content-length"]
),
time: self.progressTimeout
});
// Add progress event listener
str.on("progress", function (progress) {
if (progress.percentage === 100) {
ytdl.getInfo(url, (err, info) => {
if (err) return reject(err);
// Prefer opus
const format = info.formats.find(filter);
const canDemux = format && info.length_seconds != 0;
if (canDemux) options = { ...options, filter };
else if (info.length_seconds != 0) options = { ...options, filter: 'audioonly' };
if (canDemux) {
const demuxer = new prism.opus.WebmDemuxer();
return resolve(ytdl.downloadFromInfo(info, options).pipe(demuxer).on('end', () => demuxer.destroy()));
} else {
const transcoder = new prism.FFmpeg({
args: [
'-reconnect', '1',
'-reconnect_streamed', '1',
'-reconnect_delay_max', '5',
'-i', nextBestFormat(info.formats).url,
'-analyzeduration', '0',
'-loglevel', '0',
'-f', 's16le',
'-ar', '48000',
'-ac', '2',
],
});
const opus = new prism.opus.Encoder({ rate: 48000, channels: 2, frameSize: 960 });
const stream = transcoder.pipe(opus);
ytdl.getInfo(youtubeMetadata.link, infoOptions, function(err, info) {
if (err) {
log.error('YTDownload', JSON.stringify(err));
reject(err.message);
}
var downloadOptions = {
quality: 'highestaudio',
requestOptions: { maxRedirects: 5 },
format: ytdl.filterFormats(info.formats, 'audioonly')[0]
}
// Setup stream
var stream = ytdl.downloadFromInfo(info, downloadOptions);
stream.on("response", function(httpResponse) {
// TODO: Add event emitter to share progress with caller
// Build progress var
var str = progress({
length: parseInt(httpResponse.headers["content-length"], 10),
time: 1000
});
// Stream progress listener
str.on("progress", function(progress) {
callback(progress)
});
// Start encoding
return new Promise((resolve, reject) => {
let downloadLen
ytdl.downloadFromInfo(info, this._downloadOptions)
.on('progress', (chunk, downloaded, total) => {
if (!downloadLen) {
this.emit('downloadLength', downloadLen = total)
}
this.emit('downloadProgress', chunk, downloaded, total)
})
.pipe(fs.createWriteStream(file))
.once('finish', resolve)
.once('error', reject)
})
}
} catch (e) {
return message.edit(message.__('song_not_found')).catch(() => {});
}
if (!info) return message.edit(message.__('song_not_found')).catch(() => {});
if (info.livestream) return message.edit(message.__('livestream')).catch(() => {});
if (info.length_seconds > 1200) return message.edit(message.__('too_long', { minutes: 20 })).catch(() => {});
message.edit(message.__('downloading_with_time', { seconds: Math.round((info.length_seconds / 24).toFixed(1)) * 10 })).catch(() => {});
let title = info.title;
let ytdlStream;
try {
ytdlStream = ytdl.downloadFromInfo(info, { quality: 'highestaudio' });
} catch (e) {
client.errorLog('Error retrieving ytdl stream in mp3', e.stack, e.code);
return message.edit(message.__('song_not_found')).catch(() => {});
}
finish(ytdlStream, title, info.length_seconds, message, client, info.thumbnail_url, `https://youtu.be/${id}`).catch((e) => {
client.errorLog('Error finishing mp3 from YT source', e.stack, e.code);
return message.edit(message.__('song_not_found')).catch(() => {});
});
}
if (videoTitle.indexOf("-") > -1) {
const temp = videoTitle.split("-");
if (temp.length >= 2) {
artist = temp[0].trim();
title = temp[1].trim();
}
} else {
title = videoTitle;
}
if (info.author && info.author.name) {
artist = info.author.name;
}
//Stream setup
const stream = ytdl.downloadFromInfo(info, {
quality: self.youtubeVideoQuality,
requestOptions: self.requestOptions
});
stream.on("response", function(httpResponse) {
//Setup of progress module
const str = progress({
length: parseInt(httpResponse.headers["content-length"]),
time: self.progressTimeout
});
//Add progress event listener
str.on("progress", function(progress) {
if (progress.percentage === 100) {
resultObj.stats = {
transferredBytes: progress.transferred,
ytdl.getInfo(`http://www.youtube.com/watch?v=${videoId}`, { quality: 'highestaudio' }, function(err, info) {
var stream = ytdl.downloadFromInfo(info, {
quality: 'highestaudio'
})
ffmpeg(stream)
.audioBitrate(info.formats[0].audioBitrate)
.withAudioCodec("libmp3lame")
.toFormat("mp3")
.saveToFile(`mp3/${videoId}.mp3`)
.on("error", function(err) {
console.log('error', err)
res.json(err)
})
.on("end", function() {
next()
})
})
function(info, next){
var source = {};
source.id = info.video_id;
if(manifest.sources[source.id]){
return next({error: 'already_downloaded', message: 'Video already downloaded!'});
}
source.tmpPath = config.tmpPath+'/'+source.id;
source.title = info.title;
source.length = +info.length_seconds;
source.dateDownloaded = new Date().toISOString();
var formats = info.formats.filter(function(f){ return f.type.match(/audio\/webm/) ? true:false; });
if(formats.length){ info.formats = [formats[0]]; }
log.info("Downloading source file ["+source.title+"] ...");
var video = ytdl.downloadFromInfo(info, {filter: 'audioonly'});
video.pipe(fs.createWriteStream(source.tmpPath));
video.on('error', next);
video.on('format', function(format){
source.size = +format.size;
source.path = config.sourcesPath+'/'+source.id+'.'+format.container;
var pos = 0;
video.on('data', function(data) {
pos += data.length;
if (source.size) {
var percent = (pos / source.size * 100).toFixed(2);
process.stdout.cursorTo(0);
process.stdout.clearLine(1);
process.stdout.write(percent + '%');
ytdl.getInfo(videoUrl, { quality: self.youtubeVideoQuality }, function(err, info) {
if (err) callback(err, null);
//Stream setup
var stream = ytdl.downloadFromInfo(info, {
quality: self.youtubeVideoQuality,
requestOptions: self.requestOptions
});
stream.on("response", function(httpResponse) {
//Setup of progress module
var str = progress({
length: parseInt(httpResponse.headers["content-length"]),
time: self.progressTimeout
});
//Add progress event listener
str.on("progress", function(progress) {
if (progress.percentage === 100) {
resultObj.stats= {
fs.stat(fname, (err) => {
if (err) {
const stream = ytdl.downloadFromInfo(info, downloadOptions);
stream.pipe(fs.createWriteStream(fname));
stream.on('end', () => resolve(fname));
stream.on('abort', () => reject('An error has ocurred while downloading video'));
} else {
resolve(fname);
}
});
});