maximilian578 / Alt Watcher v2

// ==UserScript==
// @name         Alt Watcher v2
// @namespace    https://vk.com/shiki_ex
// @version      2.1.2
// @description  [shikimori.org] Добавляет ссылку на Альтернативные сайты просмотра аниме ###
// @author       STorn
// @match https://shikimori.org/*
// @match http://shikimori.org/*
// @match https://shikimori.one/*
// @match http://shikimori.one/*
// @require      https://code.jquery.com/jquery-3.3.1.slim.min.js
// @grant        none
// @license      MIT
// @copyright    2018, Newt300 (https://openuserjs.org/users/Newt300)
// ==/UserScript==

// url, name, allowed page types bitmap(0 - blocked, 1 - hentai)
const selections = [
    ["https://smotret-anime-365.ru/catalog/search?q=", "Anime 365", 1],
    ["https://hentai365.ru/catalog/search?q=", "Hentai 365", 2],
    ["https://vk.com/video?q=", "VK", 3],
    ["https://sovetromantica.com/anime?query=", "SR", 1],
    ["https://online.anidub.com/index.php?do=search&subaction=search&search_start=1&full_search=0&result_from=1&story=", "AniDub", 1],
    ["https://video.sibnet.ru/search.php?panel=open&sortby=0&duration=0&inname=1&text=", "Sibnet", 3],
    ["http://www.animespirit.ru/index.php?do=search&story=", "animespirit", 1],
    ["http://desu.me/search/555/?o=date&c[title_only]=1&c[node]=20+22+21&q=", "Desu.me", 1]
];

let $jq = jQuery.noConflict(true);

const lang_cookie_regexp = new RegExp('(?:^|; )altWatcherLanguage=([^;]*)');

const service_cookie_regexp = [
    new RegExp('(?:^|; )altWatcherPrefServiceFor1=([^;]*)'),
    new RegExp('(?:^|; )altWatcherPrefServiceFor2=([^;]*)')
];

function getPrefService(pageType) {
    let matches = document.cookie.match(service_cookie_regexp[pageType-1]);
    if (matches){
        matches = decodeURIComponent(matches[1]);
        matches = selections.find(function(it){
            return it[1] == matches;
        });
        if (matches && matches[2] & pageType) return  matches;
    }

    for (let idx = 0, v = selections[idx]; idx < selections.length; v = selections[++idx])
        if ((v[2] & pageType) !== 0)
            return v;

    return selections[0];
}

function setPrefService(pageType, value) {
    const d = new Date(Date.now() + 1e+10);
    document.cookie = "altWatcherPrefServiceFor" + pageType + "=" + encodeURIComponent(value) + "; path=/; expires=" + d.toUTCString();
}

function getAltWatcherLanguage() {
    const matches = document.cookie.match(lang_cookie_regexp);
    if (matches){
        return decodeURIComponent(matches[1]);
    }
    return "en";
}

function setAltWatcherLanguage(value) {
    const d = new Date(Date.now() + 1e+10);
    document.cookie = "altWatcherLanguage=" + encodeURIComponent(value) + "; path=/; expires=" + d.toUTCString();
}

function start(){
    let watch_online_placeholer = $jq(".watch-online-placeholer");
    if (watch_online_placeholer.length)
    {
        let lang_code = (getAltWatcherLanguage() == "en" ? 1 : 0);
        const pageType = (!!$jq('a.b-tag[href*="genre/12"]').length + 1);
        const animeName = $jq("#animes_show > section > div > header > h1").text().split(" / "); // [ru, en]
        const link = $jq('<a target="_blank"/>');
        const bar = $jq('<div/>');
        let service = getPrefService(pageType); // used in function scope to minimize cookie reading
        const barItemClicked = function (){
                service = selections[$jq(this).data('service-index')];
                link.attr('href', service[0] + encodeURIComponent(animeName[lang_code])).text('Смотреть на ' + service[1]);
                setPrefService(pageType, service[1]);
                bar.hide();
            };

        for (let idx = 0; idx < selections.length; idx++) {
            let v = selections[idx];
            if ((v[2] & pageType) !== 0)
                bar.append($jq('<a/>').addClass('b-link_button dark watch-online').text(v[1]).data('service-index', idx).click(barItemClicked));
        }

        const en = $jq('<a>').addClass(lang_code === 1 ? "b-link_button dark" : "b-link_button").text('en').attr('title', "Искать по английскому названию");
        const ru = $jq('<a>').addClass(lang_code === 0 ? "b-link_button dark" : "b-link_button").text('ru').attr('title', "Искать по русскому названию");
        const table = $jq('<table width="100%"/>').append($jq('<tr/>')
                                                       .append($jq('<td/>').append(ru.click(function(){
                                                            ru.addClass("dark");
                                                            en.removeClass("dark");
                                                            setAltWatcherLanguage("ru");
                                                            lang_code = 0;
                                                            link.attr('href', service[0] + encodeURIComponent(animeName[0]));
                                                            bar.hide();
                                                       })))
                                                       .append($jq('<td/>').append(en.click(function(){
                                                            en.addClass("dark");
                                                            ru.removeClass("dark");
                                                            setAltWatcherLanguage("en");
                                                            lang_code = 1;
                                                            link.attr('href', service[0] + encodeURIComponent(animeName[1]));
                                                            bar.hide();
                                                        }))));

        bar.append($jq('<div/>').addClass('block watch-online').css({top: "5px"}).append(table));

        
        const pref_service = getPrefService(pageType);
        watch_online_placeholer.empty().append(
            $jq('<div/>').addClass('watch-online').append(
                link.addClass("b-link_button dark").css({"float": 'left', width: "calc(100% - 31px)"})
                .attr('href', pref_service[0] + encodeURIComponent(animeName[lang_code])).text('Смотреть на ' + pref_service[1])
            ).append(
                $jq('<a/>').addClass("b-link_button dark").css({width: "31px", "float": 'right', heigth: '31px'}).text('▼').click(function(){
                    bar.toggle();
                })
            ).append($jq('<div/>').addClass('clearfix'))
        ).append(bar.addClass('block').hide());
    }
}

$jq(document).ready(start);
$jq(document).on('page:load', start);
$jq(document).on('turbolinks:load', start);