怠惰小说下载器

通用网站内容抓取工具,可批量抓取任意站点的小说、论坛内容等并保存为TXT文档

目前为 2023-11-27 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name DownloadAllContent
  3. // @name:zh-CN 怠惰小说下载器
  4. // @name:zh-TW 怠惰小説下載器
  5. // @name:ja 怠惰者小説ダウンロードツール
  6. // @namespace hoothin
  7. // @version 2.7.9
  8. // @description Fetch and download main textual content from the current page, provide special support for novels
  9. // @description:zh-CN 通用网站内容抓取工具,可批量抓取任意站点的小说、论坛内容等并保存为TXT文档
  10. // @description:zh-TW 通用網站內容抓取工具,可批量抓取任意站點的小說、論壇內容等並保存為TXT文檔
  11. // @description:ja ユニバーサルサイトコンテンツクロールツール、クロール、フォーラム内容など
  12. // @author hoothin
  13. // @match http://*/*
  14. // @match https://*/*
  15. // @match ftp://*/*
  16. // @grant GM_xmlhttpRequest
  17. // @grant GM_registerMenuCommand
  18. // @grant GM_setValue
  19. // @grant GM_getValue
  20. // @grant GM_openInTab
  21. // @grant GM_setClipboard
  22. // @grant GM_addStyle
  23. // @grant unsafeWindow
  24. // @license MIT License
  25. // @compatible chrome
  26. // @compatible firefox
  27. // @compatible opera 未测试
  28. // @compatible safari 未测试
  29. // @contributionURL https://ko-fi.com/hoothin
  30. // @contributionAmount 1
  31. // ==/UserScript==
  32.  
  33. if (window.top != window.self) {
  34. try {
  35. if (window.self.innerWidth < 250 || window.self.innerHeight < 250) {
  36. return;
  37. }
  38. } catch(e) {
  39. return;
  40. }
  41. }
  42.  
  43. (function (global, factory) {
  44. if (typeof define === "function" && define.amd) {
  45. define([], factory);
  46. } else if (typeof exports !== "undefined") {
  47. factory();
  48. } else {
  49. var mod = {
  50. exports: {}
  51. };
  52. factory();
  53. global.FileSaver = mod.exports;
  54. }
  55. })(this, function () {
  56. "use strict";
  57.  
  58. /*
  59. * FileSaver.js
  60. * A saveAs() FileSaver implementation.
  61. *
  62. * By Eli Grey, http://eligrey.com
  63. *
  64. * License : https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md (MIT)
  65. * source : http://purl.eligrey.com/github/FileSaver.js
  66. */
  67. var _global = typeof window === 'object' && window.window === window ? window : typeof self === 'object' && self.self === self ? self : typeof global === 'object' && global.global === global ? global : void 0;
  68.  
  69. function bom(blob, opts) {
  70. if (typeof opts === 'undefined') opts = {
  71. autoBom: false
  72. };else if (typeof opts !== 'object') {
  73. console.warn('Deprecated: Expected third argument to be a object');
  74. opts = {
  75. autoBom: !opts
  76. };
  77. }
  78.  
  79. if (opts.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  80. return new Blob([String.fromCharCode(0xFEFF), blob], {
  81. type: blob.type
  82. });
  83. }
  84.  
  85. return blob;
  86. }
  87.  
  88. function download(url, name, opts) {
  89. var xhr = new XMLHttpRequest();
  90. xhr.open('GET', url);
  91. xhr.responseType = 'blob';
  92.  
  93. xhr.onload = function () {
  94. saveAs(xhr.response, name, opts);
  95. };
  96.  
  97. xhr.onerror = function () {
  98. console.error('could not download file');
  99. };
  100.  
  101. xhr.send();
  102. }
  103.  
  104. function corsEnabled(url) {
  105. var xhr = new XMLHttpRequest();
  106.  
  107. xhr.open('HEAD', url, false);
  108.  
  109. try {
  110. xhr.send();
  111. } catch (e) {}
  112.  
  113. return xhr.status >= 200 && xhr.status <= 299;
  114. }
  115.  
  116.  
  117. function click(node) {
  118. try {
  119. node.dispatchEvent(new MouseEvent('click'));
  120. } catch (e) {
  121. var evt = document.createEvent('MouseEvents');
  122. evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
  123. node.dispatchEvent(evt);
  124. }
  125. }
  126.  
  127.  
  128. var isMacOSWebView = _global.navigator && /Macintosh/.test(navigator.userAgent) && /AppleWebKit/.test(navigator.userAgent) && !/Safari/.test(navigator.userAgent);
  129. var saveAs = _global.saveAs || (
  130. typeof window !== 'object' || window !== _global ? function saveAs() {}
  131.  
  132. : 'download' in HTMLAnchorElement.prototype && !isMacOSWebView ? function saveAs(blob, name, opts) {
  133. var URL = _global.URL || _global.webkitURL;
  134. var a = document.createElement('a');
  135. name = name || blob.name || 'download';
  136. a.download = name;
  137. a.rel = 'noopener';
  138.  
  139. if (typeof blob === 'string') {
  140. a.href = blob;
  141.  
  142. if (a.origin !== location.origin) {
  143. corsEnabled(a.href) ? download(blob, name, opts) : click(a, a.target = '_blank');
  144. } else {
  145. click(a);
  146. }
  147. } else {
  148. a.href = URL.createObjectURL(blob);
  149. setTimeout(function () {
  150. URL.revokeObjectURL(a.href);
  151. }, 4E4);
  152.  
  153. setTimeout(function () {
  154. click(a);
  155. }, 0);
  156. }
  157. }
  158. : 'msSaveOrOpenBlob' in navigator ? function saveAs(blob, name, opts) {
  159. name = name || blob.name || 'download';
  160.  
  161. if (typeof blob === 'string') {
  162. if (corsEnabled(blob)) {
  163. download(blob, name, opts);
  164. } else {
  165. var a = document.createElement('a');
  166. a.href = blob;
  167. a.target = '_blank';
  168. setTimeout(function () {
  169. click(a);
  170. });
  171. }
  172. } else {
  173. navigator.msSaveOrOpenBlob(bom(blob, opts), name);
  174. }
  175. }
  176. : function saveAs(blob, name, opts, popup) {
  177. popup = popup || open('', '_blank');
  178.  
  179. if (popup) {
  180. popup.document.title = popup.document.body.innerText = 'downloading...';
  181. }
  182.  
  183. if (typeof blob === 'string') return download(blob, name, opts);
  184. var force = blob.type === 'application/octet-stream';
  185.  
  186. var isSafari = /constructor/i.test(_global.HTMLElement) || _global.safari;
  187.  
  188. var isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
  189.  
  190. if ((isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== 'undefined') {
  191. var reader = new FileReader();
  192.  
  193. reader.onloadend = function () {
  194. var url = reader.result;
  195. url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, 'data:attachment/file;');
  196. if (popup) popup.location.href = url;else location = url;
  197. popup = null;
  198. };
  199.  
  200. reader.readAsDataURL(blob);
  201. } else {
  202. var URL = _global.URL || _global.webkitURL;
  203. var url = URL.createObjectURL(blob);
  204. if (popup) popup.location = url;else location.href = url;
  205. popup = null;
  206.  
  207. setTimeout(function () {
  208. URL.revokeObjectURL(url);
  209. }, 4E4);
  210. }
  211. });
  212. _global.saveAs = saveAs.saveAs = saveAs;
  213.  
  214. if (typeof module !== 'undefined') {
  215. module.exports = saveAs;
  216. }
  217. });
  218.  
  219. (function() {
  220. 'use strict';
  221. var indexReg=/^(\w.*)?PART\b|^Prologue|^(\w.*)?Chapter\s*[\-_]?\d+|分卷|^序$|^序\s*[·言章]|^前\s*言|^附\s*[录錄]|^引\s*[言子]|^摘\s*要|^[楔契]\s*子|^后\s*记|^後\s*記|^附\s*言|^结\s*语|^結\s*語|^尾\s*[声聲]|^最終話|^最终话|^番\s*外|^\d+[\s\.、,,)\-_::][^\d#\.]|^(\d|\s|\.)*[第(]?\s*[\d〇零一二两三四五六七八九十百千万萬-]+\s*[、)章节節回卷折篇幕集话話]/i;
  222. var innerNextPage=/^\s*(下一[页頁张張]|next\s*page|次のページ)/i;
  223. var lang = navigator.appName=="Netscape"?navigator.language:navigator.userLanguage;
  224. var i18n={};
  225. var rCats=[];
  226. var processFunc;
  227. var win=(typeof unsafeWindow=='undefined'? window : unsafeWindow);
  228. switch (lang){
  229. case "zh-CN":
  230. case "zh-SG":
  231. i18n={
  232. fetch:"开始下载小说【Ctrl+F9】",
  233. info:"来源:#t#\n本文是使用怠惰小说下载器(DownloadAllContent)下载的",
  234. error:"该段内容获取失败",
  235. downloading:"已下载完成 %s 段,剩余 %s 段<br>正在下载 %s",
  236. complete:"已全部下载完成,共 %s 段",
  237. del:"设置文本干扰码的CSS选择器",
  238. custom:"自定规则下载",
  239. customInfo:"输入网址或者章节CSS选择器",
  240. reSort:"按标题名重新排序章节",
  241. reSortUrl:"按网址重新排序章节",
  242. setting:"选项参数设置",
  243. searchRule:"搜索网站规则",
  244. abort:"跳过此章",
  245. save:"保存当前",
  246. saveAsMd:"存为 Markdown",
  247. downThreadNum:"设置同时下载的线程数",
  248. customTitle:"自定义章节标题,输入内页文字对应选择器",
  249. reSortDefault:"默认按页面中位置排序章节",
  250. reverseOrder:"反转章节排序",
  251. saveBtn:"保存设置",
  252. saveOk:"保存成功",
  253. nextPage:"嗅探章节内分页",
  254. nextPageReg:"自定义分页正则",
  255. retainImage:"保留正文中图片的网址",
  256. minTxtLength:"当检测到的正文字数小于此数,则尝试重新抓取",
  257. showFilterList:"下载前显示章节筛选排序窗口",
  258. ok:"确定",
  259. close:"关闭",
  260. dacSortByPos:"按页内位置排序",
  261. dacSortByUrl:"按网址排序",
  262. dacSortByName:"按章节名排序",
  263. reverse:"反选",
  264. dacUseIframe:"使用 iframe 后台加载内容(慢速)",
  265. dacSaveAsZip:"下载为 zip",
  266. dacSetCustomRule:"修改规则",
  267. dacAddUrl:"添加章节",
  268. dacStartDownload:"下载选中"
  269. };
  270. break;
  271. case "zh-TW":
  272. case "zh-HK":
  273. i18n={
  274. fetch:"開始下載小說【Ctrl+F9】",
  275. info:"來源:#t#\n本文是使用怠惰小說下載器(DownloadAllContent)下載的",
  276. error:"該段內容獲取失敗",
  277. downloading:"已下載完成 %s 段,剩餘 %s 段<br>正在下載 %s",
  278. complete:"已全部下載完成,共 %s 段",
  279. del:"設置文本干擾碼的CSS選擇器",
  280. custom:"自訂規則下載",
  281. customInfo:"輸入網址或者章節CSS選擇器",
  282. reSort:"按標題名重新排序章節",
  283. reSortUrl:"按網址重新排序章節",
  284. setting:"選項參數設定",
  285. searchRule:"搜尋網站規則",
  286. abort:"跳過此章",
  287. save:"保存當前",
  288. saveAsMd:"存爲 Markdown",
  289. downThreadNum:"設置同時下載的綫程數",
  290. customTitle:"自訂章節標題,輸入內頁文字對應選擇器",
  291. reSortDefault:"預設依頁面中位置排序章節",
  292. reverseOrder:"反轉章節排序",
  293. saveBtn:"儲存設定",
  294. saveOk:"儲存成功",
  295. nextPage:"嗅探章節內分頁",
  296. nextPageReg:"自訂分頁正規",
  297. retainImage:"保留內文圖片的網址",
  298. minTxtLength:"當偵測到的正文字數小於此數,則嘗試重新抓取",
  299. showFilterList:"下載前顯示章節篩選排序視窗",
  300. ok:"確定",
  301. close:"關閉",
  302. dacSortByPos:"依頁內位置排序",
  303. dacSortByUrl:"依網址排序",
  304. dacSortByName:"依章節名排序",
  305. reverse:"反選",
  306. dacUseIframe:"使用 iframe 背景載入內容(慢速)",
  307. dacSaveAsZip:"下載為 zip",
  308. dacSetCustomRule:"修改規則",
  309. dacAddUrl:"新增章節",
  310. dacStartDownload:"下載選取"
  311. };
  312. break;
  313. default:
  314. i18n={
  315. fetch:"Download [Ctrl+F9]",
  316. info:"Source: #t#\nThe TXT is downloaded by 'DownloadAllContent'",
  317. error:"Failed in downloading current chapter",
  318. downloading:"%s pages are downloaded, there are still %s pages left<br>Downloading %s ......",
  319. complete:"Completed! Get %s pages in total",
  320. del:"Set css selectors for ignore",
  321. custom:"Custom to download",
  322. customInfo:"Input urls OR sss selectors for chapter links",
  323. reSort:"ReSort by title",
  324. reSortUrl:"Resort by URLs",
  325. setting:"Open Setting",
  326. searchRule:"Search rule",
  327. abort:"Abort",
  328. save:"Save",
  329. saveAsMd:"Save as Markdown",
  330. downThreadNum:"Set threadNum for download",
  331. customTitle: "Customize the chapter title, enter the selector on inner page",
  332. reSortDefault: "Default sort by position in the page",
  333. reverseOrder:"Reverse chapter ordering",
  334. saveBtn:"Save Setting",
  335. saveOk:"Save Over",
  336. nextPage:"Check next page in chapter",
  337. nextPageReg:"Custom RegExp of next page",
  338. retainImage:"Keep the URL of image if there are images in the text",
  339. minTxtLength:"Try to crawl again when the length of content is less than this",
  340. showFilterList: "Show chapter filtering and sorting window before downloading",
  341. ok:"OK",
  342. close:"Close",
  343. dacSortByPos:"Sort by position",
  344. dacSortByUrl:"Sort by URL",
  345. dacSortByName:"Sort by name",
  346. reverse:"Reverse selection",
  347. dacUseIframe: "Use iframe to load content (slow)",
  348. dacSaveAsZip: "Save as zip",
  349. dacSetCustomRule:"Modify rules",
  350. dacAddUrl:"Add Chapter",
  351. dacStartDownload:"Download selected"
  352. };
  353. break;
  354. }
  355. var firefox=navigator.userAgent.toLowerCase().indexOf('firefox')!=-1,curRequests=[],useIframe=false,iframeSandbox=false,iframeInit=false;
  356. var filterListContainer,txtDownContent,txtDownWords,txtDownQuit,dacLinksCon,dacUseIframe,shadowContainer;
  357.  
  358. const escapeHTMLPolicy = (win.trustedTypes && win.trustedTypes.createPolicy) ? win.trustedTypes.createPolicy('dac_default', {
  359. createHTML: (string, sink) => string
  360. }) : null;
  361.  
  362. function createHTML(html) {
  363. return escapeHTMLPolicy ? escapeHTMLPolicy.createHTML(html) : html;
  364. }
  365.  
  366. function str2Num(str) {
  367. str = str.replace(/^番\s*外/, "99999+").replace(/[一①Ⅰ壹]/g, "1").replace(/[二②Ⅱ贰]/g, "2").replace(/[三③Ⅲ叁]/g, "3").replace(/[四④Ⅳ肆]/g, "4").replace(/[五⑤Ⅴ伍]/g, "5").replace(/[六⑥Ⅵ陆]/g, "6").replace(/[七⑦Ⅶ柒]/g, "7").replace(/[八⑧Ⅷ捌]/g, "8").replace(/[九⑨Ⅸ玖]/g, "9").replace(/[十⑩Ⅹ拾]/g, "*10+").replace(/[百佰]/g, "*100+").replace(/[千仟]/g, "*1000+").replace(/[万萬]/g, "*10000+").replace(/\s/g, "").match(/[\d\*\+]+/);
  368. if (!str) return 0;
  369. str = str[0];
  370. let mul = str.match(/(\d*)\*(\d+)/);
  371. while(mul) {
  372. let result = parseInt(mul[1] || 1) * parseInt(mul[2]);
  373. str = str.replace(mul[0], result);
  374. mul = str.match(/(\d+)\*(\d+)/);
  375. }
  376. let plus = str.match(/(\d+)\+(\d+)/);
  377. while(plus) {
  378. let result = parseInt(plus[1]) + parseInt(plus[2]);
  379. str = str.replace(plus[0], result);
  380. plus = str.match(/(\d+)\+(\d+)/);
  381. }
  382. return parseInt(str);
  383. }
  384.  
  385. var dragOverItem, dragFrom, linkDict;
  386. function createLinkItem(aEle) {
  387. let item = document.createElement("div");
  388. item.innerHTML = createHTML(`
  389. <input type="checkbox" checked>
  390. <a class="dacLink" draggable="false" target="_blank" href="${aEle.href}">${aEle.innerText || "📄"}</a>
  391. <span>🖱️</span>
  392. `);
  393. item.title = aEle.innerText;
  394. item.setAttribute("draggable", "true");
  395. item.addEventListener("dragover", e => {
  396. e.preventDefault();
  397. });
  398. item.addEventListener("dragenter", e => {
  399. if (dragOverItem) dragOverItem.style.opacity = "";
  400. item.style.opacity = 0.3;
  401. dragOverItem = item;
  402. });
  403. item.addEventListener('dragstart', e => {
  404. dragFrom = item;
  405. });
  406. item.addEventListener('drop', e => {
  407. if (!dragFrom) return;
  408. if (e.clientX < item.getBoundingClientRect().left + 142) {
  409. dacLinksCon.insertBefore(dragFrom, item);
  410. } else {
  411. if (item.nextElementSibling) {
  412. dacLinksCon.insertBefore(dragFrom, item.nextElementSibling);
  413. } else {
  414. dacLinksCon.appendChild(dragFrom);
  415. }
  416. }
  417. e.preventDefault();
  418. });
  419. linkDict[aEle.href] = item;
  420. dacLinksCon.appendChild(item);
  421. }
  422.  
  423. var saveAsZip = true;
  424. function filterList(list) {
  425. if (!GM_getValue("showFilterList")) {
  426. indexDownload(list);
  427. return;
  428. }
  429. if (txtDownContent) {
  430. txtDownContent.style.display = "none";
  431. }
  432. if (filterListContainer) {
  433. filterListContainer.style.display = "";
  434. filterListContainer.classList.remove("customRule");
  435. dacLinksCon.innerHTML = createHTML("");
  436. } else {
  437. document.addEventListener('dragend', e => {
  438. if (dragOverItem) dragOverItem.style.opacity = "";
  439. }, true);
  440. filterListContainer = document.createElement("div");
  441. filterListContainer.id = "filterListContainer";
  442. filterListContainer.innerHTML = createHTML(`
  443. <div id="dacFilterBg" style="height: 100%; width: 100%; position: fixed; top: 0; z-index: 99998; opacity: 0.3; filter: alpha(opacity=30); background-color: #000;"></div>
  444. <div style="padding: 5px; box-sizing: border-box; overflow: hidden; width: 600px; height: auto; max-height: 80vh; min-height: 200px; position: fixed; left: 50%; top: 10%; margin-left: -300px; z-index: 99998; background-color: #ffffff; border: 1px solid #afb3b6; border-radius: 10px; opacity: 0.95; filter: alpha(opacity=95); box-shadow: 5px 5px 20px 0px #000;">
  445. <div class="dacCustomRule">
  446. ${i18n.custom}
  447. <textarea id="dacCustomInput"></textarea>
  448. <div class="fun">
  449. <input id="dacConfirmRule" value="${i18n.ok}" type="button"/>
  450. <input id="dacCustomClose" value="${i18n.close}" type="button"/>
  451. </div>
  452. </div>
  453. <div class="sort">
  454. <input id="dacSortByPos" value="${i18n.dacSortByPos}" type="button"/>
  455. <input id="dacSortByUrl" value="${i18n.dacSortByUrl}" type="button"/>
  456. <input id="dacSortByName" value="${i18n.dacSortByName}" type="button"/>
  457. <input id="reverse" value="${i18n.reverse}" type="button"/>
  458. </div>
  459. <div id="dacLinksCon" style="max-height: calc(80vh - 100px); min-height: 100px; display: grid; grid-template-columns: auto auto; width: 100%; overflow: auto; white-space: nowrap;"></div>
  460. <p style="margin: 5px; text-align: center; font-size: 14px; height: 20px;"><span><input id="dacUseIframe" type="checkbox"/><label for="dacUseIframe"> ${i18n.dacUseIframe}</label></span> <span style="display:${win.downloadAllContentSaveAsZip ? "inline" : "none"}"><input id="dacSaveAsZip" type="checkbox" checked="checked"/><label for="dacSaveAsZip"> ${i18n.dacSaveAsZip}</label></span></p>
  461. <div class="fun">
  462. <input id="dacSetCustomRule" value="${i18n.dacSetCustomRule}" type="button"/>
  463. <input id="dacAddUrl" value="${i18n.dacAddUrl}" type="button"/>
  464. <input id="dacStartDownload" value="${i18n.dacStartDownload}" type="button"/>
  465. <input id="dacLinksClose" value="${i18n.close}" type="button"/>
  466. </div>
  467. </div>`);
  468. let dacSortByPos = filterListContainer.querySelector("#dacSortByPos");
  469. let dacSortByUrl = filterListContainer.querySelector("#dacSortByUrl");
  470. let dacSortByName = filterListContainer.querySelector("#dacSortByName");
  471. let reverse = filterListContainer.querySelector("#reverse");
  472. let dacSetCustomRule = filterListContainer.querySelector("#dacSetCustomRule");
  473. let dacCustomInput = filterListContainer.querySelector("#dacCustomInput");
  474. let dacConfirmRule = filterListContainer.querySelector("#dacConfirmRule");
  475. let dacCustomClose = filterListContainer.querySelector("#dacCustomClose");
  476. let dacAddUrl = filterListContainer.querySelector("#dacAddUrl");
  477. let dacStartDownload = filterListContainer.querySelector("#dacStartDownload");
  478. let dacLinksClose = filterListContainer.querySelector("#dacLinksClose");
  479. let dacFilterBg = filterListContainer.querySelector("#dacFilterBg");
  480. let dacSaveAsZip = filterListContainer.querySelector("#dacSaveAsZip");
  481. dacUseIframe = filterListContainer.querySelector("#dacUseIframe");
  482. dacSaveAsZip.onchange = e => {
  483. saveAsZip = dacSaveAsZip.checked;
  484. };
  485. dacSortByPos.onclick = e => {
  486. let linkList = [].slice.call(dacLinksCon.children);
  487. if (linkList[0].children[1].href != list[0].href) {
  488. list.reverse().forEach(a => {
  489. let link = linkDict[a.href];
  490. if (!link) return;
  491. dacLinksCon.insertBefore(link, dacLinksCon.children[0]);
  492. });
  493. } else {
  494. list.forEach(a => {
  495. let link = linkDict[a.href];
  496. if (!link) return;
  497. dacLinksCon.insertBefore(link, dacLinksCon.children[0]);
  498. });
  499. }
  500. };
  501. dacSortByUrl.onclick = e => {
  502. let linkList = [].slice.call(dacLinksCon.children);
  503. linkList.sort((a, b) => {
  504. const nameA = a.children[1].href.toUpperCase();
  505. const nameB = b.children[1].href.toUpperCase();
  506. if (nameA < nameB) {
  507. return -1;
  508. }
  509. if (nameA > nameB) {
  510. return 1;
  511. }
  512. return 0;
  513. });
  514. if (linkList[0] == dacLinksCon.children[0]) {
  515. linkList = linkList.reverse();
  516. }
  517. linkList.forEach(link => {
  518. dacLinksCon.appendChild(link);
  519. });
  520. };
  521. dacSortByName.onclick = e => {
  522. let linkList = [].slice.call(dacLinksCon.children);
  523. linkList.sort((a, b) => {
  524. return str2Num(a.innerText) - str2Num(b.innerText);
  525. });
  526. if (linkList[0] == dacLinksCon.children[0]) {
  527. linkList = linkList.reverse();
  528. }
  529. linkList.forEach(link => {
  530. dacLinksCon.appendChild(link);
  531. });
  532. };
  533. reverse.onclick = e => {
  534. let linkList = [].slice.call(dacLinksCon.children);
  535. linkList.forEach(link => {
  536. link.children[0].checked=!link.children[0].checked;
  537. });
  538. };
  539. dacSetCustomRule.onclick = e => {
  540. filterListContainer.classList.add("customRule");
  541. dacCustomInput.value = GM_getValue("DACrules_" + document.domain) || "";
  542. };
  543. dacConfirmRule.onclick = e => {
  544. if (dacCustomInput.value) {
  545. customDown(dacCustomInput.value);
  546. }
  547. };
  548. dacCustomClose.onclick = e => {
  549. filterListContainer.classList.remove("customRule");
  550. };
  551. dacAddUrl.onclick = e => {
  552. let addUrls = window.prompt(i18n.customInfo, "https://xxx.xxx/book-[20-99].html, https://xxx.xxx/book-[01-10].html");
  553. if (!addUrls || !/^http|^ftp/.test(addUrls)) return;
  554. let index = 1;
  555. [].forEach.call(addUrls.split(","), function(i) {
  556. var curEle;
  557. var varNum = /\[\d+\-\d+\]/.exec(i);
  558. if (varNum) {
  559. varNum = varNum[0].trim();
  560. } else {
  561. curEle = document.createElement("a");
  562. curEle.href = i;
  563. curEle.innerText = "Added Url";
  564. createLinkItem(curEle);
  565. return;
  566. }
  567. var num1 = /\[(\d+)/.exec(varNum)[1].trim();
  568. var num2 = /(\d+)\]/.exec(varNum)[1].trim();
  569. var num1Int = parseInt(num1);
  570. var num2Int = parseInt(num2);
  571. var numLen = num1.length;
  572. var needAdd = num1.charAt(0) == "0";
  573. if (num1Int >= num2Int) return;
  574. for (var j = num1Int; j <= num2Int; j++) {
  575. var urlIndex = j.toString();
  576. if (needAdd) {
  577. while(urlIndex.length < numLen) urlIndex = "0" + urlIndex;
  578. }
  579. var curUrl = i.replace(/\[\d+\-\d+\]/, urlIndex).trim();
  580. curEle = document.createElement("a");
  581. curEle.href = curUrl;
  582. curEle.innerText = "Added Url " + index++;
  583. createLinkItem(curEle);
  584. }
  585. });
  586. };
  587. dacStartDownload.onclick = e => {
  588. let linkList = [].slice.call(dacLinksCon.querySelectorAll("input:checked+.dacLink"));
  589. useIframe = !!dacUseIframe.checked;
  590. indexDownload(linkList, true);
  591. };
  592. dacLinksClose.onclick = e => {
  593. filterListContainer.style.display = "none";
  594. };
  595. dacFilterBg.onclick = e => {
  596. filterListContainer.style.display = "none";
  597. };
  598. let listStyle = GM_addStyle(`
  599. #filterListContainer * {
  600. font-size: 13px;
  601. float: initial;
  602. background-image: initial;
  603. height: fit-content;
  604. }
  605. #filterListContainer.customRule .dacCustomRule {
  606. display: flex;
  607. }
  608. #filterListContainer .dacCustomRule>textarea {
  609. height: 300px;
  610. width: 100%;
  611. border: 1px #DADADA solid;
  612. background: #ededed70;
  613. margin: 5px;
  614. }
  615. #filterListContainer.customRule .dacCustomRule~* {
  616. display: none!important;
  617. }
  618. #dacLinksCon>div {
  619. padding: 5px 0;
  620. display: flex;
  621. }
  622. #dacLinksCon>div>a {
  623. max-width: 245px;
  624. display: inline-block;
  625. text-overflow: ellipsis;
  626. overflow: hidden;
  627. }
  628. #dacLinksCon>div>input {
  629. margin-right: 5px;
  630. }
  631. #filterListContainer .dacCustomRule {
  632. border-radius: 8px;
  633. font-weight: bold;
  634. font-size: 16px;
  635. outline: none;
  636. align-items: center;
  637. flex-wrap: nowrap;
  638. white-space: nowrap;
  639. flex-direction: column;
  640. display: none;
  641. }
  642. #filterListContainer input {
  643. border-width: 2px;
  644. border-style: outset;
  645. border-color: buttonface;
  646. border-image: initial;
  647. border: 1px #DADADA solid;
  648. padding: 5px;
  649. border-radius: 8px;
  650. font-weight: bold;
  651. font-size: 9pt;
  652. outline: none;
  653. cursor: pointer;
  654. line-height: initial;
  655. width: initial;
  656. min-width: initial;
  657. max-width: initial;
  658. height: initial;
  659. min-height: initial;
  660. max-height: initial;
  661. }
  662. #dacLinksCon>div:nth-of-type(4n),
  663. #dacLinksCon>div:nth-of-type(4n+1) {
  664. background: #ffffff;
  665. }
  666. #dacLinksCon>div:nth-of-type(4n+2),
  667. #dacLinksCon>div:nth-of-type(4n+3) {
  668. background: #f5f5f5;
  669. }
  670. #filterListContainer .fun,#filterListContainer .sort {
  671. display: flex;
  672. justify-content: space-around;
  673. flex-wrap: nowrap;
  674. width: 100%;
  675. height: 28px;
  676. }
  677. #filterListContainer input[type=button]:hover {
  678. border: 1px #C6C6C6 solid;
  679. box-shadow: 1px 1px 1px #EAEAEA;
  680. color: #333333;
  681. background: #F7F7F7;
  682. }
  683. #filterListContainer input[type=button]:active {
  684. box-shadow: inset 1px 1px 1px #DFDFDF;
  685. }
  686. `);
  687. dacLinksCon = filterListContainer.querySelector("#dacLinksCon");
  688. shadowContainer = document.createElement("div");
  689. document.body.appendChild(shadowContainer);
  690. let shadow = shadowContainer.attachShadow({ mode: "open" });
  691. shadow.appendChild(listStyle);
  692. shadow.appendChild(filterListContainer);
  693. }
  694. if (shadowContainer.parentNode) shadowContainer.parentNode.removeChild(shadowContainer);
  695. linkDict = {};
  696. list.forEach(a => {
  697. createLinkItem(a);
  698. });
  699. dacUseIframe.checked = useIframe;
  700. document.body.appendChild(shadowContainer);
  701. }
  702.  
  703. function initTxtDownDiv() {
  704. if (txtDownContent) {
  705. txtDownContent.style.display = "";
  706. return;
  707. }
  708. txtDownContent = document.createElement("div");
  709. txtDownContent.id = "txtDownContent";
  710. let shadowContainer = document.createElement("div");
  711. document.body.appendChild(shadowContainer);
  712. let shadow = shadowContainer.attachShadow({ mode: "open" });
  713. shadow.appendChild(txtDownContent);
  714. txtDownContent.innerHTML=createHTML(`
  715. <div style="font-size:16px;color:#333333;width:362px;height:110px;position:fixed;left:50%;top:50%;margin-top:-25px;margin-left:-191px;z-index:100000;background-color:#ffffff;border:1px solid #afb3b6;border-radius:10px;opacity:0.95;filter:alpha(opacity=95);box-shadow:5px 5px 20px 0px #000;">
  716. <div id="txtDownWords" style="position:absolute;width:275px;height: 90px;max-height: 90%;border: 1px solid #f3f1f1;padding: 8px;border-radius: 10px;overflow: auto;">
  717. Analysing......
  718. </div>
  719. <div id="txtDownQuit" style="width: 30px;height: 30px;border-radius: 30px;position:absolute;right:2px;top:2px;cursor: pointer;background-color:#ff5a5a;">
  720. <span style="height: 30px;line-height: 30px;display:block;color:#FFF;text-align:center;font-size: 12px;font-weight: bold;font-family: arial;background: initial; float: initial;">╳</span>
  721. </div>
  722. <div style="position:absolute;right:0px;bottom:2px;cursor: pointer;max-width:85px">
  723. <button id="abortRequest" style="background: #008aff;border: 0;padding: 5px;border-radius: 6px;color: white;float: right;margin: 1px;height: 25px;display:none;line-height: 16px;">${getI18n('abort')}</button>
  724. <button id="tempSaveTxt" style="background: #008aff;border: 0;padding: 5px;border-radius: 6px;color: white;float: right;margin: 1px;height: 25px;line-height: 16px;cursor: pointer;">${getI18n('save')}</button>
  725. <button id="saveAsMd" style="background: #008aff;border: 0;padding: 5px;border-radius: 6px;color: white;float: right;margin: 1px;height: 25px;line-height: 16px;cursor: pointer;overflow: hidden;" title="${getI18n('saveAsMd')}">Markdown</button>
  726. </div>
  727. </div>`);
  728. txtDownWords=txtDownContent.querySelector("#txtDownWords");
  729. txtDownQuit=txtDownContent.querySelector("#txtDownQuit");
  730. txtDownQuit.onclick=function(){
  731. txtDownContent.style.display="none";
  732. };
  733. initTempSave(txtDownContent);
  734. }
  735.  
  736. function saveContent() {
  737. if (win.downloadAllContentSaveAsZip && saveAsZip) {
  738. win.downloadAllContentSaveAsZip(rCats, i18n.info.replace("#t#", location.href), content => {
  739. saveAs(content, document.title + ".zip");
  740. });
  741. } else {
  742. var blob = new Blob([i18n.info.replace("#t#", location.href) + "\r\n\r\n" + document.title + "\r\n\r\n" + rCats.join("\r\n\r\n")], {type: "text/plain;charset=utf-8"});
  743. saveAs(blob, document.title + ".txt");
  744. }
  745. }
  746.  
  747. function initTempSave(txtDownContent){
  748. var tempSavebtn = txtDownContent.querySelector('#tempSaveTxt');
  749. var abortbtn = txtDownContent.querySelector('#abortRequest');
  750. var saveAsMd = txtDownContent.querySelector('#saveAsMd');
  751. tempSavebtn.onclick = function(){
  752. saveContent();
  753. console.log(curRequests);
  754. }
  755. abortbtn.onclick = function(){
  756. let curRequest = curRequests.pop();
  757. if(curRequest)curRequest[1].abort();
  758. }
  759. saveAsMd.onclick = function(){
  760. let txt = i18n.info.replace("#t#", location.href)+"\n\n---\n"+document.title+"\n===\n";
  761. rCats.forEach(cat => {
  762. cat = cat.replace("\r\n", "\n---").replace(/(\r\n|\n\r)+/g, "\n\n").replace(/[\n\r]\t+/g, "\n");
  763. txt += '\n\n'+cat;
  764. });
  765. var blob = new Blob([txt], {type: "text/plain;charset=utf-8"});
  766. saveAs(blob, document.title+".md");
  767. }
  768. }
  769.  
  770. let charset = (document.characterSet || document.charset || document.inputEncoding);
  771. let equiv = document.querySelector('[http-equiv="Content-Type"]'), charsetValid = true;
  772. if (equiv && equiv.content) {
  773. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  774. if (!innerCharSet) {
  775. charsetValid = false;
  776. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  777. charsetValid = false;
  778. }
  779. } else charsetValid = false;
  780. function indexDownload(aEles, noSort){
  781. if(aEles.length<1)return;
  782. initTxtDownDiv();
  783. if(!noSort) {
  784. if(GM_getValue("contentSort")){
  785. aEles.sort((a, b) => {
  786. return str2Num(a.innerText) - str2Num(b.innerText);
  787. });
  788. }
  789. if(GM_getValue("contentSortUrl")){
  790. aEles.sort((a, b) => {
  791. const nameA = a.href.toUpperCase();
  792. const nameB = b.href.toUpperCase();
  793. if (nameA < nameB) {
  794. return -1;
  795. }
  796. if (nameA > nameB) {
  797. return 1;
  798. }
  799. return 0;
  800. });
  801. }
  802. if(GM_getValue("reverse")){
  803. aEles=aEles.reverse();
  804. }
  805. }
  806. rCats=[];
  807. var minTxtLength=GM_getValue("minTxtLength") || 100;
  808. var customTitle=GM_getValue("customTitle");
  809. var disableNextPage=!!GM_getValue("disableNextPage");
  810. var customNextPageReg=GM_getValue("nextPageReg");
  811. if (customNextPageReg) {
  812. try {
  813. innerNextPage = new RegExp(customNextPageReg);
  814. } catch(e) {
  815. console.warn(e);
  816. }
  817. }
  818. var insertSigns=[];
  819. // var j=0,rCats=[];
  820. var downIndex=0,downNum=0,downOnce=function(wait){
  821. if(downNum>=aEles.length)return;
  822. let curIndex=downIndex;
  823. let aTag=aEles[curIndex];
  824. let request=(aTag, curIndex)=>{
  825. let tryTimes=0;
  826. let validTimes=0;
  827. function requestDoc(_charset) {
  828. if (!_charset) _charset = charset;
  829. return GM_xmlhttpRequest({
  830. method: 'GET',
  831. url: aTag.href,
  832. headers:{
  833. referer:aTag.href,
  834. "Content-Type":"text/html;charset="+_charset
  835. },
  836. timeout:10000,
  837. overrideMimeType:"text/html;charset="+_charset,
  838. onload: function(result) {
  839. let doc = getDocEle(result.responseText);
  840. if (charsetValid) {
  841. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  842. if (equiv && equiv.content) {
  843. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  844. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != _charset.replace("-", "").toLowerCase()) {
  845. charset = innerCharSet[1];
  846. return requestDoc(charset);
  847. }
  848. }
  849. }
  850. downIndex++;
  851. downNum++;
  852. if (/^{/.test(result.responseText)) {
  853. doc.json = () => {
  854. try {
  855. return JSON.parse(result.responseText);
  856. } catch(e) {}
  857. return {};
  858. }
  859. }
  860. let base = doc.querySelector("base");
  861. let nextPage = !disableNextPage && !processFunc && checkNextPage(doc, base ? base.href : aTag.href);
  862. if(nextPage){
  863. var inArr=false;
  864. for(var ai=0;ai<aEles.length;ai++){
  865. if(aEles[ai].href==nextPage.href){
  866. inArr=true;
  867. break;
  868. }
  869. }
  870. if(!inArr){
  871. nextPage.innerText=aTag.innerText+"\t>>";
  872. aEles.push(nextPage);
  873. let targetIndex = curIndex;
  874. for(let a=0;a<insertSigns.length;a++){
  875. let signs=insertSigns[a],breakSign=false;
  876. if(signs){
  877. for(let b=0;b<signs.length;b++){
  878. let sign=signs[b];
  879. if(sign==curIndex){
  880. targetIndex=a;
  881. breakSign=true;
  882. break;
  883. }
  884. }
  885. }
  886. if(breakSign)break;
  887. }
  888. let insertSign = insertSigns[targetIndex];
  889. if(!insertSign)insertSigns[targetIndex] = [];
  890. insertSigns[targetIndex].push(aEles.length-1);
  891. }
  892. }
  893. if (result.status >= 400) {
  894. console.warn("error:", `status: ${result.status} from: ${aTag.href}`);
  895. } else {
  896. console.log(result.status);
  897. }
  898. if (customTitle) {
  899. try {
  900. let title = doc.querySelector(customTitle);
  901. if (title && title.innerText) {
  902. aTag.innerText = title.innerText;
  903. }
  904. } catch(e) {
  905. console.warn(e);
  906. }
  907. }
  908. let validData = processDoc(curIndex, aTag, doc, (result.status>=400?` status: ${result.status} from: ${aTag.href} `:""), validTimes < 5);
  909. if (!validData && validTimes++ < 5) {
  910. downIndex--;
  911. downNum--;
  912. setTimeout(() => {
  913. requestDoc();
  914. }, 500);
  915. return;
  916. }
  917. if (wait) {
  918. setTimeout(() => {
  919. downOnce(wait);
  920. }, wait);
  921. } else downOnce();
  922. },
  923. onerror: function(e) {
  924. console.warn("error:", e);
  925. if(tryTimes++ < 5){
  926. setTimeout(() => {
  927. requestDoc();
  928. }, 500);
  929. return;
  930. }
  931. downIndex++;
  932. downNum++;
  933. processDoc(curIndex, aTag, null, ` NETWORK ERROR: ${(e.response||e.responseText)} from: ${aTag.href} `);
  934. if (wait) {
  935. setTimeout(() => {
  936. downOnce(wait);
  937. }, wait);
  938. } else downOnce();
  939. },
  940. ontimeout: function(e) {
  941. console.warn("timeout: times="+tryTimes+" url="+aTag.href);
  942. //console.log(e);
  943. if(tryTimes++ < 5){
  944. setTimeout(() => {
  945. requestDoc();
  946. }, 500);
  947. return;
  948. }
  949. downIndex++;
  950. downNum++;
  951. processDoc(curIndex, aTag, null, ` TIMEOUT: ${aTag.href} `);
  952. if (wait) {
  953. setTimeout(() => {
  954. downOnce(wait);
  955. }, wait);
  956. } else downOnce();
  957. }
  958. });
  959. };
  960. if (useIframe) {
  961. let iframe = document.createElement('iframe'), inited = false;
  962. iframe.name = 'pagetual-iframe';
  963. iframe.width = '100%';
  964. iframe.height = '1000';
  965. iframe.frameBorder = '0';
  966. iframe.sandbox = iframeSandbox || "allow-same-origin allow-scripts allow-popups allow-forms";
  967. iframe.style.cssText = 'margin:0!important;padding:0!important;visibility:hidden!important;flex:0;opacity:0!important;pointer-events:none!important;position:fixed;top:0px;left:0px;z-index:-2147483647;';
  968. iframe.addEventListener('load', e => {
  969. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  970. if (inited) return;
  971. inited = true;
  972. function checkIframe() {
  973. try {
  974. let doc = iframe.contentDocument || iframe.contentWindow.document;
  975. if (!doc || !doc.body) {
  976. setTimeout(() => {
  977. checkIframe();
  978. }, 1000);
  979. return;
  980. }
  981. doc.body.scrollTop = 9999999;
  982. doc.documentElement.scrollTop = 9999999;
  983. if (!processFunc && validTimes++ > 5) {
  984. iframe.src = iframe.src;
  985. validTimes = 0;
  986. inited = false;
  987. return;
  988. }
  989. if (customTitle) {
  990. try {
  991. let title = doc.querySelector(customTitle);
  992. if (title && title.innerText) {
  993. aTag.innerText = title.innerText;
  994. }
  995. } catch(e) {
  996. console.warn(e);
  997. }
  998. }
  999. downIndex++;
  1000. downNum++;
  1001. let validData = processDoc(curIndex, aTag, doc, "", true);
  1002. if (!validData) {
  1003. downIndex--;
  1004. downNum--;
  1005. setTimeout(() => {
  1006. checkIframe();
  1007. }, 1000);
  1008. return;
  1009. }
  1010. if (wait) {
  1011. setTimeout(() => {
  1012. downOnce(wait);
  1013. }, wait);
  1014. } else downOnce();
  1015. } catch(e) {
  1016. console.debug("Stop as cors");
  1017. }
  1018. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  1019. }
  1020. setTimeout(() => {
  1021. checkIframe();
  1022. }, 500);
  1023. }, false);
  1024. let checkReady = setInterval(() => {
  1025. let doc;
  1026. try {
  1027. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  1028. } catch(e) {
  1029. clearInterval(checkReady);
  1030. return;
  1031. }
  1032. if (doc) {
  1033. try {
  1034. Function('win', 'iframe', '"use strict";' + (iframeInit || "win.self=win.top;"))(iframe.contentWindow, iframe);
  1035. clearInterval(checkReady);
  1036. } catch(e) {
  1037. console.debug(e);
  1038. }
  1039. }
  1040. }, 50);
  1041. iframe.src = aTag.href;
  1042. document.body.appendChild(iframe);
  1043. return [curIndex, null, aTag.href];
  1044. } else {
  1045. return [curIndex, requestDoc(), aTag.href];
  1046. }
  1047. }
  1048. if(!aTag){
  1049. let waitAtagReadyInterval=setInterval(function(){
  1050. if(downNum>=aEles.length)clearInterval(waitAtagReadyInterval);
  1051. aTag=aEles[curIndex];
  1052. if(aTag){
  1053. clearInterval(waitAtagReadyInterval);
  1054. request(aTag, curIndex);
  1055. }
  1056. },1000);
  1057. return null;
  1058. }
  1059. let result = request(aTag, curIndex);
  1060. if (result) curRequests.push(result);
  1061. return result;
  1062. };
  1063. function getDocEle(str){
  1064. var doc = null;
  1065. try {
  1066. doc = document.implementation.createHTMLDocument('');
  1067. doc.documentElement.innerHTML = str;
  1068. }
  1069. catch (e) {
  1070. console.log('parse error');
  1071. }
  1072. return doc;
  1073. }
  1074. function sortInnerPage(){
  1075. var pageArrs=[],maxIndex=0,i,j;
  1076. for(i=0;i<insertSigns.length;i++){
  1077. var signs=insertSigns[i];
  1078. if(signs){
  1079. for(j=0;j<signs.length;j++){
  1080. var sign=signs[j];
  1081. var cat=rCats[sign];
  1082. rCats[sign]=null;
  1083. if(!pageArrs[i])pageArrs[i]=[];
  1084. pageArrs[i].push(cat);
  1085. }
  1086. }
  1087. }
  1088. for(i=pageArrs.length-1;i>=0;i--){
  1089. let pageArr=pageArrs[i];
  1090. if(pageArr){
  1091. for(j=pageArr.length-1;j>=0;j--){
  1092. rCats.splice(i+1, 0, pageArr[j]);
  1093. }
  1094. }
  1095. }
  1096. rCats = rCats.filter(function(e){return e!=null});
  1097. }
  1098. var waitForComplete;
  1099. function processDoc(i, aTag, doc, cause, check){
  1100. let cbFunc=content=>{
  1101. rCats[i]=(aTag.innerText.replace(/[\r\n\t]/g, "") + "\r\n" + (cause || '') + content.replace(/\s*$/, ""));
  1102. curRequests = curRequests.filter(function(e){return e[0]!=i});
  1103. txtDownContent.style.display="block";
  1104. txtDownWords.innerHTML=getI18n("downloading",[downNum,(aEles.length-downNum),aTag.innerText]);
  1105. if(downNum==aEles.length){
  1106. if(waitForComplete) clearTimeout(waitForComplete);
  1107. waitForComplete=setTimeout(()=>{
  1108. if(downNum==aEles.length){
  1109. txtDownWords.innerHTML=getI18n("complete",[downNum]);
  1110. sortInnerPage();
  1111. saveContent();
  1112. }
  1113. },3000);
  1114. }
  1115. };
  1116. let contentResult=getPageContent(doc, content=>{
  1117. cbFunc(content);
  1118. }, aTag.href);
  1119. if(contentResult!==false){
  1120. if(check && contentResult && contentResult.replace(/\s/g, "").length<minTxtLength){
  1121. return false;
  1122. }
  1123. cbFunc(contentResult);
  1124. }
  1125. return true;
  1126. }
  1127. var downThreadNum = parseInt(GM_getValue("downThreadNum"));
  1128. downThreadNum = downThreadNum || 20;
  1129. if (useIframe && downThreadNum > 5) {
  1130. downThreadNum = 5;
  1131. }
  1132. if (downThreadNum > 0) {
  1133. for (var i = 0; i < downThreadNum; i++) {
  1134. downOnce();
  1135. if (downIndex >= aEles.length - 1 || downIndex >= downThreadNum - 1) break;
  1136. else downIndex++;
  1137. }
  1138. } else {
  1139. downOnce(-downThreadNum * 1000);
  1140. if (downIndex < aEles.length - 1 && downIndex < downThreadNum - 1) downIndex++;
  1141. }
  1142.  
  1143. /*for(let i=0;i<aEles.length;i++){
  1144. let aTag=aEles[i];
  1145. GM_xmlhttpRequest({
  1146. method: 'GET',
  1147. url: aTag.href,
  1148. overrideMimeType:"text/html;charset="+document.charset,
  1149. onload: function(result) {
  1150. var doc = getDocEle(result.responseText);
  1151. processDoc(i, aTag, doc);
  1152. }
  1153. });
  1154. }*/
  1155. }
  1156.  
  1157. function canonicalUri(src, baseUrl) {
  1158. if (!src) {
  1159. return "";
  1160. }
  1161. if (src.charAt(0) == "#") return baseUrl + src;
  1162. if (src.charAt(0) == "?") return baseUrl.replace(/^([^\?#]+).*/, "$1" + src);
  1163. let origin = location.protocol + '//' + location.host;
  1164. let url = baseUrl || origin;
  1165. url = url.replace(/(\?|#).*/, "");
  1166. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  1167. if (url.indexOf("http") !== 0) url = origin + url;
  1168. var root_page = /^[^\?#]*\//.exec(url)[0],
  1169. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  1170. absolute_regex = /^\w+\:\/\//;
  1171. while (src.indexOf("../") === 0) {
  1172. src = src.substr(3);
  1173. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  1174. }
  1175. src = src.replace(/\.\//, "");
  1176. if (/^\/\/\/?/.test(src)) {
  1177. src = location.protocol + src;
  1178. }
  1179. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  1180. }
  1181.  
  1182. function checkNextPage(doc, baseUrl) {
  1183. let aTags = doc.querySelectorAll("a"), nextPage = null;
  1184. for (var i = 0; i < aTags.length; i++) {
  1185. let aTag = aTags[i];
  1186. if (innerNextPage.test(aTag.innerText) && aTag.href && !/javascript:|#/.test(aTag.href)) {
  1187. let nextPageHref = canonicalUri(aTag.getAttribute("href"), baseUrl || location.href);
  1188. if (nextPageHref != location.href) {
  1189. nextPage = aTag;
  1190. nextPage.href = nextPageHref;
  1191. break;
  1192. }
  1193. }
  1194. }
  1195. return nextPage;
  1196. }
  1197.  
  1198. function textNodesUnder(el){
  1199. var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  1200. while(n=walk.nextNode()) a.push(n);
  1201. return a;
  1202. }
  1203.  
  1204. function getPageContent(doc, cb, url){
  1205. if(!doc)return i18n.error;
  1206. if(processFunc){
  1207. return processFunc(doc, cb, url);
  1208. }
  1209. [].forEach.call(doc.querySelectorAll("span,div,ul"),function(item){
  1210. var thisStyle=doc.defaultView?doc.defaultView.getComputedStyle(item):item.style;
  1211. if(thisStyle && (thisStyle.display=="none" || (item.nodeName=="SPAN" && thisStyle.fontSize=="0px"))){
  1212. item.innerHTML="";
  1213. }
  1214. });
  1215. var i,j,k,rStr="",pageData=(doc.body?doc.body:doc).cloneNode(true);
  1216. pageData.innerHTML=pageData.innerHTML.replace(/\<\!\-\-((.|[\n|\r|\r\n])*?)\-\-\>/g,"");
  1217. [].forEach.call(pageData.querySelectorAll("font.jammer"),function(item){
  1218. item.innerHTML="";
  1219. });
  1220. var selectors=GM_getValue("selectors");
  1221. if(selectors){
  1222. [].forEach.call(pageData.querySelectorAll(selectors),function(item){
  1223. item.innerHTML="";
  1224. });
  1225. }
  1226. [].forEach.call(pageData.querySelectorAll("script,style,link,noscript,iframe"),function(item){
  1227. if (item && item.parentNode) {
  1228. item.parentNode.removeChild(item);
  1229. }
  1230. });
  1231. var endEle = ele => {
  1232. return /^(I|STRONG|B|FONT|P|DL|DD|H\d)$/.test(ele.nodeName) && ele.children.length <= 1;
  1233. };
  1234. var largestContent,contents=pageData.querySelectorAll("span,div,article,p,td,pre"),largestNum=0;
  1235. for(i=0;i<contents.length;i++){
  1236. let content=contents[i],hasText=false,allSingle=true,item,curNum=0;
  1237. if(/footer/.test(content.className))continue;
  1238. for(j=content.childNodes.length-1;j>=0;j--){
  1239. item=content.childNodes[j];
  1240. if(item.nodeType==3){
  1241. if(/^\s*$/.test(item.data)){
  1242. item.innerHTML="";
  1243. }else hasText=true;
  1244. }else if(/^(I|A|STRONG|B|FONT|P|DL|DD|H\d)$/.test(item.nodeName)){
  1245. hasText=true;
  1246. }else if(item.nodeType==1&&item.children.length==1&&/^(I|A|STRONG|B|FONT|P|DL|DD|H\d)$/.test(item.children[0].nodeName)){
  1247. hasText=true;
  1248. }
  1249. }
  1250. for(j=content.childNodes.length-1;j>=0;j--){
  1251. item=content.childNodes[j];
  1252. if(item.nodeType==1 && !/^(I|A|STRONG|B|FONT|BR)$/.test(item.nodeName) && /^[\s\-\_\?\>\|]*$/.test(item.innerHTML)){
  1253. item.innerHTML="";
  1254. }
  1255. }
  1256. if(content.childNodes.length>1){
  1257. let indexItem=0;
  1258. for(j=0;j<content.childNodes.length;j++){
  1259. item=content.childNodes[j];
  1260. if(item.nodeType==1){
  1261. if(item.innerText && item.innerText.length<50 && indexReg.test(item.innerText))indexItem++;
  1262. for(k=0;k<item.childNodes.length;k++){
  1263. var childNode=item.childNodes[k];
  1264. if(childNode.nodeType!=3 && !/^(I|A|STRONG|B|FONT|BR)$/.test(childNode.nodeName)){
  1265. allSingle=false;
  1266. break;
  1267. }
  1268. }
  1269. if(!allSingle)break;
  1270. }
  1271. }
  1272. if(indexItem>=5)continue;
  1273. }else{
  1274. allSingle=false;
  1275. }
  1276. if(!allSingle && !hasText){
  1277. continue;
  1278. }else {
  1279. if(pageData==document && content.offsetWidth<=0 && content.offsetHeight<=0){
  1280. continue;
  1281. }
  1282. [].forEach.call(content.childNodes,function(item){
  1283. if(item.nodeType==3)curNum+=item.data.trim().length;
  1284. else if(endEle(item) || (item.nodeType == 1 && item.children.length == 1 && endEle(item.children[0]))) curNum += (firefox ? item.textContent.trim().length : item.innerText.trim().length);
  1285. });
  1286. }
  1287. if(curNum>largestNum){
  1288. largestNum=curNum;
  1289. largestContent=content;
  1290. }
  1291. }
  1292. if(!largestContent)return i18n.error+" : NO TEXT CONTENT";
  1293. var retainImage=!!GM_getValue("retainImage");
  1294. var childlist=pageData.querySelectorAll(largestContent.nodeName);//+(largestContent.className?"."+largestContent.className.replace(/(^\s*)|(\s*$)/g, '').replace(/\s+/g, '.'):""));
  1295. function getRightStr(ele, noTextEnable){
  1296. if(retainImage){
  1297. [].forEach.call(ele.querySelectorAll("img[src]"), img => {
  1298. let imgTxtNode=document.createTextNode(`![img](${canonicalUri(img.getAttribute("src"), url || location.href)})`);
  1299. img.parentNode.replaceChild(imgTxtNode, img);
  1300. });
  1301. }
  1302. let childNodes=ele.childNodes,cStr="\r\n",hasText=false;
  1303. [].forEach.call(ele.querySelectorAll("a[href]"), a => {
  1304. a.parentNode && a.parentNode.removeChild(a);
  1305. });
  1306. for(let j=0;j<childNodes.length;j++){
  1307. let childNode=childNodes[j];
  1308. if(childNode.nodeType==3 && childNode.data && !/^[\s\-\_\?\>\|]*$/.test(childNode.data))hasText=true;
  1309. if(childNode.innerHTML){
  1310. childNode.innerHTML=childNode.innerHTML.replace(/\<\s*br\s*\>/gi,"\r\n").replace(/\n+/gi,"\n").replace(/\r+/gi,"\r");
  1311. }
  1312. let content=childNode.textContent;
  1313. if(content){
  1314. if(!content.trim())continue;
  1315. cStr+=content.replace(/[\uFEFF\xA0 ]+/g," ").replace(/([^\r]|^)\n([^\r]|$)/gi,"$1\r\n$2");
  1316. }
  1317. if(childNode.nodeType!=3 && !/^(I|A|STRONG|B|FONT|IMG)$/.test(childNode.nodeName))cStr+="\r\n";
  1318. }
  1319. if(hasText || noTextEnable || ele==largestContent)rStr+=cStr+"\r\n";
  1320. }
  1321. var sameDepthChildren=[];
  1322. for(i=0;i<childlist.length;i++){
  1323. var child=childlist[i];
  1324. if(getDepth(child)==getDepth(largestContent)){
  1325. if(largestContent.className != child.className)continue;
  1326. sameDepthChildren.push(child);
  1327. }
  1328. }
  1329. var minLength = largestNum>>2;
  1330. var tooShort = sameDepthChildren.length <= 3;
  1331. sameDepthChildren.forEach(child => {
  1332. if(tooShort && child.innerText.length < minLength) return;
  1333. if((largestContent.className && largestContent.className == child.className) || largestContent.parentNode == child.parentNode){
  1334. getRightStr(child, true);
  1335. }else {
  1336. getRightStr(child, false);
  1337. }
  1338. });
  1339. return rStr.replace(/[\n\r]+/g,"\n\r");
  1340. }
  1341.  
  1342. function getI18n(key, args){
  1343. var resultStr=i18n[key];
  1344. if(args && args.length>0){
  1345. args.forEach(function(item){
  1346. resultStr=resultStr.replace(/%s/,item);
  1347. });
  1348. }
  1349. return resultStr;
  1350. }
  1351.  
  1352. function getDepth(dom){
  1353. var pa=dom,i=0;
  1354. while(pa.parentNode){
  1355. pa=pa.parentNode;
  1356. i++;
  1357. }
  1358. return i;
  1359. }
  1360.  
  1361. async function sleep(time) {
  1362. await new Promise((resolve) => {
  1363. setTimeout(() => {
  1364. resolve();
  1365. }, time);
  1366. })
  1367. }
  1368.  
  1369. async function fetch(forceSingle){
  1370. forceSingle=forceSingle===true;
  1371. processFunc=null;
  1372. initTxtDownDiv();
  1373. var aEles=document.body.querySelectorAll("a"),list=[];
  1374. txtDownWords.innerHTML=`Analysing ( 1/${aEles.length} )......`;
  1375. txtDownContent.style.pointerEvents="none";
  1376. for(var i=0;i<aEles.length;i++){
  1377. if (i % 100 == 0) {
  1378. await sleep(1);
  1379. }
  1380. txtDownWords.innerHTML=`Analysing ( ${i + 1}/${aEles.length} )......`;
  1381. var aEle=aEles[i],has=false;
  1382. if(aEle.dataset.href && (!aEle.href || aEle.href.indexOf("javascript")!=-1)){
  1383. aEle.href=aEle.dataset.href;
  1384. }
  1385. if(aEle.href==location.href)continue;
  1386. for(var j=0;j<list.length;j++){
  1387. if(list[j].href==aEle.href){
  1388. aEle=list[j];
  1389. list.splice(j,1);
  1390. list.push(aEle);
  1391. has=true;
  1392. break;
  1393. }
  1394. }
  1395. if(!has && aEle.href && /^http/i.test(aEle.href) && ((aEle.innerText.trim()!="" && indexReg.test(aEle.innerText.trim())) || /chapter[\-_]?\d/.test(aEle.href))){
  1396. list.push(aEle);
  1397. }
  1398. }
  1399. txtDownContent.style.display="none";
  1400. txtDownContent.style.pointerEvents="";
  1401. txtDownWords.innerHTML="Analysing......";
  1402. if(list.length>2 && !forceSingle){
  1403. useIframe = false;
  1404. filterList(list);
  1405. }else{
  1406. var blob = new Blob([i18n.info.replace("#t#", location.href)+"\r\n\r\n"+document.title+"\r\n\r\n"+getPageContent(document)], {type: "text/plain;charset=utf-8"});
  1407. saveAs(blob, document.title+".txt");
  1408. }
  1409. }
  1410.  
  1411. function customDown(urls){
  1412. processFunc = null;
  1413. useIframe = false;
  1414. if(urls){
  1415. urls=decodeURIComponent(urls.replace(/%/g,'%25'));
  1416. GM_setValue("DACrules_"+document.domain, urls);
  1417. var processEles=[];
  1418. let urlsArr=urls.split("@@"),eles=[];
  1419. if(/^http|^ftp/.test(urlsArr[0])){
  1420. [].forEach.call(urlsArr[0].split(","),function(i){
  1421. var curEle;
  1422. var varNum=/\[\d+\-\d+\]/.exec(i);
  1423. if(varNum){
  1424. varNum=varNum[0].trim();
  1425. }else{
  1426. curEle=document.createElement("a");
  1427. curEle.href=i;
  1428. curEle.innerText="Added Url";
  1429. processEles.push(curEle);
  1430. return;
  1431. }
  1432. var num1=/\[(\d+)/.exec(varNum)[1].trim();
  1433. var num2=/(\d+)\]/.exec(varNum)[1].trim();
  1434. var num1Int=parseInt(num1);
  1435. var num2Int=parseInt(num2);
  1436. var numLen=num1.length;
  1437. var needAdd=num1.charAt(0)=="0";
  1438. if(num1Int>=num2Int)return;
  1439. for(var j=num1Int;j<=num2Int;j++){
  1440. var urlIndex=j.toString();
  1441. if(needAdd){
  1442. while(urlIndex.length<numLen)urlIndex="0"+urlIndex;
  1443. }
  1444. var curUrl=i.replace(/\[\d+\-\d+\]/,urlIndex).trim();
  1445. curEle=document.createElement("a");
  1446. curEle.href=curUrl;
  1447. curEle.innerText="Added Url " + processEles.length.toString();
  1448. processEles.push(curEle);
  1449. }
  1450. });
  1451. }else{
  1452. let urlSel=urlsArr[0].split(">>");
  1453. try{
  1454. eles=document.querySelectorAll(urlSel[0]);
  1455. eles=[].filter.call(eles, ele=>{
  1456. return ele.nodeName=='BODY'||(!!ele.offsetParent&&getComputedStyle(ele).display!=='none');
  1457. })
  1458. }catch(e){}
  1459. if(eles.length==0){
  1460. eles=[];
  1461. var eleTxts=urlsArr[0].split(/(?<=[^\\])[,,]/),exmpEles=[],excludeTxts={};
  1462. [].forEach.call(document.querySelectorAll("a"),function(item){
  1463. if(!item.offsetParent)return;
  1464. eleTxts.forEach(txt=>{
  1465. var txtArr=txt.split("!");
  1466. if(item.innerText.indexOf(txtArr[0])!=-1){
  1467. exmpEles.push(item);
  1468. excludeTxts[item]=txtArr.splice(1);
  1469. }
  1470. });
  1471. })
  1472. exmpEles.forEach(e=>{
  1473. var cssSelStr="a",pa=e.parentNode,excludeTxt=excludeTxts[e];
  1474. if(e.className)cssSelStr+="."+CSS.escape(e.className);
  1475. while(pa && pa.nodeName!="BODY"){
  1476. cssSelStr=pa.nodeName+">"+cssSelStr;
  1477. pa=pa.parentNode;
  1478. }
  1479. cssSelStr="body>"+cssSelStr;;
  1480. [].forEach.call(document.querySelectorAll(cssSelStr),function(item){
  1481. if(!item.offsetParent)return;
  1482. var isExclude=false;
  1483. for(var t in excludeTxt){
  1484. if(item.innerText.indexOf(excludeTxt[t])!=-1){
  1485. isExclude=true;
  1486. break;
  1487. }
  1488. }
  1489. if(!isExclude && eles.indexOf(item)==-1){
  1490. eles.push(item);
  1491. }
  1492. });
  1493. });
  1494. }
  1495. function addItem(item) {
  1496. let has=false;
  1497. for(var j=0;j<processEles.length;j++){
  1498. if(processEles[j].href==item.href){
  1499. processEles.splice(j,1);
  1500. processEles.push(item);
  1501. has=true;
  1502. break;
  1503. }
  1504. }
  1505. if((!item.href || item.href.indexOf("javascript")!=-1) && item.dataset.href){
  1506. item.href=item.dataset.href;
  1507. }
  1508. if(!has && item.href && /^http/i.test(item.href)){
  1509. processEles.push(item.cloneNode(1));
  1510. }
  1511. }
  1512. [].forEach.call(eles,function(item){
  1513. if(urlSel[1]){
  1514. item=Function("item",urlSel[1])(item);
  1515. let items;
  1516. if (Array.isArray(item)) {
  1517. items = item;
  1518. } else items = [item];
  1519. items.forEach(item => {
  1520. if(!item || !item.href)return;
  1521. if(!item.nodeName || item.nodeName!="A"){
  1522. let href=item.href;
  1523. let innerText=item.innerText;
  1524. item=document.createElement("a");
  1525. item.href=href;
  1526. item.innerText=innerText;
  1527. }
  1528. addItem(item);
  1529. });
  1530. } else {
  1531. addItem(item);
  1532. }
  1533. });
  1534. }
  1535. if(urlsArr[1]){
  1536. processEles.forEach(ele=>{
  1537. ele.href=ele.href.replace(new RegExp(urlsArr[1]), urlsArr[2]);
  1538. });
  1539. }
  1540. var retainImage=!!GM_getValue("retainImage");
  1541. var evalCode = urlsArr[3];
  1542. if (evalCode && /^iframe:/.test(evalCode.trim())) {
  1543. evalCode = evalCode.trim().replace("iframe:", "");
  1544. useIframe = true;
  1545. iframeSandbox = false;
  1546. iframeInit = false;
  1547. while (/^(sandbox|init):/.test(evalCode)) {
  1548. iframeSandbox = evalCode.match(/^sandbox:{(.*?)}/);
  1549. if (iframeSandbox) {
  1550. iframeSandbox = iframeSandbox[1];
  1551. evalCode = evalCode.replace(/^sandbox:{(.*?)}/, "");
  1552. }
  1553. iframeInit = evalCode.match(/^init:{(.*?)}/);
  1554. if (iframeInit) {
  1555. iframeInit = iframeInit[1];
  1556. evalCode = evalCode.replace(/^init:{(.*?)}/, "");
  1557. }
  1558. }
  1559. }
  1560. if(evalCode){
  1561. processFunc=(data, cb, url)=>{
  1562. let doc=data;
  1563. if(evalCode.indexOf("return ")==-1){
  1564. if(evalCode.indexOf("@")==0){
  1565. let content="";
  1566. if(retainImage){
  1567. [].forEach.call(data.querySelectorAll("img[src]"), img => {
  1568. let imgTxt=`![img](${canonicalUri(img.getAttribute("src"), location.href)})`;
  1569. let imgTxtNode=document.createTextNode(imgTxt);
  1570. img.parentNode.replaceChild(imgTxtNode, img);
  1571. });
  1572. }
  1573. [].forEach.call(data.querySelectorAll(evalCode.slice(1)), ele=>{
  1574. [].forEach.call(ele.childNodes, child=>{
  1575. if(child.innerHTML){
  1576. child.innerHTML=child.innerHTML.replace(/\<\s*br\s*\>/gi,"\r\n").replace(/\n+/gi,"\n").replace(/\r+/gi,"\r");
  1577. }
  1578. if(child.textContent){
  1579. content+=(child.textContent.replace(/ +/g," ").replace(/([^\r]|^)\n([^\r]|$)/gi,"$1\r\n$2")+"\r\n");
  1580. }
  1581. });
  1582. content+="\r\n";
  1583. });
  1584. return content;
  1585. }else return eval(evalCode);
  1586. }else{
  1587. return Function("data", "doc", "cb", "url", evalCode)(data, doc, cb, url);
  1588. }
  1589. };
  1590. }else{
  1591. if(win.dacProcess){
  1592. processFunc=win.dacProcess;
  1593. }
  1594. }
  1595. filterList(processEles);
  1596. }
  1597. }
  1598. const configPage = "https://hoothin.github.io/UserScripts/DownloadAllContent/";
  1599. const copySvg = '<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" style="transition: all ease 0.5s;top: 5px;right: 5px;position: absolute;cursor: pointer;"><title>Copy</title><path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg>';
  1600. function searchRule(){
  1601. GM_openInTab(configPage + "#@" + location.hostname, {active: true});
  1602. }
  1603. if (location.origin + location.pathname == configPage) {
  1604. let exampleNode = document.getElementById("example");
  1605. if (!exampleNode) return;
  1606.  
  1607. exampleNode = exampleNode.parentNode;
  1608. let ruleList = exampleNode.nextElementSibling.nextElementSibling;
  1609. let searchInput = document.createElement("input");
  1610. let inputTimer;
  1611. function searchByInput() {
  1612. clearTimeout(inputTimer);
  1613. inputTimer = setTimeout(() => {
  1614. let curValue = searchInput.value;
  1615. let matchRules = [];
  1616. let dontMatchRules = [];
  1617. if (curValue) {
  1618. for (let i = 0; i < ruleList.children.length; i++) {
  1619. let curRule = ruleList.children[i];
  1620. let aHref = curRule.firstChild.href;
  1621. if (aHref.indexOf(curValue) == -1) {
  1622. dontMatchRules.push(curRule);
  1623. } else {
  1624. matchRules.push(curRule);
  1625. }
  1626. }
  1627. } else {
  1628. dontMatchRules = ruleList.children;
  1629. }
  1630. if (matchRules.length) {
  1631. for (let i = 0; i < dontMatchRules.length; i++) {
  1632. let curRule = dontMatchRules[i];
  1633. curRule.style.display = "none";
  1634. }
  1635. for (let i = 0; i < matchRules.length; i++) {
  1636. let curRule = matchRules[i];
  1637. curRule.style.display = "";
  1638. }
  1639. } else {
  1640. for (let i = 0; i < dontMatchRules.length; i++) {
  1641. let curRule = dontMatchRules[i];
  1642. curRule.style.display = "";
  1643. }
  1644. }
  1645. }, 500);
  1646. }
  1647. searchInput.style.margin = "10px";
  1648. searchInput.style.width = "100%";
  1649. searchInput.placeholder = i18n.searchRule;
  1650. searchInput.addEventListener("input", function(e) {
  1651. searchByInput();
  1652. });
  1653. if (location.hash) {
  1654. let hash = location.hash.slice(1);
  1655. if (hash.indexOf("@") == 0) {
  1656. setTimeout(() => {
  1657. exampleNode.scrollIntoView();
  1658. }, 500);
  1659. searchInput.value = hash.slice(1);
  1660. searchByInput();
  1661. }
  1662. }
  1663. [].forEach.call(ruleList.querySelectorAll("div.highlight"), highlight => {
  1664. highlight.style.position = "relative";
  1665. highlight.innerHTML = highlight.innerHTML + copySvg;
  1666. let svg = highlight.children[1];
  1667. svg.addEventListener("click", function(e) {
  1668. GM_setClipboard(highlight.children[0].innerText);
  1669. svg.style.opacity = 0;
  1670. setTimeout(() => {
  1671. svg.style.opacity = 1;
  1672. }, 1000);
  1673. });
  1674. });
  1675. exampleNode.parentNode.insertBefore(searchInput, ruleList);
  1676.  
  1677.  
  1678. let donateNode = document.querySelector("[alt='donate']");
  1679. if (!donateNode) return;
  1680. let insertPos = donateNode.parentNode.nextElementSibling;
  1681. let radioIndex = 0;
  1682. function createOption(_name, _value, _type) {
  1683. if (!_type) _type = "input";
  1684. let con = document.createElement("div");
  1685. let option = document.createElement("input");
  1686. let cap = document.createElement("b");
  1687. option.type = _type;
  1688. option.value = _value;
  1689. option.checked = _value;
  1690. cap.style.margin = "0px 10px 0px 0px";
  1691. if (_type == "radio") {
  1692. let label = document.createElement("label");
  1693. label.innerText = _name;
  1694. radioIndex++;
  1695. option.id = "radio" + radioIndex;
  1696. label.setAttribute("for", option.id);
  1697. cap.appendChild(label);
  1698. } else {
  1699. if (_type == "input") {
  1700. option.style.flexGrow = "1";
  1701. }
  1702. cap.innerText = _name;
  1703. }
  1704. con.style.margin = "10px 0";
  1705. con.style.display = "flex";
  1706. con.style.alignItems = "center";
  1707. con.appendChild(cap);
  1708. con.appendChild(option);
  1709. insertPos.parentNode.insertBefore(con, insertPos);
  1710. return option;
  1711. }
  1712. let showFilterList = createOption(i18n.showFilterList, !!GM_getValue("showFilterList"), "checkbox");
  1713. let delSelector = createOption(i18n.del, GM_getValue("selectors") || "");
  1714. delSelector.setAttribute("placeHolder", ".mask,.ksam");
  1715. let downThreadNum = createOption(i18n.downThreadNum, GM_getValue("downThreadNum") || "20", "number");
  1716. let customTitle = createOption(i18n.customTitle, GM_getValue("customTitle") || "");
  1717. customTitle.setAttribute("placeHolder", "title");
  1718. let minTxtLength = createOption(i18n.minTxtLength, GM_getValue("minTxtLength") || "100", "number");
  1719. let contentSortUrlValue = GM_getValue("contentSortUrl") || false;
  1720. let contentSortValue = GM_getValue("contentSort") || false;
  1721. let reSortDefault = createOption(i18n.reSortDefault, !contentSortUrlValue && !contentSortValue, "radio");
  1722. let reSortUrl = createOption(i18n.reSortUrl, contentSortUrlValue || false, "radio");
  1723. let contentSort = createOption(i18n.reSort, contentSortValue || false, "radio");
  1724. reSortDefault.name = "sort";
  1725. reSortUrl.name = "sort";
  1726. contentSort.name = "sort";
  1727. let reverse = createOption(i18n.reverseOrder, !!GM_getValue("reverse"), "checkbox");
  1728. let retainImage = createOption(i18n.retainImage, !!GM_getValue("retainImage"), "checkbox");
  1729. let disableNextPage = !!GM_getValue("disableNextPage");
  1730. let nextPage = createOption(i18n.nextPage, !disableNextPage, "checkbox");
  1731. let nextPageReg = createOption(i18n.nextPageReg, GM_getValue("nextPageReg") || "");
  1732. nextPageReg.setAttribute("placeHolder", "^\\s*(下一[页頁张張]|next\\s*page|次のページ)");
  1733. if (disableNextPage) {
  1734. nextPageReg.parentNode.style.display = "none";
  1735. }
  1736. nextPage.onclick = e => {
  1737. nextPageReg.parentNode.style.display = nextPage.checked ? "flex" : "none";
  1738. }
  1739. let saveBtn = document.createElement("button");
  1740. saveBtn.innerText = i18n.saveBtn;
  1741. saveBtn.style.margin = "0 0 20px 0";
  1742. insertPos.parentNode.insertBefore(saveBtn, insertPos);
  1743. saveBtn.onclick = e => {
  1744. GM_setValue("selectors", delSelector.value || "");
  1745. GM_setValue("downThreadNum", downThreadNum.value || 20);
  1746. GM_setValue("minTxtLength", minTxtLength.value || 100);
  1747. GM_setValue("customTitle", customTitle.value || "");
  1748. if (reSortUrl.checked) {
  1749. GM_setValue("contentSortUrl", true);
  1750. GM_setValue("contentSort", false);
  1751. } else if (contentSort.checked) {
  1752. GM_setValue("contentSortUrl", false);
  1753. GM_setValue("contentSort", true);
  1754. } else {
  1755. GM_setValue("contentSortUrl", false);
  1756. GM_setValue("contentSort", false);
  1757. }
  1758. GM_setValue("reverse", reverse.checked);
  1759. GM_setValue("retainImage", retainImage.checked);
  1760. GM_setValue("showFilterList", showFilterList.checked);
  1761. GM_setValue("disableNextPage", !nextPage.checked);
  1762. GM_setValue("nextPageReg", nextPageReg.value || "");
  1763. alert(i18n.saveOk);
  1764. };
  1765. return;
  1766. }
  1767.  
  1768. function setDel(){
  1769. GM_openInTab(configPage + "#操作說明", {active: true});
  1770. /*var selValue=GM_getValue("selectors");
  1771. var selectors=prompt(i18n.del,selValue?selValue:"");
  1772. GM_setValue("selectors",selectors);
  1773. selValue=GM_getValue("downThreadNum");
  1774. var downThreadNum=prompt(i18n.downThreadNum,selValue?selValue:"20");
  1775. GM_setValue("downThreadNum",downThreadNum);
  1776. var sortByUrl=window.confirm(i18n.reSortUrl);
  1777. GM_setValue("contentSortUrl",sortByUrl);
  1778. if(!sortByUrl)GM_setValue("contentSort",window.confirm(i18n.reSort));*/
  1779. }
  1780.  
  1781. document.addEventListener("keydown", function(e) {
  1782. if(e.keyCode == 120 && e.ctrlKey) {
  1783. fetch(e.shiftKey);
  1784. }
  1785. });
  1786. GM_registerMenuCommand(i18n.custom, () => {
  1787. var customRules = GM_getValue("DACrules_" + document.domain);
  1788. var urls = window.prompt(i18n.customInfo, customRules ? customRules : "https://xxx.xxx/book-[20-99].html, https://xxx.xxx/book-[01-10].html");
  1789. if (urls) {
  1790. customDown(urls);
  1791. }
  1792. });
  1793. GM_registerMenuCommand(i18n.fetch, fetch);
  1794. GM_registerMenuCommand(i18n.setting, setDel);
  1795. GM_registerMenuCommand(i18n.searchRule, searchRule);
  1796. })();