磁力链接百度网盘补完

磁力链接、百度网盘补完

// ==UserScript==
// @name         磁力链接百度网盘补完
// @namespace    http://tampermonkey.net/
// @version      2.10
// @description  磁力链接、百度网盘补完
// @author       backrock12
// @include      *
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_getValue
// @require      http://libs.baidu.com/jquery/2.0.0/jquery.min.js
// @exclude      /(^[^:\/#\?]*:\/\/([^#\?\/]*\.)?www\.gamersky\.com(:[0-9]{1,5})?\/.*$)/
// @exclude      /(^[^:\/#\?]*:\/\/([^#\?\/]*\.)?www\.baidu\.com(:[0-9]{1,5})?\/.*$)/
// @exclude      /(^[^:\/#\?]*:\/\/([^#\?\/]*\.)?www\.ciweimao\.com(:[0-9]{1,5})?\/.*$)/

// ==/UserScript==

(function () {
  'use strict';


  console.log("UrlLinePlugin");

  //字符串格式化方法
  String.prototype.UrlLineformat = function (args) {
    var result = this;
    if (arguments.length > 0) {
      if (arguments.length == 1 && typeof args == "object") {
        for (var key in args) {
          if (args[key] != undefined) {
            var reg = new RegExp("({" + key + "})", "g");
            result = result.replace(reg, args[key]);
          }
        }
      } else {
        for (var i = 0; i < arguments.length; i++) {
          if (arguments[i] != undefined) {
            var reg = new RegExp("({)" + i + "(})", "g");
            result = result.replace(reg, arguments[i]);
          }
        }
      }
    }
    return result;
  };


  $.fn.replaceText = function (search, replace, action, text_only) {
    return this.each(function () {
      var node = this.firstChild,
        val,
        new_val,// Elements to be removed at the end.
        remove = [];

      if (node) {
        do {
          if (node.nodeType === 3) {
            val = node.nodeValue;
            if (val) {
              if (!action && replace) {
                new_val = val.replace(search, replace);
              }
              else {
                var t = search.exec(val)
                if (action && t && t.length > 0)
                  new_val = action(node, val, t);
                else
                  new_val = val;
              }
              if (new_val !== val) {
                if (!text_only && /</.test(new_val)) {
                  $(node).before(new_val);
                  remove.push(node);
                } else {
                  node.nodeValue = new_val;
                }
              }
            }
          }
        } while (node = node.nextSibling);
      }
      remove.length && $(remove).remove();
    });
  };


  //默认配置参数  default settings
  var default_settings = {
    magnetPattern2: /((\u672c\u7ad9\u6682?\u4e0d\u63d0\u4f9b(\u6587\u4ef6)?\u4e0b\u8f7d))|(不提供(文件)?下载)/g,
    magnetPattern: /(magnet:\?)?(xt=)?(urn:btih:)?(?=.{0,31}[0-9])(?=.{0,31}[a-z])([0-9A-Z]{32,40})(?![:.\-\!\?a-z0-9])/gi,
    pixivurl: "<a href='https://www.pixiv.net/member_illust.php?mode=medium&illust_id={0}' target='_blank'>{1}</a>",
    bilibiliurl: "<a href='https://www.bilibili.com/video/av{0}/' target='_blank'>{1}</a>",
    magneturl: "<a href='magnet:?xt=urn:btih:{0}' target='_blank' urlline='true'>magnet:?xt=urn:btih:{1}</a>",
    baiduurl1: "<a href='https://pan.baidu.com/s/1{0}' target='_blank' urlline='true'>" + " https://pan.baidu.com/s/1{1} </a>",
    baiduurl2: "<a href='https://pan.baidu.com/s/1{0}#{1}' target='_blank' urlline='true' >{2}</a>",
    baiduurl3: "<a href='https://pan.baidu.com/s/1{0}' target='_blank' urlline='true' >{1}</a>",
    baiduurl4: "<a href='https://pan.baidu.com/s/1{0}#{1}' target='_blank' urlline='true' > https://pan.baidu.com/s/1{2}#{3} </a>",
    baiduPattern0: /((https?:\/\/)?pan\.baidu\.com\/s\/1([a-zA-Z0-9_\-]{5,22})|(https?:\/\/)?pan\.baidu\.com\/share\/init\?surl=([a-zA-Z0-9_\-]{5,22})|[^a-zA-Z]s\/1([a-zA-Z0-9_\-]{5,22})|\bs\/1([a-zA-Z0-9_\-]{5,22}))/,
    baiduPattern1: /(https?:\/\/)?pan\.baidu\.com\/s\/1([a-zA-Z0-9_\-]{5,22})/,
    baiduPattern2: /(https?:\/\/)?pan\.baidu\.com\/share\/init\?surl=([a-zA-Z0-9_\-]{5,22})/,
    baiduPattern3: /\/?s\/1([a-zA-Z0-9_\-]{5,22})/,
    baiduPattern4: /\/?s?\/?1([a-zA-Z0-9_\-]{5,22})(?!\.)/,
    common_reg1: /\s*(提取密碼|提取密码|提取码|提取碼|提取|密碼|密码|百度|百度云|云盘|yun|通关口令|本帖隐藏的内容)[::]?\s*(<[^>]+>)?\s*([0-9a-zA-Z]{4,})\s*/,
    common_reg2: /\s*(百度网盘密码|提取密碼|提取密码|提取码|提取碼|提取|密碼|密码|百度|百度云|云盘|yun|通关口令|本帖隐藏的内容)[::]?\s*/,
    common_reg3: /\s*(<[^>]+>)?\s*([0-9a-zA-Z]{4,})\s*/,
    common_reg4: /[::]?\s*(<[^>]+>)?\s*([0-9a-zA-Z]{4,8})/,
    common_r: "\\s*({0})[::]?\\s*(<[^>]+>)?\\s*([0-9a-zA-Z]{4,})\\s*",
    url_reg: /(http|https):\/\/(www.)?(\w+(\.)?)+/,
    Pwnum: 5
  };


  function FormatGet(key) {
    if (key == 'DownUrl') {
      if (!arguments[3]) {
        return default_settings.baiduurl1.UrlLineformat(arguments[2], arguments[2]);
      } else {
        return default_settings.baiduurl2.UrlLineformat(arguments[2], arguments[3], arguments[3]);
      }
    } else if (key == 'Url') {
      return default_settings.baiduurl3.UrlLineformat(arguments[0], arguments[1]);
    } else if (key == 'baiduurl4') {
      if (!arguments[2]) {
        return default_settings.baiduurl1.UrlLineformat(arguments[1], arguments[1]);
      } else {
        return default_settings.baiduurl4.UrlLineformat(arguments[1], arguments[2], arguments[1], arguments[2]);
      }

    }

  }

  function SettingCheck(key, value) {
    if (key == 'baiduPattern0') {
      return default_settings.baiduPattern0.test(value)
    } else if (key == 'common_reg2') {
      return default_settings.common_reg2.test(value)
    }
  }

  function SettingGet(key, value) {
    let ss;
    if (key == 'common_reg4') {
      return (ss = default_settings.common_reg4.exec(value)) && 3 === ss.length ? ss[2] : null;
    } else if (key == 'common_reg3') {
      return (ss = default_settings.common_reg3.exec(value)) && 3 === ss.length ? ss[2] : null;
    } else if (key == 'common_reg1') {
      return (ss = default_settings.common_reg1.exec(value)) && 4 === ss.length ? ss[3] : null;
    } else if (key == 'baiduPattern0') {
      ss = default_settings.baiduPattern0.exec(value);
      return ss[3] ? ss[3] : (ss[5] ? ss[5] : (ss[6] ? ss[6] : ss[7]));
    } else if (key == 'baiduPattern4') {
      return (ss = default_settings.baiduPattern4.exec(value)) && 2 === ss.length ? ss[1] : null;
    }
  }

  function Getnextnode(node) {
    var loopnum = default_settings.Pwnum;
    var bnode;
    if (Desc_Mk) {
      bnode = node == node.previousSibling ? null : node.previousSibling;
    } else {
      bnode = node == node.nextSibling ? null : node.nextSibling;
    }
    if (!bnode) bnode = Desc_Mk ? node.parentNode.previousSibling : node.parentNode.nextSibling;
    while (node && !bnode && loopnum >= 0) {
      bnode = Desc_Mk ? node.previousSibling : node.nextSibling;
      node = node.parentNode;
      loopnum--;
    }
    return bnode;
  }

  function FindNextPw(node, Pid) {
    var loopnum = default_settings.Pwnum;
    var bnode = Getnextnode(node);
    var isreg2 = false;
    if (bnode) {
      do {
        var bh = bnode.nodeValue ? bnode.nodeValue : bnode.outerHTML;
        var bt = bnode.nodeValue ? bnode.nodeValue : bnode.innerText;
        if (bnode && bt) {
          if (SettingCheck('baiduPattern0', bt)) break;
          var pw = SettingGet('common_reg1', bt);
          if (isreg2) pw = SettingGet('common_reg3', bt);
          if (pw != null) {
            var retext = FormatGet('DownUrl', '', Pid, pw);
            var h = bh.replace(pw, retext);
            $(bnode).replaceWith(h);
            //$(bnode).remove();
            break;
          } else {
            if (SettingCheck('common_reg2', bt)) isreg2 = !isreg2;
          }
        }
        bnode= Getnextnode(bnode);
        if (!bnode) break;
        loopnum--;
      } while (loopnum >= 0);
    }
  }

  function ReplaceorPw(node, e, n) {
    var Pid = SettingGet('baiduPattern0', n[0]);
    if (!Pid) return e;
    var retext = FormatGet('DownUrl', n[0], Pid);
    var v = e.replace(n[0], retext);
    var pw = SettingGet('common_reg1', e);
    var ischeck = false;
    if (!pw) {
      var s = e.substring(e.indexOf(Pid) + Pid.length);
      if (SettingCheck('baiduPattern0', s)) {
        ischeck = true;
      }
      else {
        pw = SettingGet('common_reg4', s);
      }
    }
    if (pw) {
      var retext2 = FormatGet('DownUrl', '', Pid, pw);
      v = v.replace(pw, retext2);
    } else {
      FindNextPw(node, Pid);
    }
    if (ischeck) {
      v = ReplaceorPw(node, v, [s]);
    }
    return v;
  }


  function UrlLinePlugin(options) {
    this.settings = $.extend({}, default_settings, options);
    this._defaults = default_settings;
    this.init();
  }

  var ULSetting;
  var Desc_Mk = false;
  var MenuID;

  UrlLinePlugin.prototype = {
    init: function () {
      console.log('init');
      ULSetting = GM_getValue('UrlLineSetting');
      if (!ULSetting) ULSetting = { DescUrl: [] };
      console.log(ULSetting);

      if (ULSetting.DescUrl && ULSetting.DescUrl.length > 0) {
        var DescTxt = `(${ULSetting.DescUrl.join('|')})`;
        var DescUrlReg = new RegExp(DescTxt);
        if (DescUrlReg.test(location.href)) Desc_Mk = true;
      }
      console.log(Desc_Mk);

      if (Desc_Mk) {
        MenuID = GM_registerMenuCommand('取消反向查找', OffDescUrl);
      }
      else {
        MenuID = GM_registerMenuCommand('设置反向查找', OnDescUrl);
      }

      function OnDescUrl() {
        var urls = location.href.match(default_settings.url_reg);
        if (urls) {
          if (!ULSetting.DescUrl) {
            ULSetting.DescUrl = [urls[0]];
          } else {
            ULSetting.DescUrl = ULSetting.DescUrl.concat(urls[0]);
          }
          GM_setValue('UrlLineSetting', ULSetting);
          GM_unregisterMenuCommand(MenuID);
          MenuID = GM_registerMenuCommand('取消反向查找', OffDescUrl);
          console.log(ULSetting);
        } else {
          console.log('OnDescUrl 获取URL失敗');
        }
      }

      function OffDescUrl() {
        var urls = location.href.match(default_settings.url_reg);
        if (urls) {
          var index = ULSetting.DescUrl.indexOf(urls[0]);
          if (index > -1) {
            ULSetting.DescUrl.splice(index, 1);
            GM_setValue('UrlLineSetting', ULSetting);
            GM_unregisterMenuCommand(MenuID);
            MenuID = GM_registerMenuCommand('设置反向查找', OnDescUrl);
          }
          console.log(ULSetting);
        } else {
          console.log('OffDescUrl 获取URL失敗');
        }
      }




    },
    Star: function () {
      var t = this;
      this.init();
      console.log("star");
      if (/tieba\.baidu\.com/.test(location.href)) {
        setTimeout(function () {
          console.log("tieba");
          t.StarReplace.call(t);
        }, 2000);
      } else {
        t.StarReplace.call(t);
      }

      document.addEventListener("keydown", function (e) {
        /* CTR + Z */
        if (e.keyCode == 90 && e.ctrlKey) {
          t.StarReplace.call(t);
        } else if (e.keyCode == 88 && e.ctrlKey) {
          t.BaiduFilter(t);
        }
      });

    },
    StarReplace: function () {
      var obj = this;
      obj.MagnetReplace(obj);
      obj.BaiduReplace(obj);
    },

    MagnetReplace: function (obj) {
      try {
        obj._subMagnetReplace(obj);
      } catch (err) {
        console.log("Magnet replace Error:" + err.message);
      }
    },

    BaiduReplace: function (obj) {

      try {
        if (/pan\.baidu\.com/.test(location.href)) {
          console.log("baiduPassword");
          // $(".file-name").css('white-space','inherit');
          $("[class*='global-icon-16']").css('float', 'left');
          //填寫密碼
          if (location.hash && location.hash.length == 5) {
            var pwinput = $(".QKKaIE");
            if (!pwinput)
              pwinput = $(":contains('请输入提取码'):last").nextAll("input");
            if (!pwinput)
              pwinput = $(":contains('请输入提取码'):last").next().find("input");
            pwinput.val(location.hash.slice(1, 5));

            setTimeout(function () {
              var pwbtn = $("a:contains('提取文件')");
              pwbtn.click();
            }, 50);
          }
          obj.AddPWButton();

        } else {
          obj._subBaiduReplace(obj);
        }
      } catch (err) {
        console.log("baidu replace Error:" + err.message);
      }
    },

    _subMagnetReplace: function (obj) {
      $("*").replaceText(default_settings.magnetPattern2, "");
      function magnetReplacer(match, p1, p2, p3, p4) {
        var value = match.replace("magnet:?", "").replace("xt=", "").replace("urn:btih:", "");
        return default_settings.magneturl.UrlLineformat(value, match);
      }
      $("*").not("script").not("a[urlline='true']").replaceText(default_settings.magnetPattern, magnetReplacer);
      console.log(location.href + "is magnet replace");
    },

    _subBaiduReplace: function (obj) {

      $("*").not("script").not("a").replaceText(default_settings.baiduPattern0,
        function (match, p1, p2, p3) {
          var Pid = SettingGet('baiduPattern0', match);
          return FormatGet('Url', Pid, match);
        },
        ReplaceorPw);

      $("a[urlline!='true']").each(function () {
        var h = $(this).attr("href");
        if (SettingCheck('baiduPattern0', h)) {
          var Pid = SettingGet('baiduPattern0', h);
          FindNextPw(this, Pid);
        } else {
          if (/\.bdimg.com/.test(h)) {
            var t = $(this).text()
            if (SettingCheck('baiduPattern0', t)) {
              var tPid = SettingGet('baiduPattern0', t);
              FindNextPw(this, tPid);
            }
          }
        }
      });
      console.log(location.href + "is baidu replace");
    },

    BaiduFilter: function (obj) {
      var r = window.getSelection();
      if (r.rangeCount > 0) {
        for (var i = 0; i < r.rangeCount; i++) {
          var s = r.getRangeAt(i);
          var seltext = s.toString();
          console.log('Selection' + seltext);
          var filtertext = seltext.replace(/([\u4e00-\u9fa5]|[::??!!])+/, '');
          var Pid, purl, pw;
          if (SettingCheck('baiduPattern0', filtertext)) {
            Pid = SettingGet('baiduPattern0', filtertext);
          }
          if (!Pid)
            Pid = SettingGet('baiduPattern4', filtertext);


          if (Pid) {
            var lasttext = $.trim(filtertext.substring(filtertext.indexOf(Pid) + Pid.length));
            if (lasttext) {
              pw = SettingGet('common_reg1', lasttext);
              if (!pw)
                pw = SettingGet('common_reg4', lasttext);
            }
            purl = FormatGet('baiduurl4', Pid, pw)
          }

          if (purl) {
            var a = $(purl)[0];
            try {
              s.insertNode(a);
              var span = $('<span style="color:#A9A9A9"></span>')[0];
              s.surroundContents(span);//将创建的元素环绕在光标选中的文字周围
              s.collapse(false);
              console.log('Selection Success' + s);
            } catch (e) {
              console.log('Selection Error' + e.message);
            }
          }
        }
      }

    },

    AddPWButton: function () {
      console.log('AddPWButton');

      $('div.slide-show-right').css('width', '500px');
      var Pbutton = $('<span class="g-dropdown-button"></span>');
      var button_a = $('<a class="g-button g-button-blue" data-button-id="b200" data-button-index="200" href="javascript:void(0);"></a>');
      var button_a_span = $('<span class="g-button-right"><em class="icon icon-download" title="跳转到PanDownload"></em><span class="text" style="width: 60px;">PanDown</span></span>');
      var Pbutton_span = $('<span class="menu" style="width:auto;z-index:41"></span>');

      button_a.append(button_a_span);
      Pbutton.append(button_a).append(Pbutton_span);
      Pbutton.click(function () {
        let url = window.location.href;
        url = url.replace('baidu.com', 'baiduwp.com');
        window.open(url, "_blank");
      });
      $('div.module-share-top-bar div.bar div.x-button-box').append(Pbutton);
      //Pbutton.insertBefore($("a:contains('请输入提取码')"));
    }

  };


  var e = new UrlLinePlugin();
  e.Star();



})();