Download VKontakte audio through client js or the .m3u8 file extension

    How it all began...


    As always, hanging on VKontakte, I decided to download a couple of new audio recordings to the computer. But I was disappointed: the audio recordings returned in some strange format: m3u8. This format did not even play vlc media pleyer, and I began to think what to do ...

    What actually do?


    Googling what kind of .m3u8 format it is, I realized that this is audio in .m3u format . Ok, download this .m3u8 file, open it with a text editor and see something like this:

    Text
    #EXTM3U
    #EXT-X-TARGETDURATION:3
    #EXT-X-ALLOW-CACHE:YES
    #EXT-X-PLAYLIST-TYPE:VOD
    #EXT-X-VERSION:3
    #EXT-X-MEDIA-SEQUENCE:1
    #EXTINF:1.000,
    6cfGpgIDcrZjA.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXTINF:2.000,
    c2d2tpKzIsYzM.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXTINF:3.000,
    a3fWlvLDwmZD4.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXTINF:3.000,
    edeWZhKTUnazE.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXTINF:3.000,
    9df2NqJzcmZj0.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXT-X-ENDLIST
    


    Further we understand that

    9df2NqJzcmZj0.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh

    - path to audio recording. That is, you need to substitute a host for each path and, most likely, this audio will become playable. Having quickly thrown a couple of lines of code on python, we implement this:

    The code
    import re
    text='''#EXTM3U
    #EXT-X-TARGETDURATION:3
    #EXT-X-ALLOW-CACHE:YES
    #EXT-X-PLAYLIST-TYPE:VOD
    #EXT-X-VERSION:3
    #EXT-X-MEDIA-SEQUENCE:1
    #EXTINF:1.000,
    6cfGpgIDcrZjA.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXTINF:2.000,
    c2d2tpKzIsYzM.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXTINF:3.000,
    a3fWlvLDwmZD4.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXTINF:3.000,
    edeWZhKTUnazE.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXTINF:3.000,
    9df2NqJzcmZj0.ts?extra=0F4d1n-wWV6igsS5Ji7x6gYIbtU_aRzsiByqvrumv4W1iznLLoiC552LnsmyKeuuOtw70WTqfYdDCir-nmlL3VlLR9i2Y6IPOudQxWPbZjlslXE7prmIvdLyoLxb3A9NFnHo2KR5NStPg1sk6ZVXrYBh
    #EXT-X-ENDLIST'''
    host='https://cs9-5v4.vkuseraudio.net/p16/d5fce44eae6dbc/'
    al = re.findall('\n.+?\.ts\?extra\=.+?\n',text)
    for r in al:
        text=text.replace(r,'\n'+host+r.strip('\n')+'\n')
    print(text)
    input()
    


    and we get an already playable .m3u file.

    BUT! The problem is that:

    • This file can only be played while links to audio gaps are valid.
    • You can also convert the file only as long as the links are valid
    • You can only convert the file on the computer on which it was received. the links are tied to the ip address of the pc.

    Having understood all this, I decided to write a program on client js so that it could be executed on the command line. That's what I did:

    Program
    class music_get{
        constructor(){
            this.el=document.getElementsByClassName("audio_row");
            this.str_param=[];
            this.json=[];
            this.last_len=this.el.length;
            this.make_str(this.el);    
            this.load_audio_to_json(0,this.str_param[0]);
        }
        parse(element_){
            //функция, возвращающая id аудио, который надо передать в запросе, чтобы получить ссылку.
            //let i=JSON.parse(element_.attributes['data-audio'].nodeValue),s1=i[13].split("/");
            //return i[1]+"_"+i[0]+"_"+s1[2]+"_"+s1[s1.length-2];
            let i = AudioUtils.asObject(JSON.parse(element_.getAttribute('data-audio')));
            return i.fullId+"_"+i.actionHash+"_"+i.urlHash;
        }
        encode_url(t) {
            //функция, декодирующая ссылку на аудиозапись
            let c = {v:(t)=> { return t.split('').reverse().join('')},r: (t, e) => {t = t.split('');for (let i, o = _ + _, a = t.length; a--; ) ~(i = o.indexOf(t[a])) && (t[a] = o.substr(i - e, 1));return t.join('')},
                 s: (t,e)=> { let i = t.length;if (i) { let o = function(t, e) {let i = t.length,o = [];if (i) {let a = i;for (e = Math.abs(e); a--; ) e = (i * (a + 1) ^ e + a) % i,o[a] = e }return o}(t, e), a = 0;for (t = t.split(''); ++a < i; ) t[a] = t.splice(o[i - 1 - a], 1, t[a]) [0];t = t.join('')}return t},
                 i:(t, e)=> {return c.s(t, e ^ vk.id)},x: (t, e)=> {let i = [];return e = e.charCodeAt(0),each(t.split(''), (t, o) => {i.push(String.fromCharCode(o.charCodeAt(0) ^ e))}),i.join('')}
            },_ = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/=',h=(t)=>{ if (!t || t.length % 4 == 1) return !1;for (var e, i, o = 0, a = 0, s = ''; i = t.charAt(a++); ) ~(i = _.indexOf(i)) && (e = o % 4 ? 64 * e + i : i, o++ % 4) && (s += String.fromCharCode(255 & e >> ( - 2 * o & 6)));return s};
            if ((!window.wbopen || !~(window.open + '').indexOf('wbopen')) && ~t.indexOf('audio_api_unavailable')) { 
            let e = t.split('?extra=')[1].split('#'),i=''===e[1]?'':h(e[1]);
            if (e = h(e[0]), 'string' != typeof i || !e) return t;for (var o, a, s = (i = i ? i.split(String.fromCharCode(9))  : []).length; s--; ) {if (o = (a = i[s].split(String.fromCharCode(11))).splice(0, 1, e) [0], !c[o]) return t; e = c[o].apply(null, a)}if (e && 'http' === e.substr(0, 4)) return e}return t
        }
        end(){
            //для каждой аудиозаписи в html код добавляем кнопку
            each(this.json,(_,item)=>{
                let els = document.querySelectorAll('[data-full-id="'+item.fullId+'"]')[0];
                if(els.children[0].children[6].children.length===3)return;
                els.children[0].children[6].innerHTML+="
    " els.children[0].children[6].children[2].attributes.info=item; }); } make_str(mass){ //функция, добавляющая в массив str_param строки с id аудио, которые будут передаваться в запросе. each(mass,(i,e)=>{ if(Math.floor(i/10)===i/10) this.str_param.push(this.parse(e)); else this.str_param[this.str_param.length-1]+=","+this.parse(e); }); } load_audio_to_json(i,l){ //посылаем запрос на сервер вк, в котором в ответ приходит массив с аудио, //каждый элемент которого мы добавляем в массив this.json ajax.post("/al_audio.php",{act:'reload_audio',al:'1',ids:l},{onDone:(a)=>{ //each - функция, которая есть на сайте vk.com - похожа на array.forEach each(a,(_,c)=>{ c=AudioUtils.asObject(c); //ну естественно декодируем ссылку, как же без этого) c.url = this.encode_url(c.url); this.json.push(c); }); //рекурсия if(this.str_param.length-1===i) this.end(); else this.load_audio_to_json(i+1,this.str_param[i+1]); }}); } _update_scroll(){ //функция, вызывающаяся при скролле страницы. if(this.el.length===this.last_len)return; let c = this.el.length,offset=c-this.last_len; this.last_len=c; let arr = Array.from(this.el).splice(-offset); this._load_button(arr); } _load_button(list){ //функция, которая подгружает новые кнопки. let leng=this.str_param.length-1; this.make_str(list); this.load_audio_to_json(leng,this.str_param[leng]); } } class music_download{ //constructor(){} download(e){ this.info = e.attributes.info; //если формат аудио - .mp3, то просто открываем ссылку в новом окне if(this.info.url.indexOf(".mp3?")!==-1) window.open(this.info.url); else //с недавнего времени вк стало поддерживать формат .m3u8, который является аудиоплейлистом(текстом), //в котором содержатся ссылки на промежутки аудио .ts, но ссылки без хоста. //Исправим это следуюшей функцией response: fetch(this.info.url).then((e)=>e.text().then((e)=>this.response(e))); } response(data){ let alls = data.match(/\n.+?\.ts\?/ig), host=this.info.url.split("index.m3u8")[0]; each(alls,(_,e)=>data=data.replace(e,"\n"+host+e.replace('\n',''))); //скачиваем полученный файл this.download_data(this.info.title.replace(/[-\/\\:*?"<>|]/gim,'')+".m3u8",data); } download_data(f_n, t) { let e = document.createElement('a'); e.setAttribute('href', //'data:text/plain;charset=utf-8,' 'data:text/html;base64,'+ btoa(t)); e.setAttribute('download', f_n); e.style.display = 'none'; document.body.appendChild(e); e.click(); document.body.removeChild(e); } } var mus = new music_get(); //функция скролла window.onscroll=()=>mus._update_scroll();

    The result is something like this:


    Further, having downloaded all the audio in one folder, I wrote the following python code to convert all .m3u8 audio to .ts :

    The code
    import requests,re,os
    def convert_mp3(f):
        z=open(f).read()
        con=list(map(lambda e: e.rstrip('\n').rstrip('#EXT-X-ENDLIST').rstrip("\n") if '#EXTM3U' not in e else '' ,re.split('#EXTINF:\d+.\d+,\n',z)))
        z = b''
        for r in con:
            if(r==''):continue;
            z+=requests.get(r).content
        open(f.strip(".m3u8")+".ts",'bw').write(z)
    z=set()
    for file in os.listdir():
        if file.endswith(".m3u8"):
            z.add(file)
            convert_mp3(file)
    z=',\n'.join(z)
    input(f"Файлы:{z} переконвертированны.\nНажмите Enter, чтобы выйти!")
    


    In principle, you can try to combine .ts snippets on js and then download the whole file, but it didn’t work out (

    PS who succeeds - write in the comments
    P.PS I forgot to say that Yandex.browser still returns links to .mp3)

    Update:


    As correctly noted nokimaro you can immediately download mp3:
    the code
    class music_get{
        constructor(){
            this.el=document.getElementsByClassName("audio_row");
            this.s=[];
            this.j=[];
            this.last_len=this.el.length;
            this.make_str(this.el);    
            this.load_audio_to_json(0,this.s[0]);
        }
        parse(element_){
            //функция, возвращающая id аудио, который надо передать в запросе, чтобы получить ссылку.
            //let i=JSON.parse(element_.attributes['data-audio'].nodeValue),s1=i[13].split("/");
            //return i[1]+"_"+i[0]+"_"+s1[2]+"_"+s1[s1.length-2];
            let i = AudioUtils.asObject(JSON.parse(element_.getAttribute('data-audio')));
            return i.fullId+"_"+i.actionHash+"_"+i.urlHash;
        }
        encode_url(t) {
            //функция, декодирующая ссылку на аудиозапись
            let c = {v:(t)=> { return t.split('').reverse().join('')},r: (t, e) => {t = t.split('');for (let i, o = _ + _, a = t.length; a--; ) ~(i = o.indexOf(t[a])) && (t[a] = o.substr(i - e, 1));return t.join('')},
                 s: (t,e)=> { let i = t.length;if (i) { let o = function(t, e) {let i = t.length,o = [];if (i) {let a = i;for (e = Math.abs(e); a--; ) e = (i * (a + 1) ^ e + a) % i,o[a] = e }return o}(t, e), a = 0;for (t = t.split(''); ++a < i; ) t[a] = t.splice(o[i - 1 - a], 1, t[a]) [0];t = t.join('')}return t},
                 i:(t, e)=> {return c.s(t, e ^ vk.id)},x: (t, e)=> {let i = [];return e = e.charCodeAt(0),each(t.split(''), (t, o) => {i.push(String.fromCharCode(o.charCodeAt(0) ^ e))}),i.join('')}
            },_ = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/=',h=(t)=>{ if (!t || t.length % 4 == 1) return !1;for (var e, i, o = 0, a = 0, s = ''; i = t.charAt(a++); ) ~(i = _.indexOf(i)) && (e = o % 4 ? 64 * e + i : i, o++ % 4) && (s += String.fromCharCode(255 & e >> ( - 2 * o & 6)));return s};
            if ((!window.wbopen || !~(window.open + '').indexOf('wbopen')) && ~t.indexOf('audio_api_unavailable')) { 
            let e = t.split('?extra=')[1].split('#'),i=''===e[1]?'':h(e[1]);
            if (e = h(e[0]), 'string' != typeof i || !e) return t;for (var o, a, s = (i = i ? i.split(String.fromCharCode(9))  : []).length; s--; ) {if (o = (a = i[s].split(String.fromCharCode(11))).splice(0, 1, e) [0], !c[o]) return t; e = c[o].apply(null, a)}if (e && 'http' === e.substr(0, 4)) return e}return t
        }
        end(){
            //для каждой аудиозаписи в html код добавляем кнопку
            each(this.j,(_,i)=>{
                let e = document.querySelectorAll('[data-full-id="'+i.fullId+'"]')[0],q=e.children[0].children[6];
                if(q.children.length===3)return;
                q.innerHTML+=""            
            });
        }
    	_g(info){    
    		if(info.url.indexOf(".mp3?")!==-1)
    			return info.url;
    		else 
    			return info.url.replace("/index.m3u8",".mp3").replace(/\/\w{11}\//,'/');
    	}
        make_str(mass){
            //функция, добавляющая в массив s строки с id аудио, которые будут передаваться в запросе.
            each(mass,(i,e)=>{
                if(Math.floor(i/10)===i/10)
                    this.s.push(this.parse(e));
                else
                    this.s[this.s.length-1]+=","+this.parse(e);
            });
        }
        load_audio_to_json(i,l){
            //посылаем запрос на сервер вк, в котором в ответ приходит массив с аудио,
            //каждый элемент которого мы добавляем в массив this.j
            ajax.post("/al_audio.php",{act:'reload_audio',al:'1',ids:l},{onDone:(a)=>{
                //each - функция, которая есть на сайте vk.com - похожа на array.forEach
                each(a,(_,c)=>{
                    c=AudioUtils.asObject(c);
                    //ну естественно декодируем ссылку, как же без этого)
                    c.url = this.encode_url(c.url);
                    this.j.push(c);
                });
                //рекурсия
                if(this.s.length-1===i) this.end();
                else this.load_audio_to_json(i+1,this.s[i+1]);
            }});
        }
        _update_scroll(){    
            //функция, вызывающаяся при скролле страницы.
            if(this.el.length===this.last_len)return;
            let c = this.el.length,offset=c-this.last_len;
            this.last_len=c;
            let arr = Array.from(this.el).splice(-offset);
            this._load_button(arr);
        }
        _load_button(list){
            //функция, которая подгружает новые кнопки.
            let leng=this.s.length-1;
            this.make_str(list);
            this.load_audio_to_json(leng,this.s[leng]);
        }
    } 
    //функция скролла
    var m = new music_get();
    window.onscroll=()=>m._update_scroll();
    

    compressed code:
    eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('8 p=7(){5.y=O.1a("1b");5.s=[];5.j=[];5.C=5.y.o;5.J(5.y);5.D(0,5.s[0])};p.q.E=7(a){a=P.Q(1c.E(a.1d("R-1e")));n a.S+"T"+a.1f+"T"+a.1g};p.q.U=7(a){8 b={v:7(a){n a.t("").1h().F("")},r:7(a,b){a=a.t("");A(8 k=1i 0,e=d+d,c=a.o;c--;)~(k=e.B(a[c]))&&(a[c]=e.V(k-b,1));n a.F("")},s:7(a,b){8 c=a.o;u(c){8 e=b,d=a.o,f=[];u(d){8 g=d;A(e=W.1j(e);g--;)e=(d*(g+1)^e+g)%d,f[g]=e}e=0;A(a=a.t("");++e>(-2*e&6)));n f};u((!M.Z||!~(M.1p+"").B("Z"))&&~a.B("1q")){8 f=a.t("?1r=")[1].t("#"),g=""===f[1]?"":c(f[1]);u(f=c(f[0]),"1s"!=1t g||!f)n a;A(8 h,l=(g=g?g.t(H.I(9)):[]).o;l--;){u(h=(c=g[l].t(H.I(11))).K(0,1,f)[0],!b[h])n a;f=b[h].1u(1v,c)}u(f&&"1w"===f.V(0,4))n f}n a};p.q.12=7(){8 a=5;G(5.j,7(b,d){8 c=O.1x(\'[R-1y-X="\'+d.S+\'"]\')[0].N[0].N[6];3!==c.N.o&&(c.1z+="")})};p.q.13=7(a){n-1!==a.z.B(".16?")?a.z:a.z.17("/1M.1N",".16").17(/\\/\\w{11}\\//,"/")};p.q.J=7(a){8 b=5;G(a,7(a,c){W.1O(a/10)===a/10?b.s.L(b.E(c)):b.s[b.s.o-1]+=","+b.E(c)})};p.q.D=7(a,b){8 d=5;1P.1Q("/1R.1S",{1T:"1U",1V:"1",1W:b},{1X:7(b){G(b,7(a,b){b=P.Q(b);b.z=d.U(b.z);d.j.L(b)});d.s.o-1===a?d.12():d.D(a+1,d.s[a+1])}})};p.q.18=7(){u(5.y.o!==5.C){8 a=5.y.o,b=a-5.C;5.C=a;a=1Y.1Z(5.y).K(-b);5.19(a)}};p.q.19=7(a){8 b=5.s.o-1;5.J(a);5.D(b,5.s[b])};8 m=20 p;M.21=7(){n m.18()};',62,126,'|||||this||function|var|||||||||||||||return|length|music_get|prototype|||split|if||||el|url|for|indexOf|last_len|load_audio_to_json|parse|join|each|String|fromCharCode|make_str|splice|push|window|children|document|AudioUtils|asObject|data|fullId|_|encode_url|substr|Math|id|charCodeAt|wbopen|||end|_g|40px|5px|mp3|replace|_update_scroll|_load_button|getElementsByClassName|audio_row|JSON|getAttribute|audio|actionHash|urlHash|reverse|void|abs|vk|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789|charAt|64|255|open|audio_api_unavailable|extra|string|typeof|apply|null|http|querySelectorAll|full|innerHTML|href|target|_blank|style|float|right|height|width|background|doc472427950_504561254|no|repeat|index|m3u8|floor|ajax|post|al_audio|php|act|reload_audio|al|ids|onDone|Array|from|new|onscroll'.split('|'),0,{}))

    Only registered users can participate in the survey. Please come in.

    How do you download music from VKontakte?

    • 67.5% via browser add-on 52
    • 19.4% through special sites 15
    • 7.7% through js 6
    • 12.9% via VkMusicBot 10 chatbot

    Also popular now: