New YT mp3&mp4 download 2020

Control q to save yt and control b to reset list of yt's saved.

As of 2020-11-02. See the latest version.

// ==UserScript==
// @name         New YT mp3&mp4 download 2020
// @namespace    http://tampermonkey.net/
// @version      0.15
// @description  Control q to save yt and control b to reset list of yt's saved.
// @author       You
// @match        *://www.youtube.com/*
// @match        *://www.y2mate.com/*
// @match        *://lp.powerapp.download/*
// @match        https://www.y2mate.com/en19
// @match        https://www.y2mate.com/en49
// @match        *://*.lp.powerapp.download/*
// @match        *://*.fiefionfortes.casa/*
// @match        *://*.inservinea.com/*
// @match        *://*.protection.byguardio.com/*
// @match        *://*.tortsv.gq/*
// @match        *://*.takefr.cf/*
// @match        *://*.toomiplay.com/*
// @match        *://*.deej.almeusciu.site/*
// @match        *://*.upgradecircle.findgreatsourceforupgrade.info/*
// @match        *://*.afew.zoyufo.pw/*
// @match        *://*.upgradebestmaintenancetheclicks.icu/*
// @match        *://*.s3.amazonaws.com/*
// @match        *://*.updatemostrenewedapplication.best/*
// @match        *://*.get.anyconvertersearch.com/*
// @match        *://*.digitaltrends.com/*
// @match        *://*.wildbearads.com/*/
// @grant        none
// ==/UserScript==
//removed ad redirects
`
// @require       https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js
// @require       http://code.jquery.com/jquery-1.11.0.min.js
`

findid=function (id,a=document.body){
    var res=[];
    var b=id;
    function part2(e){
        if(e.id.includes(b)){
            res.push(e);
            if(e.children.length){
                e=e.children;
                e.forEach=[].forEach;
                e.forEach(e2=>{
                    part2(e2);
                })
            }
        }else{
            if(e.children.length){
                e=e.children;
                e.forEach=[].forEach;
                e.forEach(e2=>{
                    part2(e2);
                })
            }
        }
    };
    part2(a);
    return res
}
window.getElementByAttribute=function getElementByAttribute(label,item='aria-label',doc=document.body){
    var res=[];
    function part2(e){
        if(e.getAttribute(item)==label){
            res.push(e);
        }else{
            if(e.children.length){
                e=e.children;
                e.forEach=[].forEach;
                e.forEach(e2=>{
                    part2(e2);
                })
            }
        }
    };
    part2(doc);
    return res.length==1?res[0]:res||false;
}
window.get_aria_label=function (label,doc=document.body){
    var res=[];
    function part2(e){
        if(e.getAttribute('aria-label')==label){
            res.push(e);
        }else{
            if(e.children.length){
                e=e.children;
                e.forEach=[].forEach;
                e.forEach(e2=>{
                    part2(e2);
                })
            }
        }
    };
    part2(doc);
    return res[0]||false;
}
setElement = function(url) {
    return (String(url).match(/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/)&&String(url).match(/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/)[7].length==11)? String(url).match(/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/)[7]: false;
};
a=null,b=null,c=null,d=null,e=null,f=null,g=null,h=null,i=null,j=null,k=null,l=null,m=null,n=null,o=null,p=null,q=null,r=null,s=null,u=null,v=null,w=null,x=null,y=null,z=null,aa=null,bb=null,cc=null,dd=null,ee=true,gg=true,hh=null,jj=null,kk=null,ll=null,mm=null,oo=false,pp=false,qq=null,rr=null,ss=null,tt=true,uu=null,vv=null,ww=null,xx=null,zz=null,a1=null,b1=null,ii=0,kko=null;
track=[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,u,v,w,x,y,z,aa,bb,cc,dd,ee,gg,hh,jj,kk,ll,mm,oo,pp,qq,rr,ss,tt,uu,vv,ww,xx,zz,a1,b1]
this.win1=null
this.win2=null
this.win3=null
this.win4=null
hh=function(item,val){localStorage.setItem(item,val)};
jj=function(item){return localStorage.getItem(item)};
dd=function (names) {let unique = {};names.forEach(function(i) {if(!unique[i]) {unique[i] = true;}});return Object.keys(unique);};
if(window.location.href.includes('youtube')&&!window.location.href.includes('y2mate')){
    ss=eval(jj('download'))
    uu=jj('yts')
    if(ss==null||ss==undefined){
        hh('download','false');
        ss=eval(jj('download'));
    }
    kk=null;id=function(id){return document.getElementById(id)}
    b1 =document.URL;
    function hscontrolls(){
        var is=[ww.style.display=='',vv.style.display=='']
        if(is[0]){ww.style.display='block'}
        if(is[1]){vv.style.display='block'};
        toggled(ww);
        toggled(vv);
    };
    function download(a,b,c){
        stuff=eval('container[3]').innerText.split('\n');
        this.tofix=[['yts',''],['download','false'],['mute','false'],['next',false]]
        title=stuff[0]
        type=stuff[1]
        views=stuff[2]
        likes={
            likes:stuff[3]*1,
            dislikes:stuff[4]*1,
            total:(stuff[3]*1)+(stuff[4]*1),};
        fix2(stuff[0],false);
        go2=eval(jj(stuff[0]));
        var newname=Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
        if(window.opener){
            eval(`${newname}=open2(a,b,c);
${newname}.onload=function(e){console.log('done');setTimeout(function(){if(window.opener){window.close()};},1000)}
window.close();
`);
            hh(stuff[0],true)
        }
        else if(!go){
            try{open2(a,b,c)}catch(err){hh(stuff[0],true)};
        }
    }
    ta=document.getElementsByTagName('*')
    var allEqual = (arr,a) => arr.every( v => {return v === a} );
    var allEqual2 = (arr) => arr.every( v => v === arr[0] );
    ta.list=function(id,classname,tag){
        var res=[];
        var put={};
        var array=[];
        todo=document.getElementsByTagName(tag);
        todo.forEach=[].forEach;
        todo.forEach(e=>{
            array=[];
            if(typeof id=='string'){
                put.i=id==e.id;
            }else{put.i=true}
            if(typeof classname=='string'){
                put.c=classname==e.className;
            }else{put.c=true}
            array=[put.c,put.i];
            array=allEqual(array,true);
            if(array){res.push(e);}
        })
        return res;
    };
    topen=[];
    setInterval(function(){if(document.getElementsByClassName('ytp-ad-skip-button ytp-button').length==1){document.getElementsByClassName('ytp-ad-skip-button ytp-button')[0].click();;console.log('Skipped ad')}},0)
    // ad skipping ^^
    function check2(){
        index=eval(location.href.split('&')[2])
        var it=[];
        if(window.location.href.includes('playlist')){
            titles=ta.list('video-title',undefined,'span');
            links=ta.list(undefined,'yt-simple-endpoint style-scope ytd-playlist-video-renderer','a');
            for(let i=0;i<link.length;i++){
                cand=eval(localStorage.getItem(titles[i].innerText));
                console.log(cand)
            };
            for(let i=0;i<links.length;i++){
                cand=eval(localStorage.getItem(titles[i].innerText));
                cand2=eval(localStorage.getItem(links[i].innerText));
                if(!cand||!cand2){
                    localStorage.setItem(titles[i].innerText,true);
                    topen.push({
                        URL:links[i].href.split('&')[0]
                    })
                }
            }
            looping=null;
            clearInterval(looping);
            looping=setInterval(opening,1000);;
            if(ta.list('text-displayed',undefined,'yt-formatted-string')[0].innerText.split(' ')[1]=='MP3'||ta.list('text-displayed',undefined,'yt-formatted-string')[0].innerText.split(' ')[1]=='MP4'&&ta.list('text-displayed',undefined,'yt-formatted-string')[0].innerText.split(' ')[0]=='DOWNLOAD'){}else{clearInterval(looping)}
        };'y2mate.com/en48/'
        if(window.opener){n=document.URL.split('&');o=n[0];p=n[1];q=n[2];vid=setElement(o);download('https://y2mate.com/en48/#id="'+vid+'"&type=mp3',Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15),`width:${window.innerWidth},height=${window.innerHeight}`)};
    }
    function opening(){
        type=ta.list('text-displayed',undefined,'yt-formatted-string')[0].innerText.split(' ')[1]
        if(ii<topen.length){
            if (!kko) {
                "'myWindow' has never been opened!";
                kko=open('https://y2mate.com/en48/#isopen=true&url="'+topen[ii].URL+'"&type="'+type.toLowerCase(),type+'"',`width:${window.innerWidth},height=${window.innerHeight}`);
                localStorage.setItem(topen[ii].URL,true);
                ii++
            }
            else {
                if (kko.closed) {
                    kk=open('https://y2mate.com/en48/#isopen=true&url="'+topen[ii].URL+'"&type='+type.toLowerCase(),type,`width:${window.innerWidth},height=${window.innerHeight}`);
                    localStorage.setItem(topen[ii].URL,true);
                    ii++
                    "'myWindow' has been closed!";
                } else {
                    "'myWindow' has not been closed!";
                    console.log('win1')
                }
            }
        };
    };
    function mute(){document.getElementsByClassName('ytp-mute-button ytp-button')[0].click()};
    mute.desc='Mutes current video';
    function saveyt(){cc=ta.list('container','style-scope ytd-channel-name','div')[0].innerText;bb=localStorage.getItem('yts').split(',');bb.push(cc);bb=dd(bb);localStorage.setItem('yts',bb)};
    saveyt.desc=''
    function deletelist(){localStorage.setItem('yts','')};
    function toggle(){var item=eval(jj('download'));hh('download',!item);console.log()};
    function pause(){tp=document.getElementsByClassName('ytp-play-button ytp-button ytp-play-button-playlist')[0]?document.getElementsByClassName('ytp-play-button ytp-button ytp-play-button-playlist')[0].click():document.getElementsByClassName('ytp-play-button ytp-button')[0].click()};
    function next(){document.getElementsByClassName('ytp-next-button ytp-button')[0].click();};
    function prev(){document.getElementsByClassName('ytp-prev-button ytp-button')[0].click();};
    function full(){document.getElementsByClassName('ytp-fullscreen-button ytp-button')[0].click();};
    fullscreen=full;
    function toggled(e){var is=[e.style.display=='none',e.style.display=='block'];console.log(is);if(is[0]){e.style.display='block'};if(is[1]){e.style.display='none'};};
    tasks=[
        {function:hscontrolls,canAuto:false},
        {function:mute,canAuto:true},
        {function:saveyt,canAuto:true},
        {function:deletelist,canAuto:false},
        {function:toggle,canAuto:false},
        {function:pause,canAuto:true},
        {function:next,canAuto:true},
        {function:prev,canAuto:false},
        {function:fullscreen,canAuto:true},
        {function:download,cnaAuto:true},
    ]
    function ch2(i){
        console.log(!i?false:!i.closed?true:false,1)
        if(!i){
            return false
        }else{
            if(!i.closed){
                return true
            }else{
                return false
            }
        }
    }
    function open2(a,b,c){
        var iswinopen=false;
        this['w1']=ch2(win1);
        this['w2']=ch2(win2);
        this['w3']=ch2(win3);
        this['w4']=ch2(win4);
        if(!this['w1']&&!iswinopen){this.win1=open(a,b,c);iswinopen=true;console.log(1);return true}else
            if(!this['w2']&&!iswinopen){this.win2=open(a,b,c);iswinopen=true;console.log(2);return true}else
                if(!this['w3']&&!iswinopen){this.win3=open(a,b,c);iswinopen=true;console.log(3);return true}else
                    if(!this['w4']&&!iswinopen){this.win4=open(a,b,c);iswinopen=true;console.log(4);return true}else{
                        return false}
    };
    function controll(key,e,fn){
        console.log(e.code,"Key"+key,e.ctrlKey);var is=e.code=="Key"+key&&e.ctrlKey;if(fn&&is){fn(is);}else{return is}}
    dd=function (names) {let unique = {};names.forEach(function(i) {if(!unique[i]) {unique[i] = true;}});return Object.keys(unique);};
    function keys(obj,name){
        var key=Object.keys(obj);var r=`{`;var t=[];var k;key.forEach=[].forEach;key.forEach(e=>{try{k=eval(name+'.'+e);console.log([k.length,e,`${name}.${e}`,!k.toString().includes('[native code]')]);if(k.length&&!k.toString().includes('[native code]')){t.push(`${e}:${k}`)}}catch(e){}});r+=t+`}`;return r}
    hh=function(item,val){localStorage.setItem(item,val)};
    jj=function(item){return localStorage.getItem(item)};
    function check(){
        class Element{
            constructor(tag,id,classname){
                var e
                if(tag){e=document.createElement(tag);}else{return}
                e.classname=classname
                if(id){e.id=id};
                return e;
            }
        };
        stuff=eval('container[3]').innerText.split('\n');
        this.tofix=[['yts',''],['download','false'],['mute','false'],['next',false]]
        title=stuff[0]
        type=stuff[1]
        views=stuff[2]
        likes={
            likes:stuff[3]*1,
            dislikes:stuff[4]*1,
            total:(stuff[3]*1)+(stuff[4]*1),};
        z=function(a,b){
            try{a.append(b);return true}catch(x){console.log(x);return false}};
        n=document.URL.split('&');o=n[0];p=n[1];q=n[2];y=true;
        var stpb;!id('savetoplaylist')&&(stpb=new Element('button','savetoplaylist'),stpb.style.backgroundColor='red',stpb.style.color='white',stpb.innerText='Save channel',id('meta-contents').children[0].children[0].children[1].append(stpb));!!id('savetoplaylist')&&(stpb=id('savetoplaylist'));stpb.onclick=setupsave;stpb.style.height='20px'
        var s=new Element('button','download');s.style.backgroundColor='red';s.style.color='white';s.innerText='Download song [MP3]';s.onclick=function(){n=document.URL.split('&');o=n[0];p=n[1];q=n[2];vid=setElement(o);open2('https://y2mate.com/en48/#id="'+vid+'"&type="mp3"',Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15),`width:${window.innerWidth},height=${window.innerHeight}`);};
        var s2=new Element('button','download2');s2.style.backgroundColor='red';s2.style.color='white';s2.innerText='Download video [MP4]';s2.onclick=function(){n=document.URL.split('&');o=n[0];p=n[1];q=n[2];vid=setElement(o);open2('https://y2mate.com/en48/#id="'+vid+'"&type="mp4"',Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15),`width:${window.innerWidth},height=${window.innerHeight}`);};
        var r=document.getElementById('download');
        var r2=document.getElementById('download2');
        if(!r){z(document.getElementById('container'),s)}else{s=r;};
        if(!r){z(document.getElementById('container'),s2)}else{s2=r2};
        u=localStorage.getItem('yts').split(',');
        w=ta.list('container','style-scope ytd-channel-name','div')[0].innerText
        function THIS_is_WIP(t,d){document.getElementsByClassName('ytp-chrome-controls')[0].style.display='none';document.getElementsByClassName('ytp-progress-bar-container')[0].style.display='none';}
        ww=document.getElementsByClassName('ytp-chrome-controls')[0];
        vv=document.getElementsByClassName('ytp-progress-bar-container')[0];
        ss=eval(ss);
        if(ss){}
        u.forEach(v=>{
            if(v==w&&y&&ss){s.click();y=false;}
            setTimeout(function(){if(window.opener){window.close()};},1000)
        });
    };
    function fix2(item,val){
        localStorage.getItem(item)?localStorage.getItem(item):localStorage.setItem(item,val);
        return localStorage.getItem(item)
    };
    setInterval(function(){
        a1 =document.URL;
        if(a1!==b1){
            b1=a1;setTimeout(function(){listener(b1);},3e3)
        }
    },0);
    if(typeof tt==undefined){tt=false}
    document.addEventListener('keydown',function(e){
        if(tt){if(controll('Q',e)){saveyt();tt=false}}
        if(tt){if(controll('B',e)){deletelist();tt=false}}
        if(tt){if(controll('X',e)){toggle();tt=false}}
    })
    document.addEventListener('keyup',function(e){
        if(!tt){tt=!tt}
    });
    testtimer=1600
    function save(playlist=localStorage.getItem('LP'),make=true,again=true){
        if(eval(get(video_data.id)))return;;
        if(!window.location.href.includes('watch')||playlist==undefined)return;
        var found=false;
        var it
        var exist=true
        getElementByAttribute('Save to playlist').click()
        setTimeout(function(){document.getElementsByClassName('style-scope ytd-compact-link-renderer').forEach=[].forEach;
                              var list=findid('playlists')[0].children;
                              list.forEach=[].forEach
                              list.forEach(e=>{
                                  var text=e.innerText.split(`









`)[1]?e.innerText.split(`









`)[0].split(`




`)[1]:e.innerText;text==playlist?(e.getElementsByClassName('style-scope paper-checkbox')[0].click(),found=true,exist=true):text.toLowerCase().includes(playlist)?found=true:exist=false;;
                              });
                              getElementByAttribute('Save to playlist').click()
                              hh('LP',playlist);
                              if(found)(console.log('found'),(function(){try{console.countReset()}catch(err){}})());else (console.warn('did','not','find',playlist),console.count());
                              setTimeout(function(){
                                  if(window.btext.includes('Added to')){
                                      if(eval(get(video_data.id)))(console.log('setting save'),get(video_data.id,true))
                                      console.log('already saved');window.btext='';
                                  }else console.warn('not',window.btext,window.btext.includes('Added to'),'trying again',save(playlist));
                              },testtimer)
                             },200)
        if (found)return;
    }
    window.btext=='Added to'
    window.ontextchange=function(e){window.btext=e;console.log(e)}
    var oldtext=''
    var newtext='';
    setInterval(function(){
        try{newtext=getElementByAttribute('','allow-click-through')[1].children[0].innerText
            if(oldtext!=newtext)window.ontextchange(newtext)}catch(err){};
        oldtext=newtext;
    },100);
    var urlt='https://www.y2mate.com/en24/'
    get=function(e,v=undefined){return v==undefined?localStorage.getItem(e):localStorage.setItem(e,v);}
    window.autosave=function (){
        console.log('found video to save')
        channel=[]
        var itemss=document.getElementsByTagName('*');
        itemss.forEach=[].forEach;
        itemss.forEach(e=>{
            (e.id.includes('channel-name')&&(channel.push(e)))
        });
        channel[0];
        channel=channel[0]
        channel_name=channel.innerText
        eval('autosave')&&(!!get(channel_name)&&(save(get(channel_name))))
    }
    function setupsave(){
        console.log('Saving channel')
        getElementByAttribute('Save to playlist').click();
        setTimeout(function(){
            channel=[];
            var itemss=document.getElementsByTagName('*');
            itemss.forEach=[].forEach;
            itemss.forEach(e=>{
                (e.id.includes('channel-name')&&(channel.push(e)))
            });
            channel[0];
            channel=channel[0]
            channel_name=channel.innerText
            try{
                var playl=findid('playlists')[0].innerText.split('Watch later')[1];
                if(findid('playlists')[0].innerText.split('Watch later')[1].includes('      ')){
                    getElementByAttribute('Save to playlist').click()
                    setTimeout(setupsave,200)
                    return
                }
                (getElementByAttribute('Save to playlist').click(),cp=prompt('which playlist do u want to save '+video_data.uploader+' to'+playl,''),cp!=""&&(save(cp)),get(video_data.uploader,cp))
            }catch(e){console.error(e);return setTimeout(setupsave,200)}
        },500)
    }
    function x50(){
        if(!location.href.includes('list')){
            document.getElementsByClassName('style-scope ytd-thumbnail').forEach=[].forEach;
            document.getElementsByClassName('style-scope ytd-thumbnail').forEach(e=>{
                var is3=location.href.includes('watch')?location.href.includes('watch'):
                location.href.includes('embed')?location.href.includes('embed'):false
                if(e.innerText=='50+'&&!document.URL.includes('list')&&is3){e.click()
                                                                           }
            })
        }
    }
    function listener(e){
        check2();
        channel=[]
        chan=[]
        var itemss=document.getElementsByTagName('*');
        itemss.forEach=[].forEach;
        itemss.forEach(e=>{
            (e.id.includes('channel-name')&&(channel.push(e)));;
            (e.id.includes('channel-name')&&(chan.push(e)));;
        });
        chan=chan[0];
        var channel_url=chan.children[0].children[0].children[0].children[0].href
        channel[0];
        channel=channel[0]
        var hash='';
        channel_name=channel.innerText
        var subcount=id('owner-sub-count').innerText
        var vt,view=id('info-contents').innerText.split('\n')[1]
        id('info-contents').innerText.split('\n')[0].includes('#')?(hash=id('info-contents').innerText.split('\n')[0],vt=id('info-contents').innerText.split('\n')[1],niew=id('info-contents').innerText.split('\n')[2]):(hash='no hash',vt=id('info-contents').innerText.split('\n')[0])
        var vid=setElement(location.href)
        var n=document.URL.split('&'),o=n[0],p=n[1],q=n[2];
        window.video_data={hash:hash,id:vid,title:vt,stats:view,uploader:channel_name,sub_count:subcount,channel_url:channel_url,list:p.split('=')[1]}
        x50();
        check2();
        console.log('change',e);
        stuff=eval('container[3]').innerText.split('\n');
        title=stuff[0];
        type=stuff[1];
        views=stuff[2];
        likes={likes:stuff[3],
               dislikes:stuff[4],
               total:(stuff[3]*1)+(stuff[4]*1),};
        check();
        setTimeout(startauto,3000)
    }
    function startauto(){
        var itemss=document.getElementsByTagName('*');
        itemss.forEach=[].forEach;
        itemss.forEach(e=>{
            (e.id.includes('channel-name')&&(channel.push(e)))
        });
        channel[0];
        channel=channel[0]
        channel_name=channel.innerText
        autosave();
        this.tofix.forEach(e=>{
            fix2(e[0],e[1]);
        });
        tasks.forEach(e=>{
            try{
                e.name=[e.function.name]
                fix2(e.name,'false')
                e.name.push(jj(e.name))
                go=eval(jj(e.name[0]))
                if(go){e.function();}
                stuff=eval('container[3]').innerText.split('\n');
                this.tofix=[['yts',''],['download','false'],['mute','false'],['next',false]]
                title=stuff[0]
                type=stuff[1]
                views=stuff[2]
                likes={likes:stuff[3]*1,
                       dislikes:stuff[4]*1,
                       total:(stuff[3]*1)+(stuff[4]*1),};
            }
            catch(e){console.log(window.Error(e))}})
    }
    listener();
}
else if(location.href.startsWith('https://www.y2mate')&&window.location.hash){
    var go=false
    decodeURIComponent(location.hash).split('#')[1].split('&').forEach(eval);
    console.info('evaled location.hash')

    locationbar.setItem(id+type)=='true'&&confirm(`you already have downloaded a ${type} version of this ${id} are you sure u want to continue`)&&(go=true)
    !go&&(window.close)
    if(go){
        document.getElementById('txt-url').value=eval(typeof url)?url:typeof id?"https://www.youtube.com/watch?v="+id:window.close();
        document.getElementById('btn-submit').click();
        var r=setInterval(function(){
            if(process_mp3_a){
                clearInterval(r);console.log('found');
                if(type.toLowerCase()=='mp3'){
                    process_mp3_a.click();
                }else{
                    document.getElementsByClassName('btn btn-success')[0].click();
                }
                r2=setInterval(function(){
                    if(document.getElementsByClassName('btn btn-success btn-file')[0]){
                        setTimeout(function(){window.close()},2000);
                        locationbar.setItem(id+type,true)
                        clearInterval(r2);
                        document.getElementsByClassName('btn btn-success btn-file')[0].click();};
                },100)
            }
        },1000)
        }
}
else{if(window.opener){window.close()}}