Skip to content

Commit

Permalink
重构激活链接逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
misiai committed Dec 5, 2020
1 parent 6277cdc commit 0583888
Show file tree
Hide file tree
Showing 7 changed files with 635 additions and 155 deletions.
8 changes: 7 additions & 1 deletion src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,19 @@ export const JUMP_LINK_REG = [// 判断是否是网盘链接,如果是,则
/^((?:https?:\/\/)?cloud\.?189?.cn\/t\/[\w\-_]+)$/ig,
]

export const LINKIFY_REG = [
/(https?:\/\/)?((?:\w+\.)?lanzou.?\.com\/(?:[a-z\d]+))(?:.*?码.*?([a-z\d]+))?/gi,
/(https?:\/\/)?(cloud\.189?\.cn\/t\/(?:[a-z\d]+))(?:.*?码.*?([a-z\d]+))?/gi,
/(https?:\/\/)?((?:pan|e?yun)\.baidu\.com\/s\/(?:[a-z\d\-_]+)(?:#[a-z\d-_]*)?)(?:.*?码.*?([a-z\d]+))?/gi,
]

export const INVALIDATE_LINK_REG = [
/(被取消了|分享文件已过期|已经被删除|分享内容可能因为|啊哦,你来晚了|取消分享了|外链不存在)/ig,
]

export const PARSE_PWD_REG = [
/(https?:\/\/(?:pan|yun|eyun)\.baidu\.com\/s[hare]*\/[int?surl=]*[\w-_]{8,25})[&\w=]*[^\w]*(?:密码|授权码|提取码)*[::]*[^\w]*([\w]{4})*/igm,
/(https?:\/\/(?:\w+)?\.?lanzou.?\.com\/[\w-_]{6,13})\/?[&\w=]*[^\w]*(?:密码|授权码|提取码)*[::]*[^\w]*([\w]{4})*/igm,
/(https?:\/\/(?:\w+)?\.?lanzou.?\.com\/[\w-_]{6,13})\/?[&\w=]*[^\w]*(?:密码|授权码|提取码)*[::]*[^\w]*([\w]{3,})*/igm,
/(https?:\/\/cloud.189.cn\/t\/[\w\-_]+)\/?[^\w]*[((::]*([\w]+)*[))]*/igm,
]
export const URL_REG = /^(https?:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i;
Expand Down
63 changes: 52 additions & 11 deletions src/func.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import {
API_DISK_URL, SEARCH_API_URL, API_TAOKE_COUPON_URL,
API_DISK_URL, SEARCH_API_URL, API_TAOKE_COUPON_URL, ACTIVE_LINK_REG, JUMP_LINK_REG,
PARSE_PWD_REG, BUTTON_TEXT_VIP_VIDEO, BUTTON_TEXT_PARSE_BAIDU,
KEY_LINKS_DIALOG, NOTICE_TEXT_CLOSE_LINK_DIALOG, BUTTON_TEXT_FIND_COUPON,
URL_REG, API_PARSE_BAIDU_URL, VIP_VIDEO_API_URL, BUTTON_TEXT_SETTING, BUTTON_TEXT_HISTORY, BUTTON_TEXT_COUPON, HISTORY_PRICE_URL
} from './config'


import style from './styles/styles.scss'
import { uniqueArr } from './util';

export function selector(dom) {
return document.querySelector(dom);
Expand Down Expand Up @@ -133,8 +134,9 @@ function parseDom(arg) {

// 添加页面链接汇总dom
export function appendLinksDom(linksArr) {
console.log(linksArr);
if (linksArr.length <= 0) return;// 没有东西,就不要创建了
if (document.querySelector('.kuan-links-wrapper')) return;// 已经有了

let open = getValue(KEY_LINKS_DIALOG, 'true')
if (open !== 'true') return;
let dom = `
Expand All @@ -156,15 +158,21 @@ export function appendLinksDom(linksArr) {
let oWrapper = linksDom;
// console.log(oTitle, oLinks, oWrapper);

if (!document.querySelector('.kuan-links-wrapper')) {
document.body.appendChild(oWrapper);
};


oLinks.innerHTML = ''//先清空呀
linksArr.forEach((item, i) => {
console.log(i);
// console.log(i);
let { link, pwd } = item;
let linkDom = `<div class="item"><em>[${i + 1}]</em><a class="kuan-link" href="${link}" target="_blank">${link}</a><span class="pwd">${pwd}</span></div>`;
oLinks.appendChild(parseDom(linkDom));
if (link !== undefined && link !== 'undefined') {
let linkDom = `<div class="item"><em>[${i + 1}]</em><a class="kuan-link" href="${link}" target="_blank">${link}</a><span class="pwd">${pwd}</span></div>`;
oLinks.appendChild(parseDom(linkDom));
}
});

document.body.appendChild(oWrapper);
// 折叠展开
oTitle.addEventListener('click', clickFun);

Expand All @@ -180,9 +188,9 @@ export function appendLinksDom(linksArr) {
l = oWrapper.offsetLeft;
t = oWrapper.offsetTop;
//开关打开
console.log('x', x, 'y', y);
console.log(l, t);
console.log('mouseDown');
// console.log('x', x, 'y', y);
// console.log(l, t);
// console.log('mouseDown');
oTitle.style.cursor = 'move';
window.addEventListener('mousemove', moveFunc)

Expand Down Expand Up @@ -220,6 +228,13 @@ export function appendLinksDom(linksArr) {
}

}
// 场景:有些dom是js动态添加的,但用户点击时,重新获取这些dom里面的看可能存在的link
export function AddLinks(oldLinkArr, aimLink) {
let newArr = [...oldLinkArr, aimLink]
return uniqueArr(newArr)
}



export function parseTitle(title) {
return title.replace(/^【.*】/ig, '');
Expand Down Expand Up @@ -476,31 +491,57 @@ export function unique(arr) {// 去重
}
return arr;
}
// 根据正则解析出网盘链接地址
export function parseLink(html) {
console.log('html', html);
for (let i = 0; i < ACTIVE_LINK_REG.length; i++) {
let res = matchAll(html, ACTIVE_LINK_REG[i]);
console.log('res', res);
for (let j = 0; j < res.length; j++) {
if (res[j].length >= 3 && res[j][2] !== undefined) {
let diskUrl = res[j][1]
console.log('diskUrl', diskUrl);
let [disk_type, disk_id] = getDiskIdAndType(res[j][1]);
// setCompressValue(disk_type, disk_id, getCompressPass());//密码
// console.log('find pwd: ', disk_id, '===>>', res[j][2]);
// setPwdValue(disk_type, disk_id, res[j][2]);
}

// linksArr.push({ link: res[j][1], pwd: res[j][2] || '' });
}
}

}

// 顺带抓取链接后面的密码
// 返回:{ link: res[j][1], pwd: res[j][2] || ''}
export function parsePwd(html) {
/*
0: "https://pan.baidu.com/s/1KpvGklksecWEEAQop1PumQ 提取码: 9g4q"
1: "https://pan.baidu.com/s/1KpvGklksecWEEAQop1PumQ"
2: "9g4q"
groups: undefined */
let linksArr = [];
let cprP = getCompressPass()
for (let i = 0; i < PARSE_PWD_REG.length; i++) {
let res = matchAll(html, PARSE_PWD_REG[i]);
for (let j = 0; j < res.length; j++) {
if (res[j].length >= 3 && res[j][2] !== undefined) {
let [disk_type, disk_id] = getDiskIdAndType(res[j][1]);
setCompressValue(disk_type, disk_id, getCompressPass());//密码
setCompressValue(disk_type, disk_id, cprP);//密码
console.log('find pwd: ', disk_id, '===>>', res[j][2]);
setPwdValue(disk_type, disk_id, res[j][2]);
}

linksArr.push({ link: res[j][1], pwd: res[j][2] || '' });
}
}
appendLinksDom(linksArr);//添加所有链接的节点

return linksArr;
}



export function matchAll(str, reg) {// helper,简单封装匹配函数
let res = [];
let match;
Expand Down
197 changes: 115 additions & 82 deletions src/helper.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
INVALIDATE_LINK_REG,
INVALIDATE_LINK_REG, LINKIFY_REG,
BAIDU_ELEMENT, DISK_INFO_START_WITH, LZ_ELEMENT, VIP_VIDEO_API_URL,
ACTIVE_LINK_REG, URL_REG, LZ_PWD_EXITS_ELEMENT, IS_DISK_URL, TY_ELEMENT,
TYY_PRIVATE_TEXT, SYS_ERROR_NOTICE, QUERY_SUCCESS_NOTICE, PLEASE_INPUT_NOTICE, JUMP_LINK_REG,
Expand All @@ -10,8 +10,8 @@ import {
selector, getPass, getDiskIdAndType, sendPass, appendVipVideoDom,
setValue, getValue, setPwdValue, getPwdValue, getSentValue, setSentValue,
mactchReplaceHtml, parsePwd, sendInvalidate, activeAnyLink, parseTitle,
appendCouponQrCode,
appendBaiduParseDom, appendSettingDom, appendCouponDom, appendHistoryDom,
appendCouponQrCode, parseLink,
appendBaiduParseDom, appendSettingDom, appendCouponDom, appendHistoryDom, linkify, appendLinksDom, AddLinks,
} from './func'

import { jumpUrl, parseItemId } from './util';
Expand Down Expand Up @@ -291,89 +291,122 @@ export function OtherPage(config) {

let { href } = config;


parsePwd(document.body.innerText);//先分析下密码

//点击激活链接
document.body.addEventListener('click', (ev) => {
if (ev.target !== document.body) {//不是点击的body
let html = ev.target.innerHTML;

if (ev.target.nodeName.toLowerCase() === 'a') return;//A标签排除在外!

// console.log('ev.target: ', ev.target);
// console.log('ev.target.nodeName: ', ev.target.nodeName.toLowerCase());
// console.log('ev.target.hasChildNodes: ', ev.target.hasChildNodes());
// console.log('ev.target.childNodes: ', ev.target.childNodes);

// document.nodeName


console.log('ev.target', ev.target);
// console.log('click html:', html);
let kuanLinks = document.querySelectorAll('.kuan-link');
let kuanLinksWrapper = document.querySelector('.kuan-links');
console.log('kuanLinksWrapper', kuanLinksWrapper);
console.log('kuanLinks', kuanLinks);
for (const item of kuanLinks) {
if (item === ev.target) return;
// Array.prototype.slice.call(document.querySelectorAll(
// "a[href*='pan.baidu.com'], a[href*='lanzou'], a[href*='lanzoui.com'], a[href*='lanzous.com'], a[href*='lanzoux.com']"
// )).forEach(function (link) {
// let txt = link.nextSibling && link.nextSibling.nodeValue;
// console.log('link', link);
// console.log('txt', txt);
// parseLink(link)
// let linkcode = /码.*?([a-z\d]{4})/i.exec(txt) && RegExp.$1;

// if (!linkcode) {
// txt = link.parentNode.innerText;
// linkcode = /码.*?([a-z\d]{4})/i.exec(txt) && RegExp.$1;
// }

// });

let linkArr = parsePwd(document.body.innerText);//先分析下密码
appendLinksDom(linkArr)

// document.addEventListener('click', (ev) => {
// if (ev.target === document.body) return
// linkArr = AddLinks(linkArr, parsePwd(ev.target.innerText))
// appendLinksDom(linkArr)
// })



/*
以下代码,参考自:https://greasyfork.org/zh-CN/scripts/18733-%E7%BD%91%E7%9B%98%E6%8F%90%E5%8F%96%E5%B7%A5%E5%85%B7/code
*/
let CODE_RULE_COMMON = /^([a-z\d]{3,})$/i;
let MAX_SEARCH_CODE_RANGE = 5;
//functions...
let textNodesUnder = function (el) {
let n, a = [],
walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false);
while ((n = walk.nextNode())) {
if (n.nodeName === '#text')
a.push(n);
}
return a;
};
let generalLinkifyText = function (source, eles, index, testReg, validateRule) {
let count = 0,
text = source,
match;
while ((match = testReg.exec(source))) {
count++;

let url = (match[1] || "http://") + match[2];
let originalText = (match[1] || "") + match[2];
let code = match[3] || findCodeFromElements(eles, index, validateRule) || "";
url = url.split('#')[0];
text = text.replace(originalText, "<a href='" + url + "#" + code + "' target='_blank'>" + url + '</a>');
}
return {
count,
text
};
};
let findCodeFromElements = function (eles, index, rule) {
for (let i = 0; i < MAX_SEARCH_CODE_RANGE && i < eles.length; i++) {
let txt = null
try {
txt = eles[i + index].textContent || '';
}
if (ev.target === kuanLinksWrapper) return;//自己的框框不能装
// console.log('inner html', html);
// console.log('html', typeof ev.target);
parsePwd(ev.target.innerText);//顺带要获取下密码

if (URL_REG.test(html)) {//匹配到了纯网址点击

for (let i = 0; i < JUMP_LINK_REG.length; i++) {
let reg = JUMP_LINK_REG[i]
if (reg.test(html)) {
GM_log('jump url: ', html)
jumpUrl(html)
return
}
}

// if (!IS_DISK_URL.test(html)) {
// ev.target.innerHTML = activeAnyLink(html);
// return;//就不再往下执行了,因为不是网盘地址
// }
// let body = document.body.innerHTML
// if (body.split(html).length - 1 < 2) {
// console.log('loop active');
// loopToActive(html, ev, true);
// } else {
// return;
// }

let l = html.length * 3;
let body = document.body.innerHTML
let r = new RegExp(html, 'ig').exec(body)
if (r) {
let cut_body = body.substring(r.index - l, r.index + l);
if (cut_body.split(html).length - 1 < 2) {
console.log('loop active');
loopToActive(html, ev, true);
} else {
return;
}
}

catch (e) {
continue
}
loopToActive(html, ev);

let codeReg = /码.*?([a-z\d]+)/gi;
let codeMatch = codeReg.exec(txt) && RegExp.$1;
if (!codeMatch) continue;
let linkTestReg = /(https?:|\.(net|cn|com|gov|cc|me))/gi;
if (linkTestReg.exec(txt) && linkTestReg.lastIndex <= codeReg.lastIndex) {
break;
}
if (rule.test(codeMatch)) return codeMatch;
}
});

// 通过正则循环激活链接
function loopToActive(html, ev, tag = false) {
for (let i = 0; i < ACTIVE_LINK_REG.length; i++) {
let [isMatch, newHtml] = mactchReplaceHtml(html, ACTIVE_LINK_REG[i], tag);
if (isMatch) {
ev.target.innerHTML = newHtml;
return null;
};
let linkify = function () {
let eles = textNodesUnder(document.body);
let processor = [];
for (let m = 0; m < LINKIFY_REG.length; m++) {
processor.push(
function (...args) {
return generalLinkifyText(...[
...args,
LINKIFY_REG[m],
CODE_RULE_COMMON
]);
}
)
}
for (let i = 0; i < eles.length; i++) {
let ele = eles[i];
if (ele.parentNode.tagName == 'a' || !ele.textContent) continue;

let txt = ele.textContent;
let loopCount = 0;

for (var action of processor) {
let {
count,
text
} = action(txt, eles, i + 1);
loopCount += count;
txt = text;
}
if (loopCount > 0) {
var span = document.createElement("span");
span.innerHTML = txt;
ele.parentNode.replaceChild(span, ele);
}
}
}

};

linkify()
}
Loading

0 comments on commit 0583888

Please sign in to comment.