Quick Movie Search

Кнопки быстрого доступа к популярным поисковым сайтам повышают удобство просмотра фильмов и сериалов.

// ==UserScript==
// @name         Quick Movie Search
// @namespace    Quick Movie Search
// @version      1.0
// @description  Кнопки быстрого доступа к популярным поисковым сайтам повышают удобство просмотра фильмов и сериалов.
// @author       Maesta_Nequitia
// @match        *://www.kinopoisk.ru/*
// @match        *://www.imdb.com/*
// @grant        none
// @icon         https://www.kinopoisk.ru/favicon.ico
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    const BUTTON_STYLE = {
        position: 'fixed',
        top: '26px',
        zIndex: '9999',
        cursor: 'pointer',
    };

    const filmSeriesRegex = /^https:\/\/www\.kinopoisk\.ru\/(film|series)\/[^\/]+\/?$/;

    const customSites = [
        { icon: 'https://favicon.yandex.net/favicon/imdb.com', position: '1000px', handler: 'https://www.imdb.com/find/?q=' },
        { icon: 'https://favicon.yandex.net/favicon/rutracker.org', position: '1040px', handler: 'https://rutracker.org/forum/tracker.php?nm=' },
        { icon: 'https://favicon.yandex.net/favicon/rutor.info', position: '1080px', handler: 'http://rutor.info/search/0/0/100/0/' },
        { icon: 'https://favicon.yandex.net/favicon/nnmclub.to', position: '1120px', handler: 'https://nnmclub.to/forum/tracker.php?nm=' },
        { icon: 'https://favicon.yandex.net/favicon/kinozal.tv', position: '1160px', handler: 'https://kinozal.tv/browse.php?s=' },
        { icon: 'https://favicon.yandex.net/favicon/tgx.rs', position: '1200px', handler: 'https://tgx.rs/torrents.php?c3=1&c46=1&c45=1&c42=1&c4=1&c1=1&search=' },
        { icon: 'https://favicon.yandex.net/favicon/kinopoisk-watch-dsze5.ondigitalocean.app', position: '960px', handler: 'https://kinopoisk-watch-dsze5.ondigitalocean.app/player/?id=' },
    ];

    // Функция для добавления стилей
    function addCustomStyles() {
        const customStyles = `
            .styles_root__BJH2_ {
                position: sticky;
                top: 0;
                left: 0;
                width: 100%;
                z-index: 9999;
            }
        `;
        const styleElement = document.createElement('style');
        styleElement.textContent = customStyles;
        document.head.appendChild(styleElement);
    }

    addCustomStyles(); // Вызываем функцию для добавления стилей

    function createButton(id, text, clickHandler, style) {
        style = style || {};
        let button = document.getElementById(id);

        if (!button) {
            button = document.createElement("button");
            button.id = id;
            button.innerHTML = text;
            Object.assign(button.style, style);
            button.addEventListener("click", clickHandler);
            document.body.appendChild(button);
        }
    }

    function openPage(url) {
        try {
            window.open(url, '_blank'); // Открывать в новой вкладке
        } catch (error) {
            console.warn('Error opening page:', error);
        }
    }

    function openPageForCurrentFilmDefault(searchURL) {
        const titleElement = document.querySelector('.styles_originalTitle__JaNKM') || document.querySelector('.styles_title__hTCAr span');

        if (!titleElement) {
            console.warn('Title element not found.');
            return;
        }

        const filmTitle = titleElement.innerText.replace(/\([^\)]+\)/g, '').trim();
        const pageURL = searchURL + encodeURIComponent(filmTitle);

        openPage(pageURL);
    }

    function openPageForCurrentFilmWithId(searchURL) {
        const filmIdMatch = window.location.pathname.match(/\/(film|series)\/(\d+)\/?/);

        if (!filmIdMatch) {
            console.warn('Film ID not found in URL.');
            return;
        }

        const filmId = filmIdMatch[2];
        const pageURL = searchURL + filmId;

        openPage(pageURL);
    }

    function createCustomButton(iconInfo) {
        let customButton = document.getElementById(iconInfo.icon);

        if (!customButton) {
            customButton = document.createElement('a');
            customButton.id = iconInfo.icon;
            customButton.href = '#'; // Задаем временный href
            customButton.target = '_blank'; // Открывать в новой вкладке

            const customIcon = document.createElement('img');
            customIcon.src = iconInfo.icon;
            customIcon.alt = 'Custom';

            Object.assign(customButton.style, BUTTON_STYLE, { left: iconInfo.position });

            if (iconInfo.icon === 'https://favicon.yandex.net/favicon/kinopoisk-watch-dsze5.ondigitalocean.app') {
                // Для Kinopoisk формируем URL на основе текущего ID фильма
                const filmIdMatch = window.location.pathname.match(/\/(film|series)\/(\d+)\/?/);
                if (filmIdMatch) {
                    const filmId = filmIdMatch[2];
                    customButton.href = `${iconInfo.handler}${filmId}`;
                }
            } else {
                // Для других сайтов используем название фильма
                const filmTitleElement = document.querySelector('.styles_originalTitle__JaNKM') || document.querySelector('.styles_title__hTCAr span');
                if (filmTitleElement) {
                    const filmTitle = filmTitleElement.innerText.replace(/\([^\)]+\)/g, '').trim();
                    customButton.href = `${iconInfo.handler}${encodeURIComponent(filmTitle)}`;
                }
            }

            customButton.appendChild(customIcon);
            document.body.appendChild(customButton);
        }
    }

    function checkUrl() {
        const currentUrl = window.location.href;

        if (filmSeriesRegex.test(currentUrl)) {
            customSites.forEach(createCustomButton);
        } else {
            customSites.forEach(({ icon }) => {
                const customButton = document.getElementById(icon);
                if (customButton) {
                    customButton.remove();
                }
            });
        }
    }

    checkUrl();

    const observer = new MutationObserver(checkUrl);
    observer.observe(document.body, { childList: true, subtree: true });
})();

// Функция для выбора случайного фильма
(function () {
    'use strict';

    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function createRandomButton() {
        const randomButton = document.createElement('button');
        randomButton.textContent = 'Случайный фильм';
        randomButton.style.margin = '-4px';
        randomButton.addEventListener('click', handleButtonClick);

        const targetElement = document.querySelector('.hide_my_vote_filtr');
        targetElement ? targetElement.appendChild(randomButton) : console.log('Target element not found.');
    }

    function handleButtonClick() {
        const infoElements = document.querySelectorAll('.info');
        if (!infoElements.length) {
            console.log('No elements with class "info" found.');
            return;
        }

        const randomIndex = getRandomInt(0, infoElements.length - 1);
        const randomInfo = infoElements[randomIndex];
        const filmName = randomInfo.querySelector('.name').textContent.trim();
        const filmDuration = randomInfo.querySelector('span:nth-child(2)').textContent.trim();
        const englishName = randomInfo.querySelector('.name-ru + .name-en');
        let filmInfo = `Случайный фильм (${randomIndex + 1}):<br>${filmName}`;
        englishName && (filmInfo += `<br>${englishName.textContent.trim()}`);
        filmInfo += `<br>${filmDuration}<br>`;
        console.log(filmInfo);
        alert(filmInfo);
    }

    createRandomButton();
})();

// Кнопка на IMDb
const BUTTON_STYLE = {
    position: 'fixed',
    top: '19px',
    zIndex: '9999',
    cursor: 'pointer',
    right: '26px',
};

var imdbHeader = document.getElementById('imdbHeader');
if (imdbHeader) {
    imdbHeader.style.position = 'sticky';
    imdbHeader.style.top = '0';
    imdbHeader.style.width = '100%';
    imdbHeader.style.zIndex = '1000';
    imdbHeader.style.display = 'flex';

    var englishTitleElement = document.querySelector('.sc-d8941411-1.fTeJrK');
    if (!englishTitleElement) {
        englishTitleElement = document.querySelector('.hero__primary-text');
    }

    if (englishTitleElement) {
        var englishTitle = englishTitleElement.textContent.trim();
        var originalTitleIndex = englishTitle.indexOf('Original title:');

        if (originalTitleIndex !== -1) {
            englishTitle = englishTitle.substring(originalTitleIndex + 'Original title:'.length).trim();
        }

        var kinopoiskIcon = document.createElement('img');
        kinopoiskIcon.src = 'https://favicon.yandex.net/favicon/kinopoisk.ru';
        kinopoiskIcon.style.width = '16px';
        kinopoiskIcon.style.height = '16px';
        var kinopoiskButton = document.createElement('a');
        kinopoiskButton.href = 'https://www.kinopoisk.ru/index.php?kp_query=' + encodeURIComponent(englishTitle);
        kinopoiskButton.target = '_blank';
        Object.assign(kinopoiskButton.style, BUTTON_STYLE);
        kinopoiskButton.innerHTML = '';
        kinopoiskButton.appendChild(kinopoiskIcon);
        imdbHeader.appendChild(kinopoiskButton);
    }
}