cyb3r-downloader/controller/youtube-dl.js
Theenoro 2ee2072dca 1.1.0
added a fully functional playlist function
2017-08-07 23:27:50 +02:00

94 lines
2.6 KiB
JavaScript

const { spawn } = require('child_process');
const ipcMain = require('electron').ipcMain;
console.log(global.dir);
var orig_path = "";
var path = "";
ipcMain
.on('start-download', (event, arg)=>{
path = orig_path
var download = new yt_dl(arg.url,arg.id);
download.addListen(event)
download.download();
})
.on('start-download-pl', (event, arg)=>{
var mkdirp = require('mkdirp');
if(orig_path === ""){
path = '.'
}else{
path = orig_path
}
mkdirp(path+'/'+arg.folder, function(err) {
path = path+'/'+arg.folder;
// path exists unless there was an error
var download = new yt_dl(arg.url,arg.id);
download.addListen(event)
download.download();
});
})
ipcMain.on('setPath', function(event, arg) {
path = arg.path;
orig_path = arg.path;
console.log('SET Path: '+path)
});
var yt_dl = class{
constructor(url,id){
this.url = url ;
this.percent = 0;
this.lwrite = null;
this.id = id;
}
addListen(e){
this.lwrite = e
}
status(stat){
this.lwrite('download-progress', stat);
}
download(){
var log = [];
var me = this;
var ls;
if(path == ''){
ls = spawn(global.dir+'/lib/youtube-dl', ['-x','--audio-format','mp3','-i',this.url]);
}else{
ls = spawn(global.dir+'/lib/youtube-dl', ['-x','--audio-format','mp3','-i',this.url,'-o',path+'/%(title)s.%(ext)s']);
}
ls.stdout.on('data', (data) => {
data = data.toString('utf8');
log.push(data);
//console.log(data);
try{
var z = data.replace(/(\r\n|\n|\r)/gm,"").split(' ');
console.log(z)
switch (z[0]) {
case '[download]':
var percent = data.split(']')[1].split('of')[0];
//console.log(z)
me.percent = percent.trim();
me.lwrite.sender.send('download-progress',{percent :me.percent,id:me.id});
break;
default:
}
}catch(e){
console.log(e);
}finally{
}
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
me.lwrite.sender.send('file',{id:me.id,file:log[log.length-2].split('[ffmpeg] Destination: ')[1]});
me.lwrite.sender.send('process-fin',{percent :me.percent,id:me.id});
});
}
}
module.exports = yt_dl;