磁力快显

在磁力宝、SOBT、ØMagnet、磁力狗等磁力搜索引擎的搜索列表增加磁力链接显示,方便快速下载资源。

// ==UserScript==
// @name         磁力快显
// @author       zxf10608
// @version      4.1
// @homepageURL  https://greasyfork.org/zh-CN/scripts/397490
// @icon      	 https://cdn.jsdelivr.net/gh/zxf10608/JavaScript/icon/magnet00.png
// @description  在磁力宝、SOBT、ØMagnet、磁力狗等磁力搜索引擎的搜索列表增加磁力链接显示,方便快速下载资源。
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js
// @include      *://clb*.*
// @include      *://sobt*.*
// @include      *://www.btmov*.*/so/*
// @include      *://btsow*/search/*
// @include      *://www.*yuhuage*.*/search/*
// @include      *://www.seedhub.cc/movies/*
// @include      /https?:\/\/(\w)*(mag|cili)\.(net|info|icu|my|me|uk|com)\/search/
// @include      /https?:\/\/cl[mg](\d.)*(\.\w+)?\.(top|cfd|icu|xyz|com)\/\S*(word|name)=/
// @connect      www.seedhub.cc
// @connect      *
// @grant        unsafeWindow
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_openInTab
// @grant        GM_notification
// @grant        GM_setClipboard
// @grant        GM_xmlhttpRequest
// @grant        GM_registerMenuCommand
// @grant        GM_unregisterMenuCommand
// @run-at       document-start
// @license      GPL License
// @namespace http://tampermonkey.net/
// ==/UserScript==

(function() {
    'use strict';

    const blockAlert = () => {
        if (document.title.match(/磁力宝|sobt/i) !== null) {
            unsafeWindow.alert = () => console.log('已阻止弹窗');
        };
    };
	blockAlert();
	
    const setupMenu = () => {
        const isOpen = GM_getValue('open') === 1;
        const menuText = isOpen ? '关闭复制弹窗通知' : '开启复制弹窗通知';
        const menuAction = () => {
            GM_setValue('open', isOpen ? 0 : 1);
            location.reload();
        };
        GM_registerMenuCommand(menuText, menuAction);
    };
	setupMenu();

    const base32To16 = (str) => {
        if (str.length % 8 !== 0 || /[0189]/.test(str)) {
            return str;
        };
        str = str.toUpperCase();
        let bin = '';
        let newStr = '';
        for (let i = 0; i < str.length; i++) {
            let charCode = str.charCodeAt(i);
            charCode = charCode < 65 ? charCode - 24 : charCode - 65;
            charCode = ('0000' + charCode.toString(2)).slice(-5);
            bin += charCode;
        };
        for (let i = 0; i < bin.length; i += 4) {
            newStr += parseInt(bin.substring(i, i + 4), 2).toString(16);
        };
        return newStr;
    };

    const magnetIcon = (link) => {
        return `<img src="https://cdn.jsdelivr.net/gh/zxf10608/JavaScript/icon/magnet00.png" 
            class="mag1" href="${link}" 
            title="识别到磁力链接,左键打开,右键复制\n${link}" 
            target="_blank" 
            style="z-index:9123456789;display:inline-block;cursor:pointer;margin:0px 5px 2px;border-radius:50%;border:0px;vertical-align:middle;outline:none!important;padding:0px!important;height:20px!important;width:20px!important;left:0px!important;top:0px!important;">`;
    };

    const magnetCall = (href) => {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: 'GET',
                url: href,
                onload: (data) => {
                    if (data.readyState == 4 && data.status == 200) {
                        resolve(data.responseText);
                    };
                },
                onerror: reject
            });
        });
    };

    const magnetLinks = async (magnetEl) => {
        const num = Math.min(magnetEl.length, 20);
        const promises = [];

        for (let i = 0; i < num; i++) {
            let link = magnetEl.eq(i).attr('href');
            if (/^(\.|\/)/.test(link)) {
                link = location.origin + link.replace(/^\.?/g, '');
            };

            promises.push(
                magnetCall(link).then(htmlTxt => {
					let newLink;
					if (/www\.seedhub\.cc/.test(link)) {
						const key = htmlTxt.match(/data = "([a-zA-Z0-9]+)"/);
						if (key) {
							newLink = atob(key[1]);
						};
					} else {
						const key = htmlTxt.match(/href="(magnet.{54}).*"/);
						if (key) {
							newLink = key[1];
						};
					};

					if (newLink) {
						magnetEl.eq(i).after(magnetIcon(newLink));
					} else {
						console.log(`${link} 无磁力链接`);
					};
				}).catch(() => console.log(`${link} 处理失败`))
            );
        };
        await Promise.all(promises);
        console.log(`识别到${magnetEl.length}个网页链接,其中${num}个磁力链接加载成功。`);
    };

    $(document).ready(async () => {
        $('.common-link:odd,.search-tips,#cps-wrap').remove();

        $('a:not([href^="magnet:"])').each(function() {
            const link = $(this).attr('href') || '';
            const reg1 = /(^|\/|&|-|\.|\?|=|:)([a-fA-F0-9]{40})(?!\w)/;
            const reg2 = /\/([a-zA-Z2-7]{32})$/;
            let hash;

            if (reg1.test(link)) {
                hash = link.match(reg1)[2];
            } else if (reg2.test(link)) {
                hash = base32To16(link.match(reg2)[1]).toUpperCase();
            } else {
                return;
            };

            $(this).attr('target', '_blank');
            const newLink = `magnet:?xt=urn:btih:${hash}`;
            $(this).append(magnetIcon(newLink));
        });

        if ($('.mag1').length < 1 && document.title.match(/磁力宝|sobt/i) === null) {
            let magnetEl;
            if (window.location.href.indexOf('www.seedhub.cc') !== -1) {
                $('.pan-links a').each(function() {
                    const datalink = $(this).attr('data-link');
                    $(this).attr('href', datalink);
                });
                magnetEl = $('.seeds a');
            } else {
                magnetEl = $('h3 a,li a,td a,dd a').not('[href="/"],[href="javascript:;"]');
                magnetEl.attr({ 'target': '_blank', 'style': 'display:inline-block;' });
            };

            await magnetLinks(magnetEl);
        } else {
            console.log(`磁力链接有${$('.mag1').length}个。`);
        };

        setTimeout(() => {
            if ($('.115offline').length > 0) {
                $('.mag1').remove();
            }
        }, 1100);

        $('body').on('contextmenu click', '.mag1', function(e) {
            const link = $(this).attr('href');
            if (e.type === 'click') {
                GM_openInTab(link, false);
            } else {
                GM_setClipboard(link);
                if (GM_getValue('open') === 1) {
                    GM_notification({
                        title: '磁力快显:',
                        text: '磁力链接复制成功!',
                        timeout: 2000
                    });
                };
                console.log(`磁力链接复制成功:\n${link}`);
            };
            return false;
        });
    });
})();