tampermonkey

// ==UserScript==
// @name               CnBlog_AUp博图通路
// @namespace          https://www.cnblogs.com/chary
// @version            0.0.5
// @description        博客图
// @author             CharyGao
// @include            *://i-beta.cnblogs.com/*
// @include            *://i.cnblogs.com/*
// @require            https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js
// @require            https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js
// @grant              unsafeWindow
// @grant              GM_getValue
// @grant              GM_setValue
// @grant              GM_xmlhttpRequest
// @grant              GM_openInTab
// @grant              GM_setClipboard
// @grant              GM_registerMenuCommand
// @grant              GM_addStyle
// @grant              GM_download
// @run-at             document-end
// ==/UserScript==
//</editor-fold>

//<editor-fold desc="Style">


// noinspection JSUnresolvedFunction
GM_addStyle(
// language=CSS
    `/*noinspection CssUnusedSymbol*/
        div#showTips {
            top: 20px;
            left: 20px;
            position: absolute;
            padding: 3px 5px;
            background: powderblue;
            transition: opacity 800ms ease;
            opacity: 0;
            font-size: 12px;
            margin: 0 auto;
            text-align: center;
            width: 350px;
            height: auto;
            color: darkblue;
        }
    `);
//</editor-fold>

(function () {
    //<editor-fold desc="0.Fields">

    let logCount = 0;
    let totalImgCount = 0;
    let downImgCount = 0;
    let updateImgCount = 0;

    let innerOldHTML = "";
    //</editor-fold>

    //<editor-fold desc="1.入口">
    setTimeout(function () {
        try {
            setUi();
        } catch (e) {
            myLog('err:', e);
        }
    }, 5000); //页面加载完成后延时2秒执行
    //</editor-fold>

    //<editor-fold desc="2.设置UI">
    function setUi() {

        let rootHeaderNode = document.querySelector('body > cnb-root > cnb-layout > div.main > div.content.grid-noGutter > div.right.grid-column-noGutter-noWrap > cnb-tab > div.tab-nav>ul.nav-list');
        if (rootHeaderNode == null) throw "aUp err!->妈的又改版了!";

        let htmlSpanElement = document.createElement("li");
        htmlSpanElement.id = "uploadOutPic";
        htmlSpanElement.innerText = "点击同步外部图片";

        rootHeaderNode.appendChild(htmlSpanElement);

        htmlSpanElement.addEventListener("click", () => {
            synchronizeImage();
        })
    }

    //</editor-fold>


    //<editor-fold desc="3.同步过程">
    function synchronizeImage() {
        let editorBody = document.getElementById("Editor_Edit_EditorBody_ifr");
        innerOldHTML = editorBody.contentDocument.body.innerHTML;
        let bodyImages = editorBody.contentDocument.body.querySelectorAll("img");
        totalImgCount = bodyImages.length;
        myLog(`totalImgCount:${totalImgCount}`);

        bodyImages.forEach(img => {
            processOneImage(img);
        })
        showTips(`正在同步!请稍等,totalImgCount:${totalImgCount}`, 300, 1);
    }

    //</editor-fold>


    //<editor-fold desc="4.处理一张图片">
    function processOneImage(img) {

        let imgOriginalSrc = img.getAttribute('data-original');
        if(imgOriginalSrc != undefined){
         img.setAttribute('src',imgOriginalSrc);
            img.removeAttribute("data-original")
        }

        imgOriginalSrc = img.getAttribute('data-src');
        if(imgOriginalSrc != undefined){
            img.setAttribute('src',imgOriginalSrc);
            img.removeAttribute("data-src")
        }



        let imgHref = img.src;
        if (imgHref.indexOf('cnblogs.com') > 0) {
            myLog(`[skip] ${imgHref}`);
        } else {
            myLog(`[handle] ${imgHref}`);
            if (imgHref.startsWith("http")) {
                downloadImage(imgHref);
            } else {
                myLog(`${imgHref},if (imgHref.startsWith("http")) == false`);
            }
        }
    }

    //</editor-fold>


    //<editor-fold desc="5.下载图片">
    function downloadImage(imgHref) {
        // noinspection JSUnresolvedFunction,JSUnusedGlobalSymbols
        GM_xmlhttpRequest({
                method: "GET",
                headers: {
                    "Content-Type": "image/png",
                    "User-Agent": "Mozilla/5.0 AppleWebKit/537.36 Chrome/81.0.4044.138 Safari/537.36",
                    "Referer": "https://mp.weixin.qq.com",
                },
                url: imgHref,
                cookie: document.cookie,
                responseType: "blob",
                timeout: 5000,//5s
                onload: (imageDataBody) => {

                    downImgCount++;
                    let tempo = `downImgCount/totalImgCount=${downImgCount}/${totalImgCount}`;

                    // noinspection JSUnresolvedVariable
                    let headerJson = keyValuePairStringToLowercaseKeyJson(imageDataBody.responseHeaders);
                    let imageType = "image/png";
                    if (headerJson !== undefined && "content-type" in headerJson) {
                        imageType = headerJson["content-type"];
                    }
                    myLog(imageDataBody.response);

                    let bodyFormData = new FormData();

                    bodyFormData.append("imageFile",
                        new Blob([imageDataBody.response], {
                                filename: "image.png",
                                type: imageType,//"image/png",//
                            }
                        )
                    );
                    bodyFormData.set("host", "www.cnblogs.com");
                    bodyFormData.set("uploadType", "Paste");
                    uploadImage(imgHref, bodyFormData);
                    myLog(`${imgHref},${tempo}`);
                },
                onerror: (imageGetError) => {
                    myLog(`${imgHref},imageGetError:${imageGetError}`);
                },
                ontimeout: (exception) => {
                    myLog(`${imgHref},ontimeout exception:${exception}`);
                }
            }
        )
    }

    //</editor-fold>


    //<editor-fold desc="6.上传图片">
    function uploadImage(imgHref, bodyFormData) {
        axios({
            method: "POST",
            url: "https://upload.cnblogs.com/imageuploader/CorsUpload",
            data: bodyFormData,
            headers: {
                "Content-Type": "multipart/form-data",
            },
            withCredentials: true,
        }).then(response => {
            if (response.status === 200) {
                if (response.data.success) {
                    return ReplaceEditor(imgHref, response.data.message);
                }
            }
            myLog(`uploadImage response:${response}`);

        }).catch(error => {
            myLog(`uploadImage error:${error}`);
        })
    }

    //</editor-fold>

    //<editor-fold desc="7.替换url">
    function ReplaceEditor(oldUrl, newUrl) {
        myLog("oldUrl:" + oldUrl);
        myLog("newUrl:" + newUrl);

        innerOldHTML = innerOldHTML.replace(new RegExp(escapeRegExp(oldUrl), 'g'), newUrl);
        updateImgCount++;
        if (updateImgCount >= downImgCount) {
            let tempo =
                `updateImgCount/downImgCount/totalImgCount = ${updateImgCount}/${downImgCount}/${totalImgCount}`;
            myLog(`newBody:${innerOldHTML}`)

            // noinspection JSJQueryEfficiency
            let editorHTML = $("#Editor_Edit_EditorBody_ifr").contents().find("body").html();
            if (null != editorHTML) {
                $("#Editor_Edit_EditorBody_ifr").contents().find("body").html(innerOldHTML);
            }

            // document.getElementById("Editor_Edit_EditorBody_ifr").contentDocument.body.innerHTML = innerOldHTML;
            document.querySelector("iframe#Editor_Edit_EditorBody_ifr").contentWindow.document.body.innerHTML =
                innerOldHTML;

            document.querySelector("#Editor_Edit_EditorBody_ifr").contentDocument.body.innerHTML
                = innerOldHTML;

            document.getElementById("Editor_Edit_EditorBody_ifr").contentDocument.body.innerHTML
                = innerOldHTML;

            if (navigator.clipboard) {
                navigator.clipboard.writeText(innerOldHTML);
            } else {
                const eventCopyer = event => {
                    event.preventDefault();
                    event.clipboardData.setData("text/plain", innerOldHTML);
                }
                document.addEventListener("copy", eventCopyer);
                document.execCommand("copy");
                document.removeEventListener("copy", eventCopyer);
            }

            // window.parent.tinyMCE.get('Editor_Edit_EditorBody').onLoad.dispatch();


            //document.querySelector("iframe#Editor_Edit_EditorBody_ifr").contentWindow.document.body.innerHTML =
            // `<div id="lg" class="s-p-top"><img id="s_lg_img" class="s_lg_img_gold_show"
            // src="https://www.baidu.com/img/bd_logo1.png" alt="" width="270" height="129"
            // usemap="#mp" data-mce-src="https://www.baidu.com/img/bd_logo1.png">159654456789</div>`

            showTips(`同步完成,单击重新同步,如同步失败请保存再编辑和同步。${tempo}`, 300, 2);
        }
        return true;
    }

    //</editor-fold>


    //<editor-fold desc="9.辅助">
    function myLog(param1, param2) {
        param1 = param1 ? param1 : "";
        param2 = param2 ? param2 : "";
        console.log(`#${logCount++}AUp:`, param1, param2);
    }

    function showTips(content, height, time_s) {
        let windowWidth = window.innerWidth;
        // noinspection JSUnusedLocalSymbols
        let windowHeight = window.innerHeight;
        let htmlDivElement = document.createElement("div");
        htmlDivElement.id = "showTips";
        htmlDivElement.innerText = content;
        htmlDivElement.style.top = height + "px";
        htmlDivElement.style.left = height + (windowWidth / 2) - 350 / 2 + "px";
        document.body.appendChild(htmlDivElement);
        htmlDivElement.style.opacity = "0";
        htmlDivElement.style.opacity = "1";
        setTimeout(() => {
            htmlDivElement.style.opacity = "0";
        }, (time_s * 1000));
    }

    String.prototype.trimChars = function (c) {
        let re = new RegExp("^[" + c + "]+|[" + c + "]+$", "g");
        return this.replace(re, "");
    }

    function keyValuePairStringToLowercaseKeyJson(responseHeaders) {
        let commaAdded = responseHeaders.replace(/(?:\r\n|\r|\n)/g, ',').trim().replace(/,+$/g, '');
        let items = commaAdded.split(',');
        let jsonString = items.map(item => {
            return item.replace(/([^:]+)(:)(.+$)/, (match, p1, p2, p3) => {
                return `"${p1.trim().toLowerCase()}": "${p3.trim().trimChars('"')}"`;
            })
        }).join(', ');
        try {
            return JSON.parse(`{${jsonString}}`);
        } catch (err) {
            myLog(`keyValuePairStringToJson err:${err}`);
        }
    }

    function escapeRegExp(string) {
        return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
    }

    //</editor-fold>


})();

 

// ==UserScript==
// @name         CSDN,CNBLOG博客文章一键转载插件
// @version      4.1.2
// @description  CSDN博客文章转载插件 可以实现CSDN上的文章一键转载
// @author       By Jackie http://csdn.admans.cn/
// @match        *://blog.csdn.net/*/article/details/*
// @match        *://mp.csdn.net/postedit*
// @match        *://mp.csdn.net/postedit?opt=1
// @match        *://mp.csdn.net/console/editor/html?opt=1
// @match        *://www.cnblogs.com/*/p/*.html
// @match        *://www.cnblogs.com/*/articles/*.html
// @match        *://www.cnblogs.com/*/archive/*/*/*/*.html
// @match        *://*.blog.csdn.net/article/details/*
// @match        *://i.cnblogs.com/EditArticles.aspx?opt=1
// @match        *://i.cnblogs.com/EditPosts.aspx?opt=1
// @match        *://i-beta.cnblogs.com/posts/edit?opt=1
// @match        *://mp.csdn.net/mp_blog/creation/editor?opt=1
// @match        *://editor.csdn.net/md/?not_checkout=1
// @match        *://mp.csdn.net/mp_blog/creation/editor?*
// @require      https://unpkg.com/turndown/dist/turndown.js
// @grant    GM_addStyle
// @namespace https://greasyfork.org/users/164689
// @supportURL   https://github.com/JackieZheng/CsdnCnblogReproduce/issues/
// @icon         https://www.google.cn/s2/favicons?domain=csdn.net
// ==/UserScript==
GM_addStyle("#ReproduceBtn{position: absolute;float: right;right: 0px;width: auto;background: #0f962191;z-index: 9989;color: white;text-align: center;margin: 5px;padding: 5px;border-radius: 5px;cursor: pointer;line-height: 100%;}");

GM_addStyle(".tag__box{width: 100% !important;}");
GM_addStyle(".tag__box div.tag__options-list{width: 100% !important;max-height:300px !important;padding: 8px 8px 0 0;display: flex;flex-direction: row;align-content: flex-start;align-items: center;justify-content: space-between;flex-wrap: wrap;}");

GM_addStyle(".tag__box div .tag__options-list .tag__option-box:last-child {margin-right: auto;}");
GM_addStyle(".tag__box div .tag__options-list .tag__option-box:hover {color:#67c23a;}");
GM_addStyle(".tag__box div.tag__options-content{height: auto !important;}");



(function() {
    'use strict';
    //document.domain="csdn.net";
    var cnblog = location.href.indexOf("cnblogs.com") > -1 ? true: false;
    if (cnblog) {
        document.domain = "cnblogs.com";
    } else {
        document.domain = "csdn.net";
    }
    //文章查看窗口
    if (location.href.indexOf("article/details") > -1 || location.href.indexOf("www.cnblogs.com") > -1) {
        var divBtn = document.createElement("div");
        divBtn.setAttribute("id", "ReproduceBtn");
        divBtn.innerHTML = '转载';
        if (cnblog) {
            divBtn.style.marginTop = "-40px";
            divBtn.style.position = "relative";
        }
        var article = document.getElementsByClassName('article_content')[0] || document.getElementsByClassName('postBody')[0] || document.getElementsByClassName('blogpost-body')[0];
        article.insertBefore(divBtn, article.childNodes[0]);
        var posteditUrl = cnblog ? "https://i-beta.cnblogs.com/posts/edit?opt=1": "https://mp.csdn.net/console/editor/html?opt=1";

        divBtn.onclick = function() {
            window.open(posteditUrl);
        }
    }
    //文章发布窗口
    else
    {
        document.onreadystatechange = function(e) {
            if (document.readyState == 'complete') {
                //setTimeout(()=>{},8000);
                var contentToPaste=null;
                var timer = setInterval(function(){
                    if(!contentToPaste)
                    {
                        contentToPaste = document.getElementsByTagName("iframe")[0] == undefined ? null: document.getElementsByTagName("iframe")[0].contentDocument.body;
                    }
                    else{
                        clearInterval(timer);
                        opt(contentToPaste);
                    }
                },30)
                }
        }

    }

    function opt(contentDocumentbody) {
        if (window.opener && (location.href.indexOf("?opt=1") > -1||location.href.indexOf("?not_checkout=1") > -1)) {
            var authorName = "";
            if (window.opener.document.getElementsByClassName('follow-nickName').length > 0) {
                authorName = window.opener.document.getElementsByClassName('follow-nickName')[0].innerText;
            } else if (window.opener.document.getElementById('profile_block')) {
                authorName = window.opener.document.getElementById('profile_block').childNodes[1].innerText;
            } else if (window.opener.document.getElementById('author_profile_detail')) {
                authorName = window.opener.document.getElementById('author_profile_detail').childNodes[1].innerText;
            }
            var blogContent = (window.opener.document.getElementById('content_views') || window.opener.document.getElementById('cnblogs_post_body')).innerHTML + "<br>---------------------" + "<br>作者:" + authorName + "<br>来源:" + (cnblog == true ? "CNBLOGS": "CSDN") + "<br>原文:" + window.opener.location.href.split('?')[0] + "<br>版权声明:本文为作者原创文章,转载请附上博文链接!" + "<br>内容解析By:<a href=https://greasyfork.org/zh-CN/scripts/381053-csdn-cnblog%E5%8D%9A%E5%AE%A2%E6%96%87%E7%AB%A0%E4%B8%80%E9%94%AE%E8%BD%AC%E8%BD%BD%E6%8F%92%E4%BB%B6 target=_blank>CSDN,CNBLOG博客文章一键转载插件</a>";
            var input_title = (document.getElementById('post-title') ||document.getElementById('txtTitle') || document.getElementById('Editor_Edit_txbTitle') || document.querySelector('input.cnb-input'))||document.getElementsByClassName("article-bar__title")[0];
            if (input_title) {
                var aTitle = "[转]" + window.opener.document.title.split('_')[0];
                aTitle = aTitle + "(转载请删除括号里的内容)";
                input_title.value = aTitle;
            }

            if (contentDocumentbody) {
                var aContent = blogContent.replace(/<ul class=\"pre-numbering\"[^>]*>(.*?)<\/ul>/g, '').replace(/<div class=\"hljs-ln-line hljs-ln-n\"[^>]*>(.*?)<\/div>/g, '').replace(/<div class=\"hljs-ln-numbers\"[^>]*>(.*?)<\/div>/g, '').replace(/<div class=\"cnblogs_code_toolbar\"[\s\S].*?<\/div>/g, '').replace(/<a[\s\S].*class=\"toolbar_item[\s\S].*>?<\/a>/g, '').replace(/\n/g, '').replace(/<nobr aria-hidden=\"true\">(.*?)<\/nobr>/g, '').replace(/<script type=\"math\/tex\"[^>]*>(.*?)<\/script>/g, '');
                if (cnblog) {
                    aContent = "(转载请删除括号里的内容)" + aContent;
                } else {
                    /*处理csdn代码*/
                    var rePre = /<pre[^>]*>(.*?)<\/pre>/gi;
                    //aContent=aContent.replace(/\n/g,'');
                    var arrMactches = aContent.match(rePre);
                    if (arrMactches != null && arrMactches.length > 0) {

                        for (var i = 0; i < arrMactches.length; i++) {

                            var preText = '';
                            var codeTag = window.opener.document.getElementsByTagName('pre')[i];
                            if(codeTag){
                                if(codeTag.querySelector("ul[class*='pre-numbering']")){
                                    codeTag.querySelector("ul[class*='pre-numbering']").remove();
                                }
                                var eles = codeTag.getElementsByTagName('li');
                                if (eles.length > 0) {
                                    for (var j = 0; j < eles.length; j++) {
                                        preText += eles[j].innerText+"\n";
                                    }
                                } else {
                                    preText += codeTag.innerText;
                                }
                            }
                            var preCodeHtml = "<pre><code class=\"hljs\">" + preText.replace(/</g, '&lt;').replace(/>/g, '&gt;') + "</code></pre>";

                            aContent = aContent.replace(arrMactches[i], preCodeHtml);
                        }
                        aContent = "(转载请删除括号里的内容)" + aContent;
                    }
                }
                contentDocumentbody.innerHTML = aContent;
                if (contentDocumentbody.children.ReadBtn) contentDocumentbody.children.ReadBtn.remove();
                if (contentDocumentbody.children.ReproduceBtn) contentDocumentbody.children.ReproduceBtn.remove();
                let mathspace=contentDocumentbody.querySelectorAll("[width*='thickmathspace']");
                mathspace.forEach(function(ele){
                    ele.outerHTML=" ";
                });
                let mathspan=contentDocumentbody.querySelectorAll("[class*='MathJax']");
                mathspan.forEach(function(ele){
                    let innerText= ele.innerText;
                    ele.outerHTML="<span>"+innerText+"</span>";
                });
            }
            if (document.querySelector("[class^='el-input__inner']")) document.querySelector("[class^='el-input__inner']").value = window.opener.location.href.split('?')[0];
            if (document.querySelector("[class^='el-checkbox__original']")) document.querySelector("[class^='el-checkbox__original']").checked = true;
            if(document.querySelectorAll("[class*='copyright-box']").length>0)
            {
                document.querySelectorAll("[class*='copyright-box']")[0].style.display="";
                document.querySelectorAll("[class*='copyright-box']")[1].style.display="";
            }

            var htmlContent = blogContent.replace(/<ul class=\"pre-numbering\"[\s\S].*<\/ul>/g, '');
            htmlContent = htmlContent.replace(/<div class=\"cnblogs_code_toolbar\"[\s\S].*?<\/div>/g, '');
            htmlContent = htmlContent.replace(/<a[\s\S].*class=\"toolbar_item[\s\S].*>?<\/a>/g, '');
            htmlContent = htmlContent.replace(/<div id=\"ReproduceBtn\"[\s\S].*?<\/div>/g, '');
            htmlContent = htmlContent.replace(/<div id=\"ReadBtn\"[\s\S].*?<\/div>/g, '');
            htmlContent = htmlContent.replace(/<div class=\"line[\s\S].*>\d+?<\/div>/g, '');
            var turndownService = new TurndownService();
            var mdContent = turndownService.turndown(htmlContent);
            console.log(mdContent);
            var csdnMDeditor=document.getElementsByClassName("editor__inner");
            if (csdnMDeditor.length>0) {
                csdnMDeditor[0].innerHTML=mdContent;
            }
            var cnblogsMDeditor = document.getElementById("Editor_Edit_EditorBody");
            if (cnblogsMDeditor) {
                cnblogsMDeditor.value = mdContent;
            } else {
                //if (input_title) {
                    //input_title.onchange = function() {
                        //if (document.getElementsByClassName("textfield")) document.getElementsByClassName("textfield")[0].options[2].selected = true;
                        if (document.querySelector("[class^='ipt-box']")) document.querySelector("[class^='ipt-box']").querySelector("[class^='el-input__inner']").value = window.opener.location.href.split('?')[0];
                        if (document.querySelector("[class^='el-checkbox__original']")) document.querySelector("[class^='el-checkbox__original']").checked = true;
                        if(document.querySelector("[class^='el-radio__original'][value='repost']"))document.querySelector("[class^='el-radio__original'][value='repost']").click();
                        if(document.querySelector("[class^='el-radio__original'][value='0']"))document.querySelector("[class^='el-radio__original'][value='0']").click()
                        if(document.querySelector("[class^='el-radio__original'][value='1']"))document.querySelectorAll("[class^='el-radio__original'][value='1']")[1].click()
                        if(document.querySelector("[class^='el-checkbox__original'][value]"))document.querySelector("[class^='el-checkbox__original'][value]").click();
                        if(document.querySelectorAll("[class*='copyright-box']"))
                        {
                            document.querySelectorAll("[class*='copyright-box']")[0].style.display="";
                            document.querySelectorAll("[class*='copyright-box']")[1].style.display="";
                        }
                    //}
                //}
            }

        }
    }

})();
// ==UserScript==
// @name              夜间模式助手
// @namespace         https://github.com/syhyz1990/darkmode
// @version           2.1.4
// @icon              https://www.youxiaohou.com/darkmode.png
// @description       实现任意网站的夜间模式,支持网站白名单
// @author            YouXiaoHou
// @license           MIT
// @homepage          https://www.youxiaohou.com/tool/install-darkmode.html
// @supportURL        https://github.com/syhyz1990/darkmode
// @updateURL         https://www.youxiaohou.com/darkmode.user.js
// @downloadURL       https://www.youxiaohou.com/darkmode.user.js
// @match             *://*/*
// @require           https://unpkg.com/darkrule@latest/dist/rule.min.js
// @require           https://unpkg.com/sweetalert2@10.16.6/dist/sweetalert2.min.js
// @resource          swalStyle https://unpkg.com/sweetalert2@10.16.6/dist/sweetalert2.min.css
// @run-at            document-start
// @grant             GM_getValue
// @grant             GM_setValue
// @grant             GM_registerMenuCommand
// @grant             GM_getResourceText
// ==/UserScript==

;(function () {
    'use strict';

    let util = {
        getValue(name) {
            return GM_getValue(name);
        },

        setValue(name, value) {
            GM_setValue(name, value);
        },

        addStyle(id, tag, css) {
            tag = tag || 'style';
            let doc = document, styleDom = doc.getElementById(id);
            if (styleDom) return;
            let style = doc.createElement(tag);
            style.rel = 'stylesheet';
            style.id = id;
            tag === 'style' ? style.innerHTML = css : style.href = css;
            doc.head.appendChild(style);
        },

        addThemeColor(color) {
            let doc = document, meta = doc.getElementsByName('theme-color')[0];
            if (meta) return meta.setAttribute('content', color);
            let metaEle = doc.createElement('meta');
            metaEle.name = 'theme-color';
            metaEle.content = color;
            doc.head.appendChild(metaEle);
        },

        getThemeColor() {
            let meta = document.getElementsByName('theme-color')[0];
            if (meta) {
                return meta.content;
            }
            return '#ffffff';
        },

        removeElementById(eleId) {
            let ele = document.getElementById(eleId);
            ele && ele.parentNode.removeChild(ele);
        },

        hasElementById(eleId) {
            return document.getElementById(eleId);
        },

        filter: '-webkit-filter: url(#dark-mode-filter) !important; filter: url(#dark-mode-filter) !important;',
        reverseFilter: '-webkit-filter: url(#dark-mode-reverse-filter) !important; filter: url(#dark-mode-reverse-filter) !important;',
        firefoxFilter: `filter: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><filter id="dark-mode-filter" color-interpolation-filters="sRGB"><feColorMatrix type="matrix" values="0.283 -0.567 -0.567 0 0.925 -0.567 0.283 -0.567 0 0.925 -0.567 -0.567 0.283 0 0.925 0 0 0 1 0"/></filter></svg>#dark-mode-filter') !important;`,
        firefoxReverseFilter: `filter: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><filter id="dark-mode-reverse-filter" color-interpolation-filters="sRGB"><feColorMatrix type="matrix" values="0.333 -0.667 -0.667 0 1 -0.667 0.333 -0.667 0 1 -0.667 -0.667 0.333 0 1 0 0 0 1 0"/></filter></svg>#dark-mode-reverse-filter') !important;`,
        noneFilter: '-webkit-filter: none !important; filter: none !important;',
    };

    let main = {
        /**
         * 配置默认值
         */
        initValue() {
            let value = [{
                name: 'dark_mode',
                value: 'light'
            }, {
                name: 'button_position',
                value: 'left'
            }, {
                name: 'button_size',
                value: 30
            }, {
                name: 'exclude_list',
                value: ['youku.com', 'v.youku.com', 'www.douyu.com', 'www.iqiyi.com', 'vip.iqiyi.com', 'mail.qq.com', 'live.kuaishou.com']
            }, {
                name: 'origin_theme_color',
                value: '#ffffff'
            }];

            value.forEach((v) => {
                util.getValue(v.name) === undefined && util.setValue(v.name, v.value);
            });
        },

        addExtraStyle() {
            try {
                return darkModeRule;
            } catch (e) {
                return '';
            }
        },

        createDarkFilter() {
            if (util.hasElementById('dark-mode-svg')) return;
            let svgDom = '<svg id="dark-mode-svg" style="height: 0; width: 0;"><filter id="dark-mode-filter" x="0" y="0" width="99999" height="99999"><feColorMatrix type="matrix" values="0.283 -0.567 -0.567 0 0.925 -0.567 0.283 -0.567 0 0.925 -0.567 -0.567 0.283 0 0.925 0 0 0 1 0"></feColorMatrix></filter><filter id="dark-mode-reverse-filter" x="0" y="0" width="99999" height="99999"><feColorMatrix type="matrix" values="0.333 -0.667 -0.667 0 1 -0.667 0.333 -0.667 0 1 -0.667 -0.667 0.333 0 1 0 0 0 1 0"></feColorMatrix></filter></svg>';
            let div = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
            div.innerHTML = svgDom;
            let frag = document.createDocumentFragment();
            while (div.firstChild)
                frag.appendChild(div.firstChild);
            document.head.appendChild(frag);
        },

        createDarkStyle() {
            util.addStyle('dark-mode-style', 'style', `
                @media screen {
                    html {
                        ${this.isFirefox() ? util.firefoxFilter : util.filter}
                        scrollbar-color: #454a4d #202324;
                    }
            
                    /* Default Reverse rule */
                    img, 
                    video, 
                    iframe,
                    canvas,
                    :not(object):not(body) > embed,
                    object,
                    svg image,
                    [style*="background:url"],
                    [style*="background-image:url"],
                    [style*="background: url"],
                    [style*="background-image: url"],
                    [background],
                    twitterwidget,
                    .sr-reader,
                    .no-dark-mode,
                    .sr-backdrop {
                        ${this.isFirefox() ? util.firefoxReverseFilter : util.reverseFilter}
                    }
            
                    [style*="background:url"] *,
                    [style*="background-image:url"] *,
                    [style*="background: url"] *,
                    [style*="background-image: url"] *,
                    input,
                    [background] *,
                    img[src^="https://s0.wp.com/latex.php"],
                    twitterwidget .NaturalImage-image {
                        ${util.noneFilter}
                    }
            
                    /* Text contrast */
                    html {
                        text-shadow: 0 0 0 !important;
                    }
            
                    /* Full screen */
                    .no-filter,
                    :-webkit-full-screen,
                    :-webkit-full-screen *,
                    :-moz-full-screen,
                    :-moz-full-screen *,
                    :fullscreen,
                    :fullscreen * {
                        ${util.noneFilter}
                    }
                    
                    ::-webkit-scrollbar {
                        background-color: #202324;
                        color: #aba499;
                    }
                    ::-webkit-scrollbar-thumb {
                        background-color: #454a4d;
                    }
                    ::-webkit-scrollbar-thumb:hover {
                        background-color: #575e62;
                    }
                    ::-webkit-scrollbar-thumb:active {
                        background-color: #484e51;
                    }
                    ::-webkit-scrollbar-corner {
                        background-color: #181a1b;
                    }
            
                    /* Page background */
                    html {
                        background: #fff !important;
                    }
                    
                    ${this.addExtraStyle()}
                }
            
                @media print {
                    .no-print {
                        display: none !important;
                    }
                }`);
        },

        setThemeColor() {
            util.setValue('origin_theme_color', util.getThemeColor());
        },

        enableDarkMode() {
            if (this.isFullScreen()) return;
            !this.isFirefox() && this.createDarkFilter();
            this.createDarkStyle();
            util.addThemeColor('#131313')
        },

        disableDarkMode() {
            util.removeElementById('dark-mode-svg');
            util.removeElementById('dark-mode-style');
            util.addThemeColor(util.getValue('origin_theme_color'))
        },

        addButton() {
            if (this.isTopWindow()) {
                let lightIcon = `<div style="background: #000;display: flex;align-items: center;justify-content: center;width: ${util.getValue('button_size')}px;height: ${util.getValue('button_size')}px;border-radius: 50%"><svg style="position: static;margin: 0;padding: 0;" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="${util.getValue('button_size') / 1.5}" height="${util.getValue('button_size') / 1.5}"><path d="M522.88 874.667A21.333 21.333 0 0 1 544.213 896v85.333a21.333 21.333 0 0 1-21.333 21.334h-21.333a21.333 21.333 0 0 1-21.334-21.334V896a21.333 21.333 0 0 1 21.334-21.333h21.333zm268.416-107.52l60.352 60.352a21.333 21.333 0 0 1 0 30.165l-15.083 15.083a21.333 21.333 0 0 1-30.186 0l-60.331-60.352a21.333 21.333 0 0 1 0-30.166l15.083-15.082a21.333 21.333 0 0 1 30.165 0zm-527.957 0l15.082 15.082a21.333 21.333 0 0 1 0 30.166l-60.352 60.352a21.333 21.333 0 0 1-30.165 0l-15.083-15.083a21.333 21.333 0 0 1 0-30.165l60.331-60.352a21.333 21.333 0 0 1 30.187 0zM512 277.333c141.376 0 256 114.624 256 256s-114.624 256-256 256-256-114.624-256-256 114.624-256 256-256zm0 64a192 192 0 1 0 0 384 192 192 0 0 0 0-384zm448.213 160a21.333 21.333 0 0 1 21.334 21.334V544a21.333 21.333 0 0 1-21.334 21.333H874.88A21.333 21.333 0 0 1 853.547 544v-21.333a21.333 21.333 0 0 1 21.333-21.334h85.333zm-810.666 0a21.333 21.333 0 0 1 21.333 21.334V544a21.333 21.333 0 0 1-21.333 21.333H64.213A21.333 21.333 0 0 1 42.88 544v-21.333a21.333 21.333 0 0 1 21.333-21.334h85.334zm687.04-307.413l15.082 15.083a21.333 21.333 0 0 1 0 30.165l-60.352 60.352a21.333 21.333 0 0 1-30.165 0l-15.083-15.083a21.333 21.333 0 0 1 0-30.165L806.4 193.92a21.333 21.333 0 0 1 30.187 0zm-618.496 0l60.352 60.352a21.333 21.333 0 0 1 0 30.165L263.36 299.52a21.333 21.333 0 0 1-30.187 0l-60.352-60.373a21.333 21.333 0 0 1 0-30.166l15.083-15.082a21.333 21.333 0 0 1 30.165 0zM522.9 64a21.333 21.333 0 0 1 21.334 21.333v85.334A21.333 21.333 0 0 1 522.9 192h-21.333a21.333 21.333 0 0 1-21.333-21.333V85.333A21.333 21.333 0 0 1 501.568 64h21.333z" fill="#fff"/></svg></div>`,
                    darkIcon = `<div style="background: #333;display: flex;align-items: center;justify-content: center;width: ${util.getValue('button_size')}px;height: ${util.getValue('button_size')}px;border-radius: 50%"><svg style="position: static;margin: 0;padding: 0;" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="${util.getValue('button_size') / 1.5}" height="${util.getValue('button_size') / 1.5}"><path d="M513.173 128A255.061 255.061 0 0 0 448 298.667c0 141.376 114.624 256 256 256a255.36 255.36 0 0 0 189.803-84.203A392.855 392.855 0 0 1 896 512c0 212.075-171.925 384-384 384S128 724.075 128 512c0-209.707 168.107-380.16 376.96-383.936l8.192-.064zM395.35 213.93l-3.52 1.409C274.645 262.827 192 377.77 192 512c0 176.725 143.275 320 320 320 145.408 0 268.16-96.981 307.115-229.803l1.536-5.504-1.6.64a319.51 319.51 0 0 1-106.496 21.227l-8.555.107c-176.725 0-320-143.275-320-320 0-28.48 3.755-56.406 10.944-83.2l.405-1.536z" fill="#adbac7"/></svg></div>`;

                let o = document.createElement('div'),
                    buttonPostion = util.getValue('button_position');
                o.style.position = 'fixed';
                o.style[buttonPostion] = '25px';
                o.style.bottom = '25px';
                o.style.cursor = 'pointer';
                o.style.zIndex = '2147483999';
                o.style.userSelect = 'none';
                o.className = 'no-print';
                o.id = 'darkBtn';
                this.isDarkMode() ? o.innerHTML = lightIcon : o.innerHTML = darkIcon;
                document.body.appendChild(o);

                o.addEventListener("click", () => {
                    if (this.isDarkMode()) { //黑暗模式变为正常模式
                        util.setValue('dark_mode', 'light');
                        o.innerHTML = darkIcon;
                        this.disableDarkMode();
                    } else {
                        util.setValue('dark_mode', 'dark');
                        o.innerHTML = lightIcon;
                        this.enableDarkMode();
                    }
                });
            }
        },

        registerMenuCommand() {
            if (this.isTopWindow()) {
                let whiteList = util.getValue('exclude_list');
                let host = location.host;
                if (whiteList.includes(host)) {
                    GM_registerMenuCommand('💡 当前网站:❌', () => {
                        let index = whiteList.indexOf(host);
                        whiteList.splice(index, 1);
                        util.setValue('exclude_list', whiteList);
                        history.go(0);
                    });
                } else {
                    GM_registerMenuCommand('💡 当前网站:✔️', () => {
                        whiteList.push(host);
                        util.setValue('exclude_list', Array.from(new Set(whiteList)));
                        history.go(0);
                    });
                }

                GM_registerMenuCommand('⚙️ 设置', () => {
                    let style = `
                                .darkmode-popup { font-size: 14px !important; }
                                .darkmode-center { display: flex;align-items: center; }
                                .darkmode-setting-label { display: flex;align-items: center;justify-content: space-between;padding-top: 15px; }
                                .darkmode-setting-label-col { display: flex;align-items: flex-start;;padding-top: 15px;flex-direction:column }
                                .darkmode-setting-radio { width: 16px;height: 16px; }
                                .darkmode-setting-textarea { width: 100%; margin: 14px 0 0; height: 100px; resize: none; border: 1px solid #bbb; box-sizing: border-box; padding: 5px 10px; border-radius: 5px; color: #666; line-height: 1.2; }
                                .darkmode-setting-input { border: 1px solid #bbb; box-sizing: border-box; padding: 5px 10px; border-radius: 5px; width: 100px}
                            `;
                    util.addStyle('darkmode-style', 'style', style);
                    util.addStyle('swal-pub-style', 'style', GM_getResourceText('swalStyle'));
                    let excludeListStr = util.getValue('exclude_list').join('\n');

                    let dom = `<div style="font-size: 1em;">
                              <label class="darkmode-setting-label">按钮位置 <div id="S-Dark-Position" class="darkmode-center"><input type="radio" name="buttonPosition" ${util.getValue('button_position') === 'left' ? 'checked' : ''} class="darkmode-setting-radio" value="left">左 <input type="radio" name="buttonPosition" style="margin-left: 30px;" ${util.getValue('button_position') === 'right' ? 'checked' : ''} class="darkmode-setting-radio" value="right">右</div></label>
                              <label class="darkmode-setting-label"><span style="text-align: left;">按钮大小(默认:30)<small id="currentSize">当前:${util.getValue('button_size')}</small></span>
                              <input id="S-Dark-Size" type="range" class="darkmode-setting-range" min="20" max="50" step="2" value="${util.getValue('button_size')}">
                              </label>
                              <label class="darkmode-setting-label-col">排除下列网址 <textarea placeholder="列表中的域名将不开启夜间模式,一行一个,例如:v.youku.com" id="S-Dark-Exclude" class="darkmode-setting-textarea">${excludeListStr}</textarea></label>
                            </div>`;
                    Swal.fire({
                        title: '夜间模式配置',
                        html: dom,
                        icon: 'info',
                        showCloseButton: true,
                        confirmButtonText: '保存',
                        footer: '<div style="text-align: center;font-size: 1em;">点击查看 <a href="https://www.youxiaohou.com/tool/install-darkmode.html" target="_blank">使用说明</a>,助手免费开源,Powered by <a href="https://www.youxiaohou.com">油小猴</a></div>',
                        customClass: {
                            popup: 'darkmode-popup',
                        },
                    }).then((res) => {
                        res.isConfirmed && history.go(0);
                    });

                    document.getElementById('S-Dark-Position').addEventListener('click', (e) => {
                        e.target.tagName === "INPUT" && util.setValue('button_position', e.target.value);
                    });
                    document.getElementById('S-Dark-Size').addEventListener('change', (e) => {
                        util.setValue('button_size', e.currentTarget.value);
                        document.getElementById('currentSize').innerText = '当前:' + e.currentTarget.value;
                    });
                    document.getElementById('S-Dark-Exclude').addEventListener('change', (e) => {
                        util.setValue('exclude_list', Array.from(new Set(e.currentTarget.value.split('\n').filter(Boolean))));
                    });
                });
            }
        },

        isTopWindow() {
            return window.self === window.top;
        },

        addListener() {
            document.addEventListener("fullscreenchange", (e) => {
                if (this.isFullScreen()) {
                    //进入全屏
                    this.disableDarkMode();
                } else {
                    //退出全屏
                    this.isDarkMode() && this.enableDarkMode();
                }
            });
        },

        isDarkMode() {
            return util.getValue('dark_mode') === 'dark';
        },

        isInExcludeList() {
            return util.getValue('exclude_list').includes(location.host);
        },

        isFullScreen() {
            return document.fullscreenElement;
        },

        isFirefox() {
            return /Firefox/i.test(navigator.userAgent);
        },

        firstEnableDarkMode() {
            if (document.head) {
                this.isDarkMode() && this.enableDarkMode();
            }
            const headObserver = new MutationObserver(() => {
                this.isDarkMode() && this.enableDarkMode();
            });
            headObserver.observe(document.head, {childList: true, subtree: true});

            if (document.body) {
                this.addButton();
            } else {
                const bodyObserver = new MutationObserver(() => {
                    if (document.body) {
                        bodyObserver.disconnect();
                        this.addButton();
                    }
                });
                bodyObserver.observe(document, {childList: true, subtree: true});
            }
        },

        init() {
            this.initValue();
            this.setThemeColor();
            this.registerMenuCommand();
            if (this.isInExcludeList()) return;
            this.addListener();
            this.firstEnableDarkMode();
        }
    };
    main.init();
})();

 

posted @ 2022-08-19 19:09  CharyGao  阅读(37)  评论(0)    收藏  举报