ghostwan / TVShow Time fast search episodes at many torrent sites

// ==UserScript==
// @name         TVShow Time fast search episodes at many torrent sites
// @version      5.0
// @description  Create links on each to-watch episodes to easily search and download it from many torrent sites, like 1337x, The Pirate Bay, EZTV, RARBG, T411 and others, you can manually choose your favorite torrent provider, subtitles provider and torrent resolution. Fork from Everton Leite script
// @author       Ghostwan
// @include      *www.tvtime.com*
// @grant        none
// ==/UserScript==

// Replace in the search url of your favorite provider the search part by $QUERY ("Utopia+S01E01+720p")
// or use the variables $NAME ("Utopia"), $EPISODE ("S01E01"), $RESOLUTION ("720p")
var providers = [
    {id: "1337x", label: "1337x", url: "http://1337x.to/search/$QUERY/1/"},
    {id: "thepiratebay", label: "The Pirate Bay", url: "https://thepiratebay.org/search/$QUERY"},
    {id: "rarbg", label: "RARBG", url: "http://rarbg.to/torrents.php?search=$QUERY"},
    {id: "eztv", label: "EZTV", url: "https://eztv.ag/search/$QUERY"},
    {id: "extratorrent", label: "Extra Torrent", url: "http://extratorrent.cc/search/?search=$QUERY"},
    {id: "torrentdownloads", label: "Torrent Downloads", url: "https://www.torrentdownloads.me/search/?search=$QUERY"},
    {id: "demonoid", label: "Demonoid", url: "http://www.dnoid.me/files/?query=$QUERY"},
    {id: "torlock", label: "Torlock", url: "https://www.torlock.com/all/torrents/$QUERY.html"},
    {id: "t411", label: "T411", url: "http://www.t411.li/torrents/search/?search=$QUERY&order=seeders&type=desc"},
    {id: "none", label: "none", url: ""},
];

var resolutions = [{id: "all", label: "All"},
                   {id: "1080p", label: "1080p"},
                   {id: "720p", label: "720p"},
                   {id: "480p", label: "480p"}
                  ];

var subtitles = [
    {id : "subscene", label : "Subscene", url: "http://subscene.com/subtitles/release?q=$QUERY"},
    {id : "podnapisi", label : "Podnapisi", url: "https://www.podnapisi.net/subtitles/search/advanced?keywords=$NAME+$EPISODE"},
    {id: "none", label: "none", url: ""},
];

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
function getCookieData(name, datas){
    for (var i=0; i<datas.length; i++){
        if (datas[i].id == getCookie(name)){
            return datas[i];
        }
    }
    return datas[0];
}

function createListButton(name, data, defaultValue ,cookieName, marginTopPosition, marginRightPosition, color) {
    var htmlContent = "";
    htmlContent += "<style>";
    htmlContent += "#torrent-"+name+"-button{ float: right; font-size: 10px; box-shadow: rgba(0, 0, 0, 0.3) 1px 1px 2px; margin-top: "+marginTopPosition+"; margin-right: "+marginRightPosition+"; cursor: pointer; background-color: #444444; color: "+color+"; padding: 0px 5px; border-radius: 3px; position: relative; z-index: 101; }";
    htmlContent += "#torrent-"+name+"-button:hover{ background-color: #666; }";
    htmlContent += "#torrent-"+name+"-list{ display: none; list-style: none; box-shadow: rgba(0, 0, 0, 0.3) 1px 1px 2px; text-align: right; margin-right: "+marginRightPosition+"; position: absolute; width: 90px; right: 2px; font-size: 10px; line-height: 11px; background: "+color+"; border-radius: 3px; padding: 0; margin-top: -7px; padding-top: 4px; padding-bottom: 2px; z-index: 100; }";
    htmlContent += "#torrent-"+name+"-list li{ padding: 1px 3px 0px 0px; cursor: pointer; color: #444; }";
    htmlContent += "#torrent-"+name+"-list li:hover, #torrent-"+name+"-list li.selected{ background-color: #444; color: "+color+"; }";
    htmlContent += "</style>";
    htmlContent += "<div id='torrent-"+name+"-button'>";
    htmlContent += "torrent "+name+"";
    htmlContent += "</div>";
    htmlContent += "<ul id='torrent-"+name+"-list'>";
    var cookie = getCookie(cookieName);
    for (var i=0; i< data.length; i++){
        htmlContent += "<li identifier='" + data[i].id + "'" + (cookie == data[i].id || (cookie === "" && data[i].id == defaultValue) ? " class='selected'" : "") + ">" + data[i].label + "</li>";
    }
    htmlContent += "</ul>";
    $("#to-watch").prepend(htmlContent);
    $("#torrent-"+name+"-button").on("click", function(){
        $("#torrent-"+name+"-list").slideToggle(200);
    });
    $("#torrent-"+name+"-list li").on("click", function(){
        setCookie(cookieName, $(this).attr("identifier"), 365);
        $("#torrent-"+name+"-list li").removeClass("selected");
        $(this).addClass("selected");
        $("#torrent-"+name+"-list").slideUp(200);
        update_dl_links(true);
    });
}

$(document).ready(function(){
    createListButton("provider1", providers, "1337x" ,"torrent-provider1", "-18px", "294px", "#ffd90e");
    createListButton("provider2", providers, "none" ,"torrent-provider2", "-18px", "193px", "#ff8cbd");
    createListButton("subtitle", subtitles, "none" ,"torrent-subtitle", "-18px", "105px", "#c1ffd4");
    createListButton("resolution", resolutions, "all" ,"torrent-resolution", "-18px", "10px", "#54d0ff");
    update_dl_links();
});

function update_dl_links(update_html_only){
    $(".dl_links").remove();
    $("#to-watch .secondary-link").each(function(){
        var episode = $(this).prev().children("a").html();
        if (episode.match(/^(a-Z)*S[0-9]+E[0-9]+/)){
            var name = $(this).html();
            if (name.indexOf("(") >= 0){
                name = name.substring(0, name.indexOf("(") - 1);
            }
            var mainProvider = getCookieData("torrent-provider1", providers);

            var secondaryProvider = getCookieData("torrent-provider2", providers);

            var torrentResolution = getCookie("torrent-resolution");

            var subtitle = getCookieData("torrent-subtitle", subtitles);

            var resolution = "";

            if (torrentResolution != "all")
                resolution = " "+torrentResolution;

            var query = encodeURIComponent(name + " " + episode + resolution);

            //url = url.replace(/%26amp%3B/g, "%20").replace(/\./g, "%20").replace(/'/g, "").replace(/[%20]{5,}/g, ' ');

            var target = $(this).parent().parent().children(".nav");
            var style = "font-size: 12px; position: absolute; font-weight: 700; font-family: ProximaNova;";
            var dl_div = "<div class='dl_links' style='float: left; margin-top: -4px;'>";
            var subtitleString = "";

            var resolutionName="";

            if (torrentResolution != "all")
                resolutionName = " : "+torrentResolution;

            var mainProviderName = mainProvider.label+resolutionName;
            var secondaryProviderName = secondaryProvider.label+resolutionName;

            if (subtitle.id != "none")
                subtitleString = "onclick=\"window.open('"+ replaceKeywords(subtitle.url, query, name, episode, resolution)+"')\"";
            if(mainProvider.id != "none")
                dl_div += " <a class='dl_button' "+subtitleString+" href='" + replaceKeywords(mainProvider.url, query, name, episode, resolution) + "' style='margin-top: 0px; " + style + "' target='_blank'>"+mainProviderName+"</a>";
            if(secondaryProvider.id != "none")
                dl_div += " <a class='dl_button' "+subtitleString+" href='" + replaceKeywords(secondaryProvider.url, query, name, episode, resolution) + "' style='margin-top: 10px; " + style + "' target='_blank'>"+secondaryProviderName+"</a>";
            dl_div += "</div>";
            $(target).prepend(dl_div);
        }
    });
    if (update_html_only !== true){
        setTimeout(function(){
            update_dl_links();
        }, 3000);
    }
}

function replaceKeywords(url, query, name, episode, resolution) {
    var outputStr = url;
    outputStr = replaceAll(outputStr, "$QUERY", query);
    outputStr = replaceAll(outputStr, "$RESOLUTION", resolution);
    outputStr = replaceAll(outputStr, "$NAME", name);
    outputStr = replaceAll(outputStr, "$EPISODE", episode);
    return outputStr;
}

function replaceAll(str, find, replace) {
    return str.split(find).join(replace);
}