[buyi] MW广告拦截

MW广告拦截

// ==UserScript==
// @name         [buyi] MW广告拦截
// @namespace    buyi
// @version      1.0.1
// @description  MW广告拦截
// @author       buyi
// @match        *://*/*
// @icon         data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wgARCAAgACADAREAAhEBAxEB/8QAGAAAAwEBAAAAAAAAAAAAAAAABgcJCAX/xAAZAQACAwEAAAAAAAAAAAAAAAACBQEDBAD/2gAMAwEAAhADEAAAAKox09suonov3EyW8eJlkoet0SoK5QLYeyQtZaSAzG+oUkVUecgnmJkY/wD/xAArEAABBAIBAwIEBwAAAAAAAAABAgMEBQYREgAHIQgyExQiQRYjMTNhcZL/2gAIAQEAAT8A/Qfx16qPVNn9n3nd7VYO/ZQKTH3A3NagLLT9g+ByWXXR7GUAgEf669LPfDJIWS10W7v7OfjWYzDGrkWDqnVsSeXA/DKySEcykbB4nn0NdZS3ZO0UlirSlTro4LBdU0S2feEqAJSojYB14J312SnY1A78X+HX2Mxp9c3Kky48uS1zkQnWljiHSCQpBGwdE7Urq1po+R9z4U3FKG0YRVWDaoLiJX7k08EpZYjAkMsAhK1khO/JA2dhgq4Dn7gBv+/v1MzdJVkdLLlLkEuSURULSWikp0kthST9SdEqGwD4IO+se7MPzvVo9axWJq66/rX7OUtDgQWlIAQ6gJ3pQLgbA2D09h6aZxOYUTsBqM0pMpaUOH5lggJC1ggbUCEaUkkaBUR9wTbZDN7hU7cKyDFY7XF5xjjsPnkdkedA64kHz467zU7+KtyMpoWQs2khBkoUdBLyUkBST9gsDRB8A6PVIxUHJIfcKVfR6idJhOQ5kF+SlXNkLUtooJIKFpUSokDyDojwCMkvKyNi70urtYVlZKKPhwoz4W4tkn8xR47I+gqJ2B4BJ67Lz7TJ3vxBbOJcciwUREKSkgJHI6HnzvQ2T1//xAAeEQACAgICAwAAAAAAAAAAAAABAgADBBESIRMUQf/aAAgBAgEBPwDQEyLQomPdswHcIJmYpmIkUaEV+exL6zYCkpx2pHKNa/mVRMpvX7ETvTxw4Gphlrbix+T/xAAfEQACAgICAwEAAAAAAAAAAAABAgADBDESExEhQQX/2gAIAQMBAT8AGpioxMyKVI5zcT1Pzip3M26pR1qJo+pxmNf0NyGpflJc3H7FqToZjuYdQywUjL1+ajKuJbz9maq00BRsz//Z
// @grant        unsafeWindow
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    const tool = {
        print(level, msg, ...args) {
            const now = new Date()
            const year = now.getFullYear()
            const month = (now.getMonth() + 1 < 10 ? "0" : "") + (now.getMonth() + 1)
            const day = (now.getDate() < 10 ? "0" : "") + now.getDate()
            const hour = (now.getHours() < 10 ? "0" : "") + now.getHours()
            const minute = (now.getMinutes() < 10 ? "0" : "") + now.getMinutes()
            const second = (now.getSeconds() < 10 ? "0" : "") + now.getSeconds()
            const timenow = "[" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second + "]"
            console[level]("[🚀 ~ MW广告拦截 🎉]" + timenow + " > ", msg, ...args)
        }
    }

    const log = {
        log(msg, ...args) {
            tool.print("log", msg, ...args)
        },
        info(msg, ...args) {
            tool.print("info", msg, ...args)
        },
        warn(msg, ...args) {
            tool.print("warn", msg, ...args)
        },
        error(msg, ...args) {
            tool.print("error", msg, ...args)
        },
        debug(msg, ...args) {
            tool.print("debug", msg, ...args)
        }
    }

    if (!unsafeWindow.$ || !unsafeWindow.jQuery || !unsafeWindow.jQuery.fn.jquery) {
        log.log("获取不到$,网站匹配失败 @buyi")
        return
    }

    // 使用类名匹配网站
    let classNames = ['main-content', 'ad-area']
    if (classNames.filter(i => $(`.${i}`).length === 0).length !== 0) {
        log.log("未找到广告元素,匹配失败 @buyi")
        return
    }

    log.log("启动中 @buyi")

    // 关闭全局透明区域广告。在cookie中设置点击次数无限大避免创建点击区域,第一次打开网站时还未创建cookie,所以执行关闭点击区域
    $.cookie("popunder-capping", '100000000000000', { expires: 365, path: '/' })
    $("#creativeDisplayed-adsterra").remove();
    log.log("关闭全局透明区域广告 @buyi")

    // 删除所有广告
    unsafeWindow.$(".ad-area").each(function () {
        let ad_group_name = $(this).attr("data-group");
        let current_url = new URL(window.location.href);
        let current_uri = current_url.pathname.split("/")[1];

        $.cookie("ad_close_" + ad_group_name + "_" + current_uri, '1')
        $(this).hide();
    });
    log.log("关闭所有广告 @buyi")

    // 重写覆盖广告渲染函数
    unsafeWindow.rsad = () => {
        log.log("重写 rsad 函数成功! @buyi")
        unsafeWindow.rsad = () => { }
    }

    // 递归关闭可关闭广告
    var closeAD = () => {
        unsafeWindow.$('.ad-area-close').click()
        setTimeout(closeAD, 3000)
    }
    closeAD()


    // 拦截alert
    var oldAlert = unsafeWindow.alert;

    const blockAlertText = [
        '请关闭阻挡广告插件并使用官方推荐浏览器 Chrome , Edge , Safari'
    ]
    unsafeWindow.alert = function (text) {
        log.log("Alert input text: " + text);
        if (blockAlertText.filter((item) => text.indexOf(item) !== -1).length > 0) {
            log.log("blocked alert text:", text)
            return;
        }
        oldAlert(text);
    }

    // 网站提示拦截成功
    let $toast = $(`<div style='
        position: fixed; 
        top: 8px; 
        left: 8px; 
        background:#07c160;
        color: white;
        height: 28px;
        line-height: 28px;
        padding: 0 16px;
        border-radius: 8px;
        z-index: 9999999999999999;' >MW拦截成功!</div>`)
    $toast.on('click', () => {
        $toast.hide()
    })
    $(document).on('click', () => {
        $toast.hide()
    })
    $toast.appendTo("body")
    // setTimeout(()=>{
    //     $toast.hide()
    // }, 1000)

    // 预加载图片
    if ($('.img-content').length === 0) {
        log.log('当前页面不是章节页面, 忽略')
        return
    }
    log.log('开始预加载图片')
    $(document).ready(() => {
        $(function () {
            const e =
                '<span class="dl-overlay-mw">MW广告拦截</span>',
                t = (e, t, r) => {
                    e.css("strokeDasharray", `${t}100`),
                        e.find(".number span").text(Math.round(t)),
                        null != r && e.find("h2").html(r);
                };
            webpMachine.webpSupport.then((r) => {
                var n = !1,
                    s = "my";
                let a,
                    i,
                    o = "ret";
                (s += "2ecret"), (s += "782ec"), (s += "ret");
                var c = 300;
                async function l(e, r, n) {
                    let s = $(".img-hosts").attr("data-img-hosts");
                    if (s) {
                        s = (s = window.atob(s)).split(",");
                        for (let t = 0; t < s.length; t++)
                            if (t >= n) {
                                let r = new URL(e);
                                e = e.replace(r.hostname, s[t]);
                                break;
                            }
                        t($(r).prev(), 0, "加載中"), await p(e, r, n);
                    }
                }
                $("img.lazy_img").each(function (e) {
                    $(this).attr("data-original", "/static/images/imagecover.png"),
                        $(this).on("load", function () {
                            ($(this).attr("src").indexOf("blob:") > -1 ||
                                $(this).attr("src").indexOf("base64") > -1) &&
                                ($(this)
                                    .css("width", "auto")
                                    .css("display", "flex")
                                    .css("min-height", "0px"),
                                    window.URL.revokeObjectURL($(this).attr("src")));
                        });
                });
                try {
                    d();
                } catch (e) { }
                function d() {
                    $("img.lazy_img").each(function (t) {
                        $(e).insertBefore($(this)),
                            $(this).outerHeight() > c && (c = $(this).outerHeight()),
                            $(this).prev().css("height", c);
                        let r = $(this)[0],
                            n = r.getAttribute("src");
                        n.indexOf("blob:") < 0 &&
                            n.indexOf("base64") &&
                            n.indexOf("/book/content/") < 0 &&
                            setTimeout(() => { p(r.getAttribute("data-r-src"), r) }, t * 500);
                    });
                }
                async function p(e, r, n = 0) {
                    let a = new XMLHttpRequest();
                    a.open("GET", e, !0),
                        a.addEventListener("progress", function (e) {
                            let n = (e.loaded / (e.loaded + 6e3)) * 100;
                            t($(r).prev(), n, "加載中");
                        }),
                        (a.responseType = "arraybuffer"),
                        (a.onerror = async function () {
                            $(r).prev().css("height", "500px");
                            let t = $(".img-hosts").attr("data-img-hosts");
                            (t = (t = window.atob(t)).split(",")),
                                n < t.length
                                    ? ((n += 1),
                                        $(r)
                                            .prev()
                                            .find(".number")
                                            .html("<span>重试中" + n + "</span>"),
                                        $(r).prev().find("h2").html(""),
                                        await l(e, r, n))
                                    : $(r).prev().hasClass("dl-overlay-mw") &&
                                    ($(r).prev().addClass("error-img"),
                                        $(r).prev().css("strokeDasharray", "100 100"),
                                        $(r).prev().find(".number").html("<span>失败</span>"),
                                        $(r).prev().find("h2").html(""),
                                        "none" == $(r).prev().find(".retry_img>span").css("display") &&
                                        ($(r).prev().find(".retry_img>span").show(),
                                            $(r)
                                                .prev()
                                                .find(".retry_img>span")
                                                .on("click", function () {
                                                    console.log(n),
                                                        $(r).prev().removeClass("error-img"),
                                                        l(e, r, n++);
                                                })));
                        }),
                        (a.onload = async function () {
                            4 == a.readyState &&
                                (200 == a.status
                                    ? ((r.src = await g(a.response, s, r)),
                                        $(r).prev().hasClass("dl-overlay-mw") && $(r).prev().remove())
                                    : 0 == n && ((n += 1), await p(e, r, n)));
                        }),
                        a.send();
                }
                function f(e) {
                    const t = e.sigBytes,
                        r = e.words,
                        n = new Uint8Array(t);
                    for (var s = 0, a = 0; s != t;) {
                        var i = r[a++];
                        if (((n[s++] = (4278190080 & i) >>> 24), s == t)) break;
                        if (((n[s++] = (16711680 & i) >>> 16), s == t)) break;
                        if (((n[s++] = (65280 & i) >>> 8), s == t)) break;
                        n[s++] = 255 & i;
                    }
                    return n;
                }
                const h = (e) => new Promise((t) => setTimeout(t, e)),
                    v = (e) => {
                        let t = new FileReader();
                        return (
                            t.readAsDataURL(e),
                            new Promise((e) => {
                                t.onloadend = () => {
                                    e(t.result);
                                };
                            })
                        );
                    };
                async function g(e, t, s) {
                    let a = e,
                        i = CryptoJS.enc.Utf8.parse(t),
                        o = CryptoJS.lib.WordArray.create(a),
                        c,
                        l = f(
                            CryptoJS.AES.decrypt(
                                {
                                    ciphertext: o,
                                },
                                i,
                                {
                                    iv: i,
                                    padding: CryptoJS.pad.Pkcs7,
                                }
                            )
                        ),
                        d = "";
                    if (r) {
                        let e = new Blob([l]);
                        d = URL.createObjectURL(e);
                    } else {
                        let e = 0;
                        for (; "" === d && e < 100;) {
                            if ((e++, !n)) {
                                let e;
                                (n = !0), (d = await webpMachine.decode(l)), (n = !1);
                            }
                            "" === d && (await h(300));
                        }
                        "" == d && console.log($(s).attr("data-sort"), "fail!!");
                    }
                    return d;
                }
            });
        });

    })
    // 预加载图片 =============== end

})();