levelKro / YouTube Direct Downloader

// ==UserScript==
// @name         YouTube Direct Downloader
// @namespace    https://levelkro.com
// @version      0.5.2
// @description  Download direct files of Youtube video (no recode).
// @author       levelKro (https://levelkro.com)
// @match        https://*.youtube.com/*
// @grant        none
// @license		 MIT
// @copyright 2018, levelKro (https://levelkro.com) (https://openuserjs.org/users/levelKro)
// ==/UserScript==
console.log("YTDD : Script started, check YouTube URL each 500ms");
var v_url = "";
var v_type = "";
var v_title = "";
var output = "";
var url = "";
var put = false;
setInterval(function(){
    if(window.location.href.indexOf("/watch")!="-1"){
        var chk = document.getElementById("messages");
        if(chk) {
            put=document.getElementById("ytdownload");
            if(!put) {
                console.log("YTDD : Installing code for rendering");
                chk.innerHTML = '<div id="ytdownload" style="background:#040404; color:#fefefe; padding:10px; border-radius:5px; border:1px solid #242424; font-size:1.2em;"></div>';
                url="";
            }
            put=document.getElementById("ytdownload");
            if(put){
                if(url!=window.location.href || put.innerHTML=="") {
                    url = window.location.href;
                    document.getElementById("ytdownload").innerHTML="<i>Contacting Youtube API ...</i>";
                    console.log("YTDD : New page detected, Watching now; "+url);
                    v_url = "";
                    v_type = "";
                    output = "";
                    var vars = "YTDD&"+url.split("?")[1];
                    var vars_array = vars.split("&");
                    vars_array.forEach(function(entry) {
                        var c = entry.indexOf("v=");
                        if(c!="-1") {
                            var v = entry.split("=")[1];
                            console.log("YTDD : Found video ID; "+v);
                            if(v) {
                                console.log("YTDD : Call Youtube API for video details");
                                var url_api="//www.youtube.com/get_video_info?video_id="+v+"&el=embedded&ps=default&eurl=&gl=US&hl=en";
                                if (window.XMLHttpRequest) {
                                    // code for IE7+, Firefox, Chrome, Opera, Safari
                                    var xmlhttp=new XMLHttpRequest();
                                }
                                else {
                                    // code for IE6, IE5
                                    var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                                }
                                xmlhttp.onreadystatechange=function() {
                                    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                                        console.log("YTDD : Youtube API answer");
                                        var response = xmlhttp.responseText;
                                        var request = {};
                                        var out = false;
                                        var pairs = response.split('&');
                                        for (var i = 0; i < pairs.length; i++) {
                                            if(!pairs[i]) continue;
                                            var pair = pairs[i].split('=');
                                            request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
                                        }
                                        if(request["title"]!="") {
                                            v_title = decodeURIComponent(request["title"]).replace(/\+/g," ");
                                        }
                                        var streams = request["url_encoded_fmt_stream_map"];
                                        var streams_array = streams.split(",");
                                        output += '<h2>YouTube Direct Downloader</h2><h3>for <u style="color:#ff9900">'+v_title+'</u></h3><p>Right click and "save target as..." for save file. <u>Don\'t forget to rename filename</u> with the name of video.</p><ul>';
                                        streams_array.forEach(function(entry) {
                                            var stream_array = entry.split("&");
                                            stream_array.forEach(function(t) {
                                                var s = t.split("=");
                                                if(s[0]=="type") v_type=decodeURIComponent(s[1]);
                                                else if(s[0]=="url") v_url=decodeURIComponent(s[1]);
                                            });
                                            if(v_type!="") {
                                                v_type=v_type.replace(';+codecs="'," (")+")";
                                                v_type=v_type.replace('")',")");
                                                v_type=v_type.replace(',+'," / ");
                                                output += '<li><a href="'+v_url+'" target="_blank" style="font-size:1.2em; color:#0099ff;">Download</a> <i>'+v_type+'</i></li>';
                                                out = true;
                                            }
                                        });
                                        output += '</ul>';
                                        if(out==false) {
                                            output = '<h2>YouTube Direct Downloader</h2><h3>for <u style="color:#ff9900">'+v+'</u></h3><p>Sorry, no link available for this video.</p>';
                                            console.log("YTDD : Sorry, no video link found. This video is private, region locked or protected. Try with GenYouTube.");
                                        }
                                    }
                                }
                                xmlhttp.open("GET", url_api, false );
                                xmlhttp.send();
                            }
                            output += '<p>Need audio or video only ? Need more formats ? Script got error ? Try <a href="https://video.genyoutube.net/'+v+'" target="_blank" style="color:#0099ff;">GenYoutube</a> (no affiliation, many ads but work).</p>';
                            output += '<p><b>DISCLAIMER</b> Do not use this script to download protected content without the permission of the author. Buy the product instead of downloading it, whenever possible. The use of this script is at your own risk and the author is not responsible for its use.</p>';
                        }
                        console.log("YTDD : Display links for the video (if available)");
                        document.getElementById("ytdownload").innerHTML = output;
                    });
                }
            }
        }
    }
}, 500);