怠惰小说下载器

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

当前为 2024-10-26 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name DownloadAllContent
  3. // @name:zh-CN 怠惰小说下载器
  4. // @name:zh-TW 怠惰小説下載器
  5. // @name:ja 怠惰者小説ダウンロードツール
  6. // @namespace hoothin
  7. // @version 2.8.3.14
  8. // @description Lightweight web scraping script. 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 軽量なWebスクレイピングスクリプト。ユニバーサルサイトコンテンツクロールツール、クロール、フォーラム内容など
  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, nextPageFunc;
  227. const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;
  228. var win=(typeof unsafeWindow=='undefined'?window:unsafeWindow);
  229. switch (lang){
  230. case "zh-CN":
  231. case "zh-SG":
  232. i18n={
  233. fetch:"开始下载小说",
  234. info:"来源:#t#\n本文是使用怠惰小说下载器(DownloadAllContent)下载的",
  235. error:"该段内容获取失败",
  236. downloading:"已下载完成 %s 段,剩余 %s 段<br>正在下载 %s",
  237. complete:"已全部下载完成,共 %s 段",
  238. del:"设置文本干扰码的CSS选择器",
  239. custom:"自定规则下载",
  240. customInfo:"输入网址或者章节CSS选择器",
  241. reSort:"按标题名重新排序章节",
  242. reSortUrl:"按网址重新排序章节",
  243. setting:"选项参数设置",
  244. searchRule:"搜索网站规则",
  245. abort:"跳过此章",
  246. save:"保存当前",
  247. saveAsMd:"存为 Markdown",
  248. downThreadNum:"设置同时下载的线程数,负数为单线程下载间隔",
  249. enableTouch:"在移动端按→↓←↑的方向滑动屏幕画正方形立即开始下载",
  250. customTitle:"自定义章节标题,输入内页文字对应选择器",
  251. maxDlPerMin:"每分钟最大下载数",
  252. reSortDefault:"默认按页面中位置排序章节",
  253. reverseOrder:"反转章节排序",
  254. saveBtn:"保存设置",
  255. saveOk:"保存成功",
  256. nextPage:"嗅探章节内分页",
  257. nextPageReg:"自定义分页正则",
  258. retainImage:"保留正文中图片的网址",
  259. minTxtLength:"当检测到的正文字数小于此数,则尝试重新抓取",
  260. showFilterList:"下载前显示章节筛选排序窗口",
  261. ok:"确定",
  262. close:"关闭",
  263. dacSortByPos:"按页内位置排序",
  264. dacSortByUrl:"按网址排序",
  265. dacSortByName:"按章节名排序",
  266. reverse:"反选",
  267. dacUseIframe:"使用 iframe 后台加载内容(慢速)",
  268. dacSaveAsZip:"下载为 zip",
  269. dacSetCustomRule:"修改规则",
  270. dacAddUrl:"添加章节",
  271. dacStartDownload:"下载选中",
  272. downloadShortcut:"下载章节",
  273. downloadSingleShortcut:"下载单页",
  274. downloadCustomShortcut:"自定义下载"
  275. };
  276. break;
  277. case "zh":
  278. case "zh-TW":
  279. case "zh-HK":
  280. i18n={
  281. fetch:"開始下載小說",
  282. info:"來源:#t#\n本文是使用怠惰小說下載器(DownloadAllContent)下載的",
  283. error:"該段內容獲取失敗",
  284. downloading:"已下載完成 %s 段,剩餘 %s 段<br>正在下載 %s",
  285. complete:"已全部下載完成,共 %s 段",
  286. del:"設置文本干擾碼的CSS選擇器",
  287. custom:"自訂規則下載",
  288. customInfo:"輸入網址或者章節CSS選擇器",
  289. reSort:"按標題名重新排序章節",
  290. reSortUrl:"按網址重新排序章節",
  291. setting:"選項參數設定",
  292. searchRule:"搜尋網站規則",
  293. abort:"跳過此章",
  294. save:"保存當前",
  295. saveAsMd:"存爲 Markdown",
  296. downThreadNum:"設置同時下載的綫程數,負數為單線程下載間隔",
  297. enableTouch:"在行動端按→↓←↑的方向滑動螢幕畫方立即開始下載",
  298. customTitle:"自訂章節標題,輸入內頁文字對應選擇器",
  299. maxDlPerMin:"每分鐘最大下載數",
  300. reSortDefault:"預設依頁面中位置排序章節",
  301. reverseOrder:"反轉章節排序",
  302. saveBtn:"儲存設定",
  303. saveOk:"儲存成功",
  304. nextPage:"嗅探章節內分頁",
  305. nextPageReg:"自訂分頁正規",
  306. retainImage:"保留內文圖片的網址",
  307. minTxtLength:"當偵測到的正文字數小於此數,則嘗試重新抓取",
  308. showFilterList:"下載前顯示章節篩選排序視窗",
  309. ok:"確定",
  310. close:"關閉",
  311. dacSortByPos:"依頁內位置排序",
  312. dacSortByUrl:"依網址排序",
  313. dacSortByName:"依章節名排序",
  314. reverse:"反選",
  315. dacUseIframe:"使用 iframe 背景載入內容(慢速)",
  316. dacSaveAsZip:"下載為 zip",
  317. dacSetCustomRule:"修改規則",
  318. dacAddUrl:"新增章節",
  319. dacStartDownload:"下載選取",
  320. downloadShortcut:"下載章節",
  321. downloadSingleShortcut:"下載單頁",
  322. downloadCustomShortcut:"自設下載"
  323. };
  324. break;
  325. case "ar":
  326. case "ar-AE":
  327. case "ar-BH":
  328. case "ar-DZ":
  329. case "ar-EG":
  330. case "ar-IQ":
  331. case "ar-JO":
  332. case "ar-KW":
  333. case "ar-LB":
  334. case "ar-LY":
  335. case "ar-MA":
  336. case "ar-OM":
  337. case "ar-QA":
  338. case "ar-SA":
  339. case "ar-SY":
  340. case "ar-TN":
  341. case "ar-YE":
  342. i18n={
  343. encode: true,
  344. fetch: "%D8%AA%D8%AD%D9%85%D9%8A%D9%84",
  345. info: "%D8%A7%D9%84%D9%85%D8%B5%D8%AF%D8%B1:%20#t#%0A%D8%AA%D9%85%20%D8%AA%D9%86%D8%B2%D9%8A%D9%84%20%D8%A7%D9%84%D9%80%20TXT%20%D8%A8%D9%88%D8%A7%D8%B3%D8%B7%D8%A9%20'DownloadAllContent'",
  346. error: "%D9%81%D8%B4%D9%84%20%D9%81%D9%8A%20%D8%AA%D8%AD%D9%85%D9%8A%D9%84%20%D8%A7%D9%84%D9%81%D8%B5%D9%84%20%D8%A7%D9%84%D8%AD%D8%A7%D9%84%D9%8A",
  347. downloading: "......%25s%20%D8%AA%D8%AD%D9%85%D9%8A%D9%84%3Cbr%3E%D8%B5%D9%81%D8%AD%D8%A7%D8%AA%20%D9%85%D8%AA%D8%A8%D9%82%D9%8A%D8%A9%20%25s%20%D8%B5%D9%81%D8%AD%D8%A7%D8%AA%20%D8%AA%D9%85%20%D8%AA%D8%AD%D9%85%D9%8A%D9%84%D9%87%D8%A7%D8%8C%20%D9%87%D9%86%D8%A7%D9%83%20%25s",
  348. complete: "%D8%B5%D9%81%D8%AD%D8%A7%D8%AA%20%D9%81%D9%8A%20%D8%A7%D9%84%D9%85%D8%AC%D9%85%D9%88%D8%B9%20%25s%20%D8%A7%D9%83%D8%AA%D9%85%D9%84!%20%D8%AD%D8%B5%D9%84%D8%AA%20%D8%B9%D9%84%D9%89",
  349. del: "%D9%84%D8%AA%D8%AC%D8%A7%D9%87%D9%84%20CSS%20%D8%AA%D8%B9%D9%8A%D9%8A%D9%86%20%D9%85%D8%AD%D8%AF%D8%AF%D8%A7%D8%AA",
  350. custom: "%D8%AA%D8%AD%D9%85%D9%8A%D9%84%20%D9%85%D8%AE%D8%B5%D8%B5",
  351. customInfo: "%D9%84%D8%B1%D9%88%D8%A7%D8%A8%D8%B7%20%D8%A7%D9%84%D9%81%D8%B5%D9%88%D9%84%20sss%20%D8%A5%D8%AF%D8%AE%D8%A7%D9%84%20%D8%A7%D9%84%D8%B1%D9%88%D8%A7%D8%A8%D8%B7%20%D8%A3%D9%88%20%D9%85%D8%AD%D8%AF%D8%AF%D8%A7%D8%AA",
  352. reSort: "%D8%A5%D8%B9%D8%A7%D8%AF%D8%A9%20%D8%A7%D9%84%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8%20%D8%AD%D8%B3%D8%A8%20%D8%A7%D9%84%D8%B9%D9%86%D9%88%D8%A7%D9%86",
  353. reSortUrl: "%D8%A5%D8%B9%D8%A7%D8%AF%D8%A9%20%D8%A7%D9%84%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8%20%D8%AD%D8%B3%D8%A8%20%D8%A7%D9%84%D8%B1%D9%88%D8%A7%D8%A8%D8%B7",
  354. setting: "%D9%81%D8%AA%D8%AD%20%D8%A7%D9%84%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF%D8%A7%D8%AA",
  355. searchRule: "%D9%82%D8%A7%D8%B9%D8%AF%D8%A9%20%D8%A7%D9%84%D8%A8%D8%AD%D8%AB",
  356. abort: "%D8%A5%D9%8A%D9%82%D8%A7%D9%81",
  357. save: "%D8%AD%D9%81%D8%B8",
  358. saveAsMd: "Markdown%20%D8%AD%D9%81%D8%B8%20%D9%83%D9%80",
  359. downThreadNum: "%D8%AA%D8%B9%D9%8A%D9%8A%D9%86%20%D8%B9%D8%AF%D8%AF%20%D8%A7%D9%84%D8%AE%D9%8A%D9%88%D8%B7%20%D9%84%D9%84%D8%AA%D8%AD%D9%85%D9%8A%D9%84",
  360. enableTouch: "On%20the%20mobile%20device,%20slide%20the%20screen%20in%20the%20direction%20of%20%E2%86%92%E2%86%93%E2%86%90%E2%86%91%20to%20draw%20a%20square%20will%20start%20downloading%20immediately",
  361. customTitle: "%D8%AA%D8%AE%D8%B5%D9%8A%D8%B5%20%D8%B9%D9%86%D9%88%D8%A7%D9%86%20%D8%A7%D9%84%D9%81%D8%B5%D9%84%D8%8C%20%D8%A5%D8%AF%D8%AE%D8%A7%D9%84%20%D8%A7%D9%84%D9%85%D8%AD%D8%AF%D8%AF%20%D9%81%D9%8A%20%D8%A7%D9%84%D8%B5%D9%81%D8%AD%D8%A9%20%D8%A7%D9%84%D8%AF%D8%A7%D8%AE%D9%84%D9%8A%D8%A9",
  362. maxDlPerMin: "%D8%A7%D9%84%D8%AD%D8%AF%20%D8%A7%D9%84%D8%A3%D9%82%D8%B5%D9%89%20%D9%84%D8%B9%D8%AF%D8%AF%20%D8%A7%D9%84%D8%AA%D9%86%D8%B2%D9%8A%D9%84%D8%A7%D8%AA%20%D9%81%D9%8A%20%D8%A7%D9%84%D8%AF%D9%82%D9%8A%D9%82%D8%A9",
  363. reSortDefault: "%D8%A7%D9%84%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8%20%D8%A7%D9%84%D8%A7%D9%81%D8%AA%D8%B1%D8%A7%D8%B6%D9%8A%20%D8%AD%D8%B3%D8%A8%20%D8%A7%D9%84%D9%85%D9%88%D9%82%D8%B9%20%D9%81%D9%8A%20%D8%A7%D9%84%D8%B5%D9%81%D8%AD%D8%A9",
  364. reverseOrder: "%D8%B9%D9%83%D8%B3%20%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8%20%D8%A7%D9%84%D9%81%D8%B5%D9%88%D9%84",
  365. saveBtn: "%D8%AD%D9%81%D8%B8%20%D8%A7%D9%84%D8%A5%D8%B9%D8%AF%D8%A7%D8%AF%D8%A7%D8%AA",
  366. saveOk: "%D8%AA%D9%85%20%D8%A7%D9%84%D8%AD%D9%81%D8%B8",
  367. nextPage: "%D8%A7%D9%84%D8%AA%D8%AD%D9%82%D9%82%20%D9%85%D9%86%20%D8%A7%D9%84%D8%B5%D9%81%D8%AD%D8%A9%20%D8%A7%D9%84%D8%AA%D8%A7%D9%84%D9%8A%D8%A9%20%D9%81%D9%8A%20%D8%A7%D9%84%D9%81%D8%B5%D9%84",
  368. nextPageReg: "%D9%85%D8%AE%D8%B5%D8%B5%20%D9%84%D9%84%D8%B5%D9%81%D8%AD%D8%A9%20%D8%A7%D9%84%D8%AA%D8%A7%D9%84%D9%8A%D8%A9%20RegExp",
  369. retainImage: "%D8%A7%D9%84%D8%A7%D8%AD%D8%AA%D9%81%D8%A7%D8%B8%20%D8%A8%D8%B9%D9%86%D9%88%D8%A7%D9%86%20%D8%A7%D9%84%D8%B5%D9%88%D8%B1%D8%A9%20%D8%A5%D8%B0%D8%A7%20%D9%83%D8%A7%D9%86%D8%AA%20%D9%87%D9%86%D8%A7%D9%83%20%D8%B5%D9%88%D8%B1%20%D9%81%D9%8A%20%D8%A7%D9%84%D9%86%D8%B5",
  370. minTxtLength: "%D8%A7%D9%84%D9%85%D8%AD%D8%A7%D9%88%D9%84%D8%A9%20%D9%85%D8%B1%D8%A9%20%D8%A3%D8%AE%D8%B1%D9%89%20%D8%B9%D9%86%D8%AF%D9%85%D8%A7%20%D9%8A%D9%83%D9%88%D9%86%20%D8%B7%D9%88%D9%84%20%D8%A7%D9%84%D9%85%D8%AD%D8%AA%D9%88%D9%89%20%D8%A3%D9%82%D9%84%20%D9%85%D9%86%20%D9%87%D8%B0%D8%A7",
  371. showFilterList: "%D8%B9%D8%B1%D8%B6%20%D9%86%D8%A7%D9%81%D8%B0%D8%A9%20%D8%A7%D9%84%D8%AA%D8%B5%D9%81%D9%8A%D8%A9%20%D9%88%D8%A7%D9%84%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8%20%D9%82%D8%A8%D9%84%20%D8%A7%D9%84%D8%AA%D8%AD%D9%85%D9%8A%D9%84",
  372. ok: "%D9%85%D9%88%D8%A7%D9%81%D9%82",
  373. close: "%D8%A5%D8%BA%D9%84%D8%A7%D9%82",
  374. dacSortByPos: "%D8%A7%D9%84%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8%20%D8%AD%D8%B3%D8%A8%20%D8%A7%D9%84%D9%85%D9%88%D9%82%D8%B9",
  375. dacSortByUrl: "%D8%A7%D9%84%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8%20%D8%AD%D8%B3%D8%A8%20%D8%A7%D9%84%D8%B1%D8%A7%D8%A8%D8%B7",
  376. dacSortByName: "%D8%A7%D9%84%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8%20%D8%AD%D8%B3%D8%A8%20%D8%A7%D9%84%D8%A7%D8%B3%D9%85",
  377. reverse: "%D8%B9%D9%83%D8%B3%20%D8%A7%D9%84%D8%A7%D8%AE%D8%AA%D9%8A%D8%A7%D8%B1",
  378. dacUseIframe: "%D9%84%D8%AA%D8%AD%D9%85%D9%8A%D9%84%20%D8%A7%D9%84%D9%85%D8%AD%D8%AA%D9%88%D9%89%20(%D8%A8%D8%B7%D9%8A%D8%A1)%20iframe%20%D8%A7%D8%B3%D8%AA%D8%AE%D8%AF%D8%A7%D9%85",
  379. dacSaveAsZip: "zip%20%D8%AD%D9%81%D8%B8%20%D9%83%D9%80",
  380. dacSetCustomRule: "%D8%AA%D8%B9%D8%AF%D9%8A%D9%84%20%D8%A7%D9%84%D9%82%D9%88%D8%A7%D8%B9%D8%AF",
  381. dacAddUrl: "%D8%A5%D8%B6%D8%A7%D9%81%D8%A9%20%D9%81%D8%B5%D9%84",
  382. dacStartDownload: "%D8%AA%D8%AD%D9%85%D9%8A%D9%84%20%D8%A7%D9%84%D9%85%D8%AD%D8%AF%D8%AF",
  383. downloadShortcut: "%D8%AA%D8%AD%D9%85%D9%8A%D9%84%20%D8%A7%D9%84%D9%81%D8%B5%D9%84",
  384. downloadSingleShortcut: "%D8%AA%D8%AD%D9%85%D9%8A%D9%84%20%D8%B5%D9%81%D8%AD%D8%A9%20%D9%88%D8%A7%D8%AD%D8%AF%D8%A9",
  385. downloadCustomShortcut: "%D8%AA%D8%AD%D9%85%D9%8A%D9%84%20%D9%85%D8%AE%D8%B5%D8%B5"
  386. };
  387. break;
  388. default:
  389. i18n={
  390. fetch:"Download",
  391. info:"Source: #t#\nThe TXT is downloaded by 'DownloadAllContent'",
  392. error:"Failed in downloading current chapter",
  393. downloading:"%s pages are downloaded, there are still %s pages left<br>Downloading %s ......",
  394. complete:"Completed! Get %s pages in total",
  395. del:"Set css selectors for ignore",
  396. custom:"Custom to download",
  397. customInfo:"Input urls OR sss selectors for chapter links",
  398. reSort:"ReSort by title",
  399. reSortUrl:"Resort by URLs",
  400. setting:"Open Setting",
  401. searchRule:"Search rule",
  402. abort:"Abort",
  403. save:"Save",
  404. saveAsMd:"Save as Markdown",
  405. downThreadNum:"Set threadNum for download, negative means interval of single thread",
  406. enableTouch:"On the mobile device, slide the screen in the direction of →↓←↑ to draw a square will start downloading immediately",
  407. customTitle: "Customize the chapter title, enter the selector on inner page",
  408. maxDlPerMin:"Maximum number of downloads per minute",
  409. reSortDefault: "Default sort by position in the page",
  410. reverseOrder:"Reverse chapter ordering",
  411. saveBtn:"Save Setting",
  412. saveOk:"Save Over",
  413. nextPage:"Check next page in chapter",
  414. nextPageReg:"Custom RegExp of next page",
  415. retainImage:"Keep the URL of image if there are images in the text",
  416. minTxtLength:"Try to crawl again when the length of content is less than this",
  417. showFilterList: "Show chapter filtering and sorting window before downloading",
  418. ok:"OK",
  419. close:"Close",
  420. dacSortByPos:"Sort by position",
  421. dacSortByUrl:"Sort by URL",
  422. dacSortByName:"Sort by name",
  423. reverse:"Reverse selection",
  424. dacUseIframe: "Use iframe to load content (slow)",
  425. dacSaveAsZip: "Save as zip",
  426. dacSetCustomRule:"Modify rules",
  427. dacAddUrl:"Add Chapter",
  428. dacStartDownload:"Download selected",
  429. downloadShortcut:"Download chapter",
  430. downloadSingleShortcut:"Download single page",
  431. downloadCustomShortcut:"Custom download"
  432. };
  433. break;
  434. }
  435. if (i18n.encode) {
  436. for (let k in i18n) {
  437. if (k != "encode") {
  438. i18n[k] = decodeURI(i18n[k]);
  439. }
  440. }
  441. }
  442. var firefox=navigator.userAgent.toLowerCase().indexOf('firefox')!=-1,curRequests=[],useIframe=false,iframeSandbox=false,iframeInit=false;
  443. var filterListContainer,txtDownContent,txtDownWords,txtDownQuit,dacLinksCon,dacUseIframe,shadowContainer,downTxtShadowContainer;
  444.  
  445. const escapeHTMLPolicy = (win.trustedTypes && win.trustedTypes.createPolicy) ? win.trustedTypes.createPolicy('dac_default', {
  446. createHTML: (string, sink) => string
  447. }) : null;
  448.  
  449. function createHTML(html) {
  450. return escapeHTMLPolicy ? escapeHTMLPolicy.createHTML(html) : html;
  451. }
  452.  
  453. function str2Num(str) {
  454. 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\*\+]+/);
  455. if (!str) return 0;
  456. str = str[0];
  457. let mul = str.match(/(\d*)\*(\d+)/);
  458. while(mul) {
  459. let result = parseInt(mul[1] || 1) * parseInt(mul[2]);
  460. str = str.replace(mul[0], result);
  461. mul = str.match(/(\d+)\*(\d+)/);
  462. }
  463. let plus = str.match(/(\d+)\+(\d+)/);
  464. while(plus) {
  465. let result = parseInt(plus[1]) + parseInt(plus[2]);
  466. str = str.replace(plus[0], result);
  467. plus = str.match(/(\d+)\+(\d+)/);
  468. }
  469. return parseInt(str);
  470. }
  471.  
  472. var dragOverItem, dragFrom, linkDict;
  473. function createLinkItem(aEle) {
  474. let item = document.createElement("div");
  475. item.innerHTML = createHTML(`
  476. <input type="checkbox" checked>
  477. <a class="dacLink" draggable="false" target="_blank" href="${aEle.href}">${aEle.innerText || "📄"}</a>
  478. <span>🖱️</span>
  479. `);
  480. item.title = aEle.innerText;
  481. item.setAttribute("draggable", "true");
  482. item.addEventListener("dragover", e => {
  483. e.preventDefault();
  484. });
  485. item.addEventListener("dragenter", e => {
  486. if (dragOverItem) dragOverItem.style.opacity = "";
  487. item.style.opacity = 0.3;
  488. dragOverItem = item;
  489. });
  490. item.addEventListener('dragstart', e => {
  491. dragFrom = item;
  492. });
  493. item.addEventListener('drop', e => {
  494. if (!dragFrom) return;
  495. if (e.clientX < item.getBoundingClientRect().left + 142) {
  496. dacLinksCon.insertBefore(dragFrom, item);
  497. } else {
  498. if (item.nextElementSibling) {
  499. dacLinksCon.insertBefore(dragFrom, item.nextElementSibling);
  500. } else {
  501. dacLinksCon.appendChild(dragFrom);
  502. }
  503. }
  504. e.preventDefault();
  505. });
  506. linkDict[aEle.href] = item;
  507. dacLinksCon.appendChild(item);
  508. }
  509.  
  510. var saveAsZip = true;
  511. function filterList(list) {
  512. if (!GM_getValue("showFilterList")) {
  513. indexDownload(list);
  514. return;
  515. }
  516. if (txtDownContent) {
  517. txtDownContent.style.display = "none";
  518. }
  519. if (filterListContainer) {
  520. filterListContainer.style.display = "";
  521. filterListContainer.classList.remove("customRule");
  522. dacLinksCon.innerHTML = createHTML("");
  523. } else {
  524. document.addEventListener('dragend', e => {
  525. if (dragOverItem) dragOverItem.style.opacity = "";
  526. }, true);
  527. filterListContainer = document.createElement("div");
  528. filterListContainer.id = "filterListContainer";
  529. filterListContainer.innerHTML = createHTML(`
  530. <div id="dacFilterBg" style="height: 100%; width: 100%; position: fixed; top: 0; z-index: 2147483646; opacity: 0.3; filter: alpha(opacity=30); background-color: #000;"></div>
  531. <div id="filterListBody">
  532. <div class="dacCustomRule">
  533. ${i18n.custom}
  534. <textarea id="dacCustomInput"></textarea>
  535. <div class="fun">
  536. <input id="dacConfirmRule" value="${i18n.ok}" type="button"/>
  537. <input id="dacCustomClose" value="${i18n.close}" type="button"/>
  538. </div>
  539. </div>
  540. <div class="sort">
  541. <input id="dacSortByPos" value="${i18n.dacSortByPos}" type="button"/>
  542. <input id="dacSortByUrl" value="${i18n.dacSortByUrl}" type="button"/>
  543. <input id="dacSortByName" value="${i18n.dacSortByName}" type="button"/>
  544. <input id="reverse" value="${i18n.reverse}" type="button"/>
  545. </div>
  546. <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>
  547. <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>
  548. <div class="fun">
  549. <input id="dacSetCustomRule" value="${i18n.dacSetCustomRule}" type="button"/>
  550. <input id="dacAddUrl" value="${i18n.dacAddUrl}" type="button"/>
  551. <input id="dacStartDownload" value="${i18n.dacStartDownload}" type="button"/>
  552. <input id="dacLinksClose" value="${i18n.close}" type="button"/>
  553. </div>
  554. </div>`);
  555. let dacSortByPos = filterListContainer.querySelector("#dacSortByPos");
  556. let dacSortByUrl = filterListContainer.querySelector("#dacSortByUrl");
  557. let dacSortByName = filterListContainer.querySelector("#dacSortByName");
  558. let reverse = filterListContainer.querySelector("#reverse");
  559. let dacSetCustomRule = filterListContainer.querySelector("#dacSetCustomRule");
  560. let dacCustomInput = filterListContainer.querySelector("#dacCustomInput");
  561. let dacConfirmRule = filterListContainer.querySelector("#dacConfirmRule");
  562. let dacCustomClose = filterListContainer.querySelector("#dacCustomClose");
  563. let dacAddUrl = filterListContainer.querySelector("#dacAddUrl");
  564. let dacStartDownload = filterListContainer.querySelector("#dacStartDownload");
  565. let dacLinksClose = filterListContainer.querySelector("#dacLinksClose");
  566. let dacFilterBg = filterListContainer.querySelector("#dacFilterBg");
  567. let dacSaveAsZip = filterListContainer.querySelector("#dacSaveAsZip");
  568. dacUseIframe = filterListContainer.querySelector("#dacUseIframe");
  569. dacSaveAsZip.onchange = e => {
  570. saveAsZip = dacSaveAsZip.checked;
  571. };
  572. dacSortByPos.onclick = e => {
  573. let linkList = [].slice.call(dacLinksCon.children);
  574. if (linkList[0].children[1].href != list[0].href) {
  575. list.reverse().forEach(a => {
  576. let link = linkDict[a.href];
  577. if (!link) return;
  578. dacLinksCon.insertBefore(link, dacLinksCon.children[0]);
  579. });
  580. } else {
  581. list.forEach(a => {
  582. let link = linkDict[a.href];
  583. if (!link) return;
  584. dacLinksCon.insertBefore(link, dacLinksCon.children[0]);
  585. });
  586. }
  587. };
  588. dacSortByUrl.onclick = e => {
  589. let linkList = [].slice.call(dacLinksCon.children);
  590. linkList.sort((a, b) => {
  591. const nameA = a.children[1].href.toUpperCase();
  592. const nameB = b.children[1].href.toUpperCase();
  593. if (nameA < nameB) {
  594. return -1;
  595. }
  596. if (nameA > nameB) {
  597. return 1;
  598. }
  599. return 0;
  600. });
  601. if (linkList[0] == dacLinksCon.children[0]) {
  602. linkList = linkList.reverse();
  603. }
  604. linkList.forEach(link => {
  605. dacLinksCon.appendChild(link);
  606. });
  607. };
  608. dacSortByName.onclick = e => {
  609. let linkList = [].slice.call(dacLinksCon.children);
  610. linkList.sort((a, b) => {
  611. return str2Num(a.innerText) - str2Num(b.innerText);
  612. });
  613. if (linkList[0] == dacLinksCon.children[0]) {
  614. linkList = linkList.reverse();
  615. }
  616. linkList.forEach(link => {
  617. dacLinksCon.appendChild(link);
  618. });
  619. };
  620. reverse.onclick = e => {
  621. let linkList = [].slice.call(dacLinksCon.children);
  622. linkList.forEach(link => {
  623. link.children[0].checked=!link.children[0].checked;
  624. });
  625. };
  626. dacSetCustomRule.onclick = e => {
  627. filterListContainer.classList.add("customRule");
  628. dacCustomInput.value = GM_getValue("DACrules_" + document.domain) || "";
  629. };
  630. dacConfirmRule.onclick = e => {
  631. if (dacCustomInput.value) {
  632. customDown(dacCustomInput.value);
  633. }
  634. };
  635. dacCustomClose.onclick = e => {
  636. filterListContainer.classList.remove("customRule");
  637. };
  638. dacAddUrl.onclick = e => {
  639. let addUrls = window.prompt(i18n.customInfo, "https://xxx.xxx/book-[20-99].html, https://xxx.xxx/book-[01-10].html");
  640. if (!addUrls || !/^http|^ftp/.test(addUrls)) return;
  641. let index = 1;
  642. [].forEach.call(addUrls.split(","), function(i) {
  643. var curEle;
  644. var varNum = /\[\d+\-\d+\]/.exec(i);
  645. if (varNum) {
  646. varNum = varNum[0].trim();
  647. } else {
  648. curEle = document.createElement("a");
  649. curEle.href = i;
  650. curEle.innerText = "Added Url";
  651. createLinkItem(curEle);
  652. return;
  653. }
  654. var num1 = /\[(\d+)/.exec(varNum)[1].trim();
  655. var num2 = /(\d+)\]/.exec(varNum)[1].trim();
  656. var num1Int = parseInt(num1);
  657. var num2Int = parseInt(num2);
  658. var numLen = num1.length;
  659. var needAdd = num1.charAt(0) == "0";
  660. if (num1Int >= num2Int) return;
  661. for (var j = num1Int; j <= num2Int; j++) {
  662. var urlIndex = j.toString();
  663. if (needAdd) {
  664. while(urlIndex.length < numLen) urlIndex = "0" + urlIndex;
  665. }
  666. var curUrl = i.replace(/\[\d+\-\d+\]/, urlIndex).trim();
  667. curEle = document.createElement("a");
  668. curEle.href = curUrl;
  669. curEle.innerText = "Added Url " + index++;
  670. createLinkItem(curEle);
  671. }
  672. });
  673. };
  674. dacStartDownload.onclick = e => {
  675. let linkList = [].slice.call(dacLinksCon.querySelectorAll("input:checked+.dacLink"));
  676. useIframe = !!dacUseIframe.checked;
  677. indexDownload(linkList, true);
  678. };
  679. dacLinksClose.onclick = e => {
  680. filterListContainer.style.display = "none";
  681. };
  682. dacFilterBg.onclick = e => {
  683. filterListContainer.style.display = "none";
  684. };
  685. let listStyle = GM_addStyle(`
  686. #filterListContainer * {
  687. font-size: 13px;
  688. float: initial;
  689. background-image: initial;
  690. height: fit-content;
  691. color: black;
  692. }
  693. #filterListContainer.customRule .dacCustomRule {
  694. display: flex;
  695. }
  696. #filterListContainer .dacCustomRule>textarea {
  697. height: 300px;
  698. width: 100%;
  699. border: 1px #DADADA solid;
  700. background: #ededed70;
  701. margin: 5px;
  702. }
  703. #filterListContainer.customRule .dacCustomRule~* {
  704. display: none!important;
  705. }
  706. #dacLinksCon>div {
  707. padding: 5px 0;
  708. display: flex;
  709. }
  710. #dacLinksCon>div>a {
  711. max-width: 245px;
  712. display: inline-block;
  713. text-overflow: ellipsis;
  714. overflow: hidden;
  715. }
  716. #dacLinksCon>div>input {
  717. margin-right: 5px;
  718. }
  719. #filterListContainer .dacCustomRule {
  720. border-radius: 8px;
  721. font-weight: bold;
  722. font-size: 16px;
  723. outline: none;
  724. align-items: center;
  725. flex-wrap: nowrap;
  726. white-space: nowrap;
  727. flex-direction: column;
  728. display: none;
  729. }
  730. #filterListContainer input {
  731. border-width: 2px;
  732. border-style: outset;
  733. border-color: buttonface;
  734. border-image: initial;
  735. border: 1px #DADADA solid;
  736. padding: 5px;
  737. border-radius: 8px;
  738. font-weight: bold;
  739. font-size: 9pt;
  740. outline: none;
  741. cursor: pointer;
  742. line-height: initial;
  743. width: initial;
  744. min-width: initial;
  745. max-width: initial;
  746. height: initial;
  747. min-height: initial;
  748. max-height: initial;
  749. }
  750. #dacLinksCon>div:nth-of-type(4n),
  751. #dacLinksCon>div:nth-of-type(4n+1) {
  752. background: #ffffff;
  753. }
  754. #dacLinksCon>div:nth-of-type(4n+2),
  755. #dacLinksCon>div:nth-of-type(4n+3) {
  756. background: #f5f5f5;
  757. }
  758. #filterListContainer .fun,#filterListContainer .sort {
  759. display: flex;
  760. justify-content: space-around;
  761. flex-wrap: nowrap;
  762. width: 100%;
  763. height: 28px;
  764. }
  765. #filterListContainer input[type=button]:hover {
  766. border: 1px #C6C6C6 solid;
  767. box-shadow: 1px 1px 1px #EAEAEA;
  768. color: #333333;
  769. background: #F7F7F7;
  770. }
  771. #filterListContainer input[type=button]:active {
  772. box-shadow: inset 1px 1px 1px #DFDFDF;
  773. }
  774. #filterListBody {
  775. padding: 5px;
  776. box-sizing: border-box;
  777. overflow: hidden;
  778. width: 600px;
  779. height: auto;
  780. max-height: 80vh;
  781. min-height: 200px;
  782. position: fixed;
  783. left: 50%;
  784. top: 10%;
  785. margin-left: -300px;
  786. z-index: 2147483646;
  787. background-color: #ffffff;
  788. border: 1px solid #afb3b6;
  789. border-radius: 10px;
  790. opacity: 0.95;
  791. filter: alpha(opacity=95);
  792. box-shadow: 5px 5px 20px 0px #000;
  793. }
  794. @media screen and (max-width: 800px) {
  795. #filterListBody {
  796. width: 90%;
  797. margin-left: -45%;
  798. }
  799. }
  800. `);
  801. dacLinksCon = filterListContainer.querySelector("#dacLinksCon");
  802. shadowContainer = document.createElement("div");
  803. shadowContainer.id = "download-all-content";
  804. document.body.appendChild(shadowContainer);
  805. let shadow = shadowContainer.attachShadow({ mode: "open" });
  806. shadow.appendChild(listStyle);
  807. shadow.appendChild(filterListContainer);
  808. }
  809. if (shadowContainer.parentNode) shadowContainer.parentNode.removeChild(shadowContainer);
  810. linkDict = {};
  811. list.forEach(a => {
  812. createLinkItem(a);
  813. });
  814. dacUseIframe.checked = useIframe;
  815. document.body.appendChild(shadowContainer);
  816. }
  817.  
  818. function initTxtDownDiv() {
  819. if (txtDownContent) {
  820. txtDownContent.style.display = "";
  821. document.body.appendChild(downTxtShadowContainer);
  822. return;
  823. }
  824. txtDownContent = document.createElement("div");
  825. txtDownContent.id = "txtDownContent";
  826. downTxtShadowContainer = document.createElement("div");
  827. document.body.appendChild(downTxtShadowContainer);
  828. let shadow = downTxtShadowContainer.attachShadow({ mode: "open" });
  829. shadow.appendChild(txtDownContent);
  830. txtDownContent.innerHTML = createHTML(`
  831. <style>
  832. #txtDownContent>div{
  833. font-size:16px;
  834. color:#333333;
  835. width:342px;
  836. height:110px;
  837. position:fixed;
  838. left:50%;
  839. top:50%;
  840. margin-top:-25px;
  841. margin-left:-171px;
  842. z-index:2147483647;
  843. background-color:#ffffff;
  844. border:1px solid #afb3b6;
  845. border-radius:10px;
  846. opacity:0.95;
  847. filter:alpha(opacity=95);
  848. box-shadow:5px 5px 20px 0px #000;
  849. }
  850. #txtDownWords{
  851. position:absolute;
  852. width:275px;
  853. height: 90px;
  854. max-height: 90%;
  855. border: 1px solid #f3f1f1;
  856. padding: 8px;
  857. border-radius: 10px;
  858. overflow: auto;
  859. }
  860. #txtDownQuit{
  861. width: 30px;height: 30px;border-radius: 30px;position:absolute;right:2px;top:2px;cursor: pointer;background-color:#ff5a5a;
  862. }
  863. #txtDownQuit>span{
  864. 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;
  865. }
  866. #txtDownQuit+div{
  867. position:absolute;right:0px;bottom:2px;cursor: pointer;max-width:85px;
  868. }
  869. #txtDownQuit+div>button{
  870. background: #008aff;border: 0;padding: 5px;border-radius: 6px;color: white;float: right;margin: 1px;height: 25px;line-height: 16px;cursor: pointer;overflow: hidden;
  871. }
  872. </style>
  873. <div>
  874. <div id="txtDownWords">
  875. Analysing......
  876. </div>
  877. <div id="txtDownQuit">
  878. <span>╳</span>
  879. </div>
  880. <div>
  881. <button id="abortRequest" style="display:none;">${getI18n('abort')}</button>
  882. <button id="tempSaveTxt">${getI18n('save')}</button>
  883. <button id="saveAsMd" title="${getI18n('saveAsMd')}">Markdown</button>
  884. </div>
  885. </div>`);
  886. txtDownWords=txtDownContent.querySelector("#txtDownWords");
  887. txtDownQuit=txtDownContent.querySelector("#txtDownQuit");
  888. txtDownQuit.onclick=function(){
  889. txtDownContent.style.display="none";
  890. };
  891. initTempSave(txtDownContent);
  892. win.txtDownWords = txtDownWords;
  893. }
  894.  
  895. function saveContent() {
  896. if (win.downloadAllContentSaveAsZip && saveAsZip) {
  897. win.downloadAllContentSaveAsZip(rCats, i18n.info.replace("#t#", location.href), content => {
  898. saveAs(content, document.title.replace(/[\*\/:<>\?\\\|\r\n,]/g, "_") + ".zip");
  899. });
  900. } else {
  901. var blob = new Blob([i18n.info.replace("#t#", location.href) + "\r\n\r\n" + rCats.join("\r\n\r\n")], {type: "text/plain;charset=utf-8"});
  902. saveAs(blob, document.title.replace(/[\*\/:<>\?\\\|\r\n,]/g, "_") + ".txt");
  903. }
  904. }
  905.  
  906. function initTempSave(txtDownContent){
  907. var tempSavebtn = txtDownContent.querySelector('#tempSaveTxt');
  908. var abortbtn = txtDownContent.querySelector('#abortRequest');
  909. var saveAsMd = txtDownContent.querySelector('#saveAsMd');
  910. tempSavebtn.onclick = function(){
  911. saveContent();
  912. console.log(curRequests);
  913. }
  914. abortbtn.onclick = function(){
  915. let curRequest = curRequests.pop();
  916. if(curRequest)curRequest[1].abort();
  917. }
  918. saveAsMd.onclick = function(){
  919. let txt = i18n.info.replace("#t#", location.href)+"\n\n---\n"+document.title+"\n===\n";
  920. rCats.forEach(cat => {
  921. cat = cat.replace("\r\n", "\n---").replace(/(\r\n|\n\r)+/g, "\n\n").replace(/[\n\r]\t+/g, "\n");
  922. txt += '\n\n'+cat;
  923. });
  924. var blob = new Blob([txt], {type: "text/plain;charset=utf-8"});
  925. saveAs(blob, document.title.replace(/[\*\/:<>\?\\\|\r\n,]/g, "_") + ".md");
  926. }
  927. }
  928.  
  929. let charset = (document.characterSet || document.charset || document.inputEncoding);
  930. let equiv = document.querySelector('[http-equiv="Content-Type"]'), charsetValid = true;
  931. if (equiv && equiv.content) {
  932. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  933. if (!innerCharSet) {
  934. charsetValid = false;
  935. } else if (innerCharSet[1].replace("-", "").toLowerCase() != charset.replace("-", "").toLowerCase()) {
  936. charsetValid = false;
  937. }
  938. } else charsetValid = false;
  939. function indexDownload(aEles, noSort){
  940. if(aEles.length<1)return;
  941. initTxtDownDiv();
  942. if(!noSort) {
  943. if(GM_getValue("contentSort")){
  944. aEles.sort((a, b) => {
  945. return str2Num(a.innerText) - str2Num(b.innerText);
  946. });
  947. }
  948. if(GM_getValue("contentSortUrl")){
  949. aEles.sort((a, b) => {
  950. const nameA = a.href.toUpperCase();
  951. const nameB = b.href.toUpperCase();
  952. if (nameA < nameB) {
  953. return -1;
  954. }
  955. if (nameA > nameB) {
  956. return 1;
  957. }
  958. return 0;
  959. });
  960. }
  961. if(GM_getValue("reverse")){
  962. aEles=aEles.reverse();
  963. }
  964. }
  965. rCats=[];
  966. const minute=60000;
  967. var minTxtLength=GM_getValue("minTxtLength") || 100;
  968. var customTitle=GM_getValue("customTitle");
  969. var disableNextPage=!!GM_getValue("disableNextPage");
  970. var customNextPageReg=GM_getValue("nextPageReg");
  971. var maxDlPerMin=GM_getValue("maxDlPerMin") || 0;
  972. var dlCount=0;
  973. if (customNextPageReg) {
  974. try {
  975. innerNextPage = new RegExp(customNextPageReg);
  976. } catch(e) {
  977. console.warn(e);
  978. }
  979. }
  980. var insertSigns=[];
  981. // var j=0,rCats=[];
  982. var downIndex=0,downNum=0,downOnce=function(wait){
  983. if(downNum>=aEles.length)return;
  984. if(maxDlPerMin){
  985. if(dlCount===-1){
  986. setTimeout(() => {
  987. downOnce(wait);
  988. }, minute);
  989. return;
  990. }else if(dlCount>=maxDlPerMin){
  991. dlCount=-1;
  992. setTimeout(() => {
  993. dlCount=0;
  994. downOnce(wait);
  995. }, minute);
  996. return;
  997. }else dlCount++;
  998. }
  999. let curIndex=downIndex;
  1000. let aTag=aEles[curIndex];
  1001. let request=(aTag, curIndex)=>{
  1002. let tryTimes=0;
  1003. let validTimes=0;
  1004. function requestDoc(_charset) {
  1005. if (!_charset) _charset = charset;
  1006. return GM_xmlhttpRequest({
  1007. method: 'GET',
  1008. url: aTag.href,
  1009. headers:{
  1010. referer:aTag.href,
  1011. "Content-Type":"text/html;charset="+_charset
  1012. },
  1013. timeout:10000,
  1014. overrideMimeType:"text/html;charset="+_charset,
  1015. onload: async function(result) {
  1016. let doc = getDocEle(result.responseText);
  1017. if (charsetValid) {
  1018. let equiv = doc.querySelector('[http-equiv="Content-Type"]');
  1019. if (equiv && equiv.content) {
  1020. let innerCharSet = equiv.content.match(/charset\=([^;]+)/);
  1021. if (innerCharSet && innerCharSet[1].replace("-", "").toLowerCase() != _charset.replace("-", "").toLowerCase()) {
  1022. charset = innerCharSet[1];
  1023. return requestDoc(charset);
  1024. }
  1025. }
  1026. }
  1027. downIndex++;
  1028. downNum++;
  1029. if (/^{/.test(result.responseText)) {
  1030. doc.json = () => {
  1031. try {
  1032. return JSON.parse(result.responseText);
  1033. } catch(e) {}
  1034. return {};
  1035. }
  1036. }
  1037. let base = doc.querySelector("base");
  1038. let nextPages = !disableNextPage && !processFunc && await checkNextPage(doc, base ? base.href : aTag.href);
  1039. if (nextPages) {
  1040. if (!nextPages.length) nextPages = [nextPages];
  1041. nextPages.forEach(nextPage => {
  1042. var inArr=false;
  1043. for(var ai=0;ai<aEles.length;ai++){
  1044. if(aEles[ai].href==nextPage.href){
  1045. inArr=true;
  1046. break;
  1047. }
  1048. }
  1049. if(!inArr){
  1050. nextPage.innerText=aTag.innerText+"\t>>";
  1051. aEles.push(nextPage);
  1052. let targetIndex = curIndex;
  1053. for(let a=0;a<insertSigns.length;a++){
  1054. let signs=insertSigns[a],breakSign=false;
  1055. if(signs){
  1056. for(let b=0;b<signs.length;b++){
  1057. let sign=signs[b];
  1058. if(sign==curIndex){
  1059. targetIndex=a;
  1060. breakSign=true;
  1061. break;
  1062. }
  1063. }
  1064. }
  1065. if(breakSign)break;
  1066. }
  1067. let insertSign = insertSigns[targetIndex];
  1068. if(!insertSign)insertSigns[targetIndex] = [];
  1069. insertSigns[targetIndex].push(aEles.length-1);
  1070. }
  1071. });
  1072. }
  1073. if (result.status >= 400) {
  1074. console.warn("error:", `status: ${result.status} from: ${aTag.href}`);
  1075. } else {
  1076. console.log(result.status);
  1077. }
  1078. if (customTitle) {
  1079. try {
  1080. let title = doc.querySelector(customTitle);
  1081. if (title && title.innerText) {
  1082. aTag.innerText = title.innerText;
  1083. }
  1084. } catch(e) {
  1085. console.warn(e);
  1086. }
  1087. }
  1088. let validData = processDoc(curIndex, aTag, doc, (result.status>=400?` status: ${result.status} from: ${aTag.href} `:""), validTimes < 5);
  1089. if (!validData && validTimes++ < 5) {
  1090. downIndex--;
  1091. downNum--;
  1092. setTimeout(() => {
  1093. requestDoc();
  1094. }, Math.random() * 500 + validTimes * 1000);
  1095. return;
  1096. }
  1097. if (wait) {
  1098. setTimeout(() => {
  1099. downOnce(wait);
  1100. }, wait);
  1101. } else downOnce();
  1102. },
  1103. onerror: function(e) {
  1104. console.warn("error:", e, aTag.href);
  1105. if(tryTimes++ < 5){
  1106. setTimeout(() => {
  1107. requestDoc();
  1108. }, Math.random() * 500 + tryTimes * 1000);
  1109. return;
  1110. }
  1111. downIndex++;
  1112. downNum++;
  1113. processDoc(curIndex, aTag, null, ` NETWORK ERROR: ${(e.response||e.responseText)} from: ${aTag.href} `);
  1114. if (wait) {
  1115. setTimeout(() => {
  1116. downOnce(wait);
  1117. }, wait);
  1118. } else downOnce();
  1119. },
  1120. ontimeout: function(e) {
  1121. console.warn("timeout: times="+(tryTimes+1)+" url="+aTag.href);
  1122. //console.log(e);
  1123. if(tryTimes++ < 5){
  1124. setTimeout(() => {
  1125. requestDoc();
  1126. }, Math.random() * 500 + tryTimes * 1000);
  1127. return;
  1128. }
  1129. downIndex++;
  1130. downNum++;
  1131. processDoc(curIndex, aTag, null, ` TIMEOUT: ${aTag.href} `);
  1132. if (wait) {
  1133. setTimeout(() => {
  1134. downOnce(wait);
  1135. }, wait);
  1136. } else downOnce();
  1137. }
  1138. });
  1139. };
  1140. if (useIframe) {
  1141. let iframe = document.createElement('iframe'), inited = false, failedTimes = 0;
  1142. let loadtimeout;
  1143. let loadIframe = src => {
  1144. iframe.src = src;
  1145. clearTimeout(loadtimeout);
  1146. loadtimeout = setTimeout(() => {
  1147. iframe.src = src;
  1148. }, 20000);
  1149. };
  1150. iframe.name = 'pagetual-iframe';
  1151. iframe.width = '100%';
  1152. iframe.height = '1000';
  1153. iframe.frameBorder = '0';
  1154. iframe.sandbox = iframeSandbox || "allow-same-origin allow-scripts allow-popups allow-forms";
  1155. 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;';
  1156. iframe.addEventListener('load', e => {
  1157. if (e.data != 'pagetual-iframe:DOMLoaded' && e.type != 'load') return;
  1158. if (inited) return;
  1159. inited = true;
  1160. clearTimeout(loadtimeout);
  1161. async function checkIframe() {
  1162. try {
  1163. let doc = iframe.contentDocument || iframe.contentWindow.document;
  1164. if (!doc || !doc.body) {
  1165. setTimeout(() => {
  1166. checkIframe();
  1167. }, 1000);
  1168. return;
  1169. }
  1170. doc.body.scrollTop = 9999999;
  1171. doc.documentElement.scrollTop = 9999999;
  1172. if (!processFunc && validTimes++ > 5 && failedTimes++ < 2) {
  1173. loadIframe(iframe.src);
  1174. validTimes = 0;
  1175. inited = false;
  1176. return;
  1177. }
  1178. let base = doc.querySelector("base");
  1179. let nextPages = !disableNextPage && !processFunc && await checkNextPage(doc, base ? base.href : aTag.href);
  1180. if (nextPages) {
  1181. if (!nextPages.length) nextPages = [nextPages];
  1182. nextPages.forEach(nextPage => {
  1183. var inArr=false;
  1184. for(var ai=0;ai<aEles.length;ai++){
  1185. if(aEles[ai].href==nextPage.href){
  1186. inArr=true;
  1187. break;
  1188. }
  1189. }
  1190. if(!inArr){
  1191. nextPage.innerText=aTag.innerText+"\t>>";
  1192. aEles.push(nextPage);
  1193. let targetIndex = curIndex;
  1194. for(let a=0;a<insertSigns.length;a++){
  1195. let signs=insertSigns[a],breakSign=false;
  1196. if(signs){
  1197. for(let b=0;b<signs.length;b++){
  1198. let sign=signs[b];
  1199. if(sign==curIndex){
  1200. targetIndex=a;
  1201. breakSign=true;
  1202. break;
  1203. }
  1204. }
  1205. }
  1206. if(breakSign)break;
  1207. }
  1208. let insertSign = insertSigns[targetIndex];
  1209. if(!insertSign)insertSigns[targetIndex] = [];
  1210. insertSigns[targetIndex].push(aEles.length-1);
  1211. }
  1212. });
  1213. }
  1214. if (customTitle) {
  1215. try {
  1216. let title = doc.querySelector(customTitle);
  1217. if (title && title.innerText) {
  1218. aTag.innerText = title.innerText;
  1219. }
  1220. } catch(e) {
  1221. console.warn(e);
  1222. }
  1223. }
  1224. downIndex++;
  1225. downNum++;
  1226. let validData = processDoc(curIndex, aTag, doc, "", failedTimes < 2);
  1227. if (!validData) {
  1228. downIndex--;
  1229. downNum--;
  1230. setTimeout(() => {
  1231. checkIframe();
  1232. }, 1000);
  1233. return;
  1234. }
  1235. if (wait) {
  1236. setTimeout(() => {
  1237. downOnce(wait);
  1238. }, wait);
  1239. } else downOnce();
  1240. } catch(e) {
  1241. console.debug("Stop as cors");
  1242. }
  1243. if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  1244. }
  1245. setTimeout(() => {
  1246. checkIframe();
  1247. }, 500);
  1248. }, false);
  1249. let checkReady = setInterval(() => {
  1250. let doc;
  1251. try {
  1252. doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
  1253. } catch(e) {
  1254. clearInterval(checkReady);
  1255. return;
  1256. }
  1257. if (doc) {
  1258. try {
  1259. Function('win', 'iframe', '"use strict";' + (iframeInit || "win.self=win.top;"))(iframe.contentWindow, iframe);
  1260. clearInterval(checkReady);
  1261. } catch(e) {
  1262. console.debug(e);
  1263. }
  1264. }
  1265. }, 50);
  1266. loadIframe(aTag.href);
  1267. document.body.appendChild(iframe);
  1268. return [curIndex, null, aTag.href];
  1269. } else {
  1270. return [curIndex, requestDoc(), aTag.href];
  1271. }
  1272. }
  1273. if(!aTag){
  1274. let waitAtagReadyInterval=setInterval(function(){
  1275. if(downNum>=aEles.length)clearInterval(waitAtagReadyInterval);
  1276. aTag=aEles[curIndex];
  1277. if(aTag){
  1278. clearInterval(waitAtagReadyInterval);
  1279. request(aTag, curIndex);
  1280. }
  1281. },1000);
  1282. return null;
  1283. }
  1284. let result = request(aTag, curIndex);
  1285. if (result) curRequests.push(result);
  1286. return result;
  1287. };
  1288. function getDocEle(str){
  1289. var doc = null;
  1290. try {
  1291. doc = document.implementation.createHTMLDocument('');
  1292. doc.documentElement.innerHTML = str;
  1293. }
  1294. catch (e) {
  1295. console.log('parse error');
  1296. }
  1297. return doc;
  1298. }
  1299. function sortInnerPage(){
  1300. var pageArrs=[],maxIndex=0,i,j;
  1301. for(i=0;i<insertSigns.length;i++){
  1302. var signs=insertSigns[i];
  1303. if(signs){
  1304. for(j=0;j<signs.length;j++){
  1305. var sign=signs[j];
  1306. var cat=rCats[sign];
  1307. rCats[sign]=null;
  1308. if(!pageArrs[i])pageArrs[i]=[];
  1309. pageArrs[i].push(cat);
  1310. }
  1311. }
  1312. }
  1313. for(i=pageArrs.length-1;i>=0;i--){
  1314. let pageArr=pageArrs[i];
  1315. if(pageArr){
  1316. for(j=pageArr.length-1;j>=0;j--){
  1317. rCats.splice(i+1, 0, pageArr[j]);
  1318. }
  1319. }
  1320. }
  1321. rCats = rCats.filter(function(e){return e!=null});
  1322. }
  1323. var waitForComplete;
  1324. function processDoc(i, aTag, doc, cause, check){
  1325. let cbFunc=content=>{
  1326. rCats[i]=(aTag.innerText.replace(/[\r\n\t]/g, "") + "\r\n" + (cause || '') + content.replace(/\s*$/, ""));
  1327. curRequests = curRequests.filter(function(e){return e[0]!=i});
  1328. txtDownContent.style.display="block";
  1329. txtDownWords.innerHTML=getI18n("downloading",[downNum,(aEles.length-downNum),aTag.innerText]);
  1330. if(downNum==aEles.length){
  1331. if(waitForComplete) clearTimeout(waitForComplete);
  1332. waitForComplete=setTimeout(()=>{
  1333. if(downNum==aEles.length){
  1334. txtDownWords.innerHTML=getI18n("complete",[downNum]);
  1335. sortInnerPage();
  1336. saveContent();
  1337. }
  1338. },3000);
  1339. }
  1340. };
  1341. let contentResult=getPageContent(doc, content=>{
  1342. cbFunc(content);
  1343. }, aTag.href);
  1344. if(contentResult!==false){
  1345. if(check && contentResult && contentResult.replace(/\s/g, "").length<minTxtLength){
  1346. return false;
  1347. }
  1348. cbFunc(contentResult);
  1349. }
  1350. return true;
  1351. }
  1352. var downThreadNum = parseInt(GM_getValue("downThreadNum"));
  1353. downThreadNum = downThreadNum || 20;
  1354. if (useIframe && downThreadNum > 5) {
  1355. downThreadNum = 5;
  1356. }
  1357. if (downThreadNum > 0) {
  1358. for (var i = 0; i < downThreadNum; i++) {
  1359. downOnce();
  1360. if (downIndex >= aEles.length - 1 || downIndex >= downThreadNum - 1) break;
  1361. else downIndex++;
  1362. }
  1363. } else {
  1364. downOnce(-downThreadNum * 1000);
  1365. }
  1366. }
  1367.  
  1368. function canonicalUri(src, baseUrl) {
  1369. if (!src) {
  1370. return "";
  1371. }
  1372. if (src.charAt(0) == "#") return baseUrl + src;
  1373. if (src.charAt(0) == "?") return baseUrl.replace(/^([^\?#]+).*/, "$1" + src);
  1374. let origin = location.protocol + '//' + location.host;
  1375. let url = baseUrl || origin;
  1376. url = url.replace(/(\?|#).*/, "");
  1377. if (/https?:\/\/[^\/]+$/.test(url)) url = url + '/';
  1378. if (url.indexOf("http") !== 0) url = origin + url;
  1379. var root_page = /^[^\?#]*\//.exec(url)[0],
  1380. root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  1381. absolute_regex = /^\w+\:\/\//;
  1382. while (src.indexOf("../") === 0) {
  1383. src = src.substr(3);
  1384. root_page = root_page.replace(/\/[^\/]+\/$/, "/");
  1385. }
  1386. src = src.replace(/\.\//, "");
  1387. if (/^\/\/\/?/.test(src)) {
  1388. src = location.protocol + src;
  1389. }
  1390. return (absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src));
  1391. }
  1392.  
  1393. async function checkNextPage(doc, baseUrl) {
  1394. let nextPage = null;
  1395. if (nextPageFunc) {
  1396. nextPage = await nextPageFunc(doc, baseUrl);
  1397. if (nextPage && nextPage.length === 0) nextPage = null;
  1398. } else {
  1399. let aTags = doc.querySelectorAll("a");
  1400. for (var i = 0; i < aTags.length; i++) {
  1401. let aTag = aTags[i];
  1402. if (innerNextPage.test(aTag.innerText) && aTag.href && !/javascript:|#/.test(aTag.href)) {
  1403. let nextPageHref = canonicalUri(aTag.getAttribute("href"), baseUrl || location.href);
  1404. if (nextPageHref != location.href) {
  1405. nextPage = aTag;
  1406. nextPage.href = nextPageHref;
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. }
  1412. return nextPage;
  1413. }
  1414.  
  1415. function textNodesUnder(el){
  1416. var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  1417. while(n=walk.nextNode()) a.push(n);
  1418. return a;
  1419. }
  1420.  
  1421. function getPageContent(doc, cb, url){
  1422. if(!doc)return i18n.error;
  1423. if(doc.body && !doc.body.children.length)return doc.body.innerText;
  1424. if(processFunc){
  1425. return processFunc(doc, cb, url);
  1426. }
  1427. [].forEach.call(doc.querySelectorAll("span,div,ul"),function(item){
  1428. var thisStyle=doc.defaultView?doc.defaultView.getComputedStyle(item):item.style;
  1429. if(thisStyle && (thisStyle.display=="none" || (item.nodeName=="SPAN" && thisStyle.fontSize=="0px"))){
  1430. item.innerHTML="";
  1431. }
  1432. });
  1433. var i,j,k,rStr="",pageData=(doc.body?doc.body:doc).cloneNode(true);
  1434. pageData.innerHTML=pageData.innerHTML.replace(/\<\!\-\-((.|[\n|\r|\r\n])*?)\-\-\>/g,"");
  1435. [].forEach.call(pageData.querySelectorAll("font.jammer"),function(item){
  1436. item.innerHTML="";
  1437. });
  1438. var selectors=GM_getValue("selectors");
  1439. if(selectors){
  1440. [].forEach.call(pageData.querySelectorAll(selectors),function(item){
  1441. item.innerHTML="";
  1442. });
  1443. }
  1444. [].forEach.call(pageData.querySelectorAll("script,style,link,noscript,iframe"),function(item){
  1445. if (item && item.parentNode) {
  1446. item.parentNode.removeChild(item);
  1447. }
  1448. });
  1449. var endEle = ele => {
  1450. return /^(I|STRONG|B|FONT|P|DL|DD|H\d)$/.test(ele.nodeName) && ele.children.length <= 1;
  1451. };
  1452. var largestContent,contents=pageData.querySelectorAll("span,div,article,p,td,pre"),largestNum=0;
  1453. for(i=0;i<contents.length;i++){
  1454. let content=contents[i],hasText=false,allSingle=true,item,curNum=0;
  1455. if(/footer/.test(content.className))continue;
  1456. for(j=content.childNodes.length-1;j>=0;j--){
  1457. item=content.childNodes[j];
  1458. if(item.nodeType==3){
  1459. if(/^\s*$/.test(item.data)){
  1460. item.innerHTML="";
  1461. }else hasText=true;
  1462. }else if(/^(I|A|STRONG|B|FONT|P|DL|DD|H\d)$/.test(item.nodeName)){
  1463. hasText=true;
  1464. }else if(item.nodeType==1&&item.children.length==1&&/^(I|A|STRONG|B|FONT|P|DL|DD|H\d)$/.test(item.children[0].nodeName)){
  1465. hasText=true;
  1466. }
  1467. }
  1468. for(j=content.childNodes.length-1;j>=0;j--){
  1469. item=content.childNodes[j];
  1470. if(item.nodeType==1 && !/^(I|A|STRONG|B|FONT|BR)$/.test(item.nodeName) && /^[\s\-\_\?\>\|]*$/.test(item.innerHTML)){
  1471. item.innerHTML="";
  1472. }
  1473. }
  1474. if(content.childNodes.length>1){
  1475. let indexItem=0;
  1476. for(j=0;j<content.childNodes.length;j++){
  1477. item=content.childNodes[j];
  1478. if(item.nodeType==1){
  1479. if(item.innerText && item.innerText.length<50 && indexReg.test(item.innerText))indexItem++;
  1480. for(k=0;k<item.childNodes.length;k++){
  1481. var childNode=item.childNodes[k];
  1482. if(childNode.nodeType!=3 && !/^(I|A|STRONG|B|FONT|BR)$/.test(childNode.nodeName)){
  1483. allSingle=false;
  1484. break;
  1485. }
  1486. }
  1487. if(!allSingle)break;
  1488. }
  1489. }
  1490. if(indexItem>=5)continue;
  1491. }else{
  1492. allSingle=false;
  1493. }
  1494. if(!allSingle && !hasText){
  1495. continue;
  1496. }else {
  1497. if(pageData==document && content.offsetWidth<=0 && content.offsetHeight<=0){
  1498. continue;
  1499. }
  1500. [].forEach.call(content.childNodes,function(item){
  1501. if(item.nodeType==3)curNum+=item.data.trim().length;
  1502. 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);
  1503. });
  1504. }
  1505. if(curNum>largestNum){
  1506. largestNum=curNum;
  1507. largestContent=content;
  1508. }
  1509. }
  1510. if(!largestContent)return i18n.error+" : NO TEXT CONTENT";
  1511. var retainImage=!!GM_getValue("retainImage");
  1512. function getContentByLargest() {
  1513. var childlist=pageData.querySelectorAll(largestContent.nodeName);//+(largestContent.className?"."+largestContent.className.replace(/(^\s*)|(\s*$)/g, '').replace(/\s+/g, '.'):""));
  1514. function getRightStr(ele, noTextEnable){
  1515. [].forEach.call(ele.querySelectorAll("a[href]"), a => {
  1516. a.parentNode && a.parentNode.removeChild(a);
  1517. });
  1518. if(retainImage){
  1519. [].forEach.call(ele.querySelectorAll("img[src]"), img => {
  1520. let imgTxtNode=document.createTextNode(`![img](${canonicalUri(img.getAttribute("src"), url || location.href)})`);
  1521. img.parentNode.replaceChild(imgTxtNode, img);
  1522. });
  1523. }
  1524. let childNodes=ele.childNodes,cStr="\r\n",hasText=false;
  1525. for(let j=0;j<childNodes.length;j++){
  1526. let childNode=childNodes[j];
  1527. if(childNode.nodeType==3 && childNode.data && !/^[\s\-\_\?\>\|]*$/.test(childNode.data))hasText=true;
  1528. if(childNode.innerHTML){
  1529. childNode.innerHTML=childNode.innerHTML.replace(/\<\s*br\s*\>/gi,"\r\n").replace(/\n+/gi,"\n").replace(/\r+/gi,"\r");
  1530. }
  1531. let content=childNode.textContent;
  1532. if(content){
  1533. if(!content.trim())continue;
  1534. cStr+=content.replace(/[\uFEFF\xA0 ]+/g," ").replace(/([^\r]|^)\n([^\r]|$)/gi,"$1\r\n$2");
  1535. }
  1536. if(childNode.nodeType!=3 && !/^(I|A|STRONG|B|FONT|IMG)$/.test(childNode.nodeName))cStr+="\r\n";
  1537. else if(childNode.nextSibling && /^P$/.test(childNode.nextSibling.nodeName))cStr+="\r\n";
  1538. }
  1539. if(hasText || noTextEnable || ele==largestContent)rStr+=cStr+"\r\n";
  1540. }
  1541. var sameDepthChildren=[];
  1542. for(i=0;i<childlist.length;i++){
  1543. var child=childlist[i];
  1544. if(getDepth(child)==getDepth(largestContent)){
  1545. if(largestContent.className != child.className)continue;
  1546. sameDepthChildren.push(child);
  1547. }
  1548. }
  1549. var minLength = largestNum>>2;
  1550. var tooShort = sameDepthChildren.length <= 3;
  1551. sameDepthChildren.forEach(child => {
  1552. if(tooShort && child.innerText.length < minLength) return;
  1553. if((largestContent.className && largestContent.className == child.className) || largestContent.parentNode == child.parentNode){
  1554. getRightStr(child, true);
  1555. }else {
  1556. getRightStr(child, false);
  1557. }
  1558. });
  1559. rStr = rStr.replace(/[\n\r]+/g,"\n\r");
  1560. }
  1561. getContentByLargest();
  1562. if (rStr.length < 100) {
  1563. let articles = pageData.querySelectorAll("article");
  1564. if (articles && articles.length == 1) {
  1565. largestContent = articles[0];
  1566. largestNum = largestContent.innerText.length;
  1567. if (largestNum > 100) {
  1568. rStr = "";
  1569. getContentByLargest();
  1570. }
  1571. }
  1572. }
  1573. return rStr;
  1574. }
  1575.  
  1576. function getI18n(key, args){
  1577. var resultStr=i18n[key];
  1578. if(args && args.length>0){
  1579. args.forEach(function(item){
  1580. resultStr=resultStr.replace(/%s/,item);
  1581. });
  1582. }
  1583. return resultStr;
  1584. }
  1585.  
  1586. function getDepth(dom){
  1587. var pa=dom,i=0;
  1588. while(pa.parentNode){
  1589. pa=pa.parentNode;
  1590. i++;
  1591. }
  1592. return i;
  1593. }
  1594.  
  1595. async function sleep(time) {
  1596. await new Promise((resolve) => {
  1597. setTimeout(() => {
  1598. resolve();
  1599. }, time);
  1600. })
  1601. }
  1602.  
  1603. async function fetch(forceSingle){
  1604. forceSingle=forceSingle===true;
  1605. processFunc=null;
  1606. initTxtDownDiv();
  1607. var aEles=document.body.querySelectorAll("a"),list=[];
  1608. txtDownWords.innerHTML=`Analysing ( 1/${aEles.length} )......`;
  1609. txtDownContent.style.pointerEvents="none";
  1610. for(var i=0;i<aEles.length;i++){
  1611. if (i % 100 == 0) {
  1612. await sleep(1);
  1613. }
  1614. txtDownWords.innerHTML=`Analysing ( ${i + 1}/${aEles.length} )......`;
  1615. var aEle=aEles[i],has=false;
  1616. if(aEle.dataset.href && (!aEle.href || aEle.href.indexOf("javascript")!=-1)){
  1617. aEle.href=aEle.dataset.href;
  1618. }
  1619. if(aEle.href==location.href)continue;
  1620. for(var j=0;j<list.length;j++){
  1621. if(list[j].href==aEle.href){
  1622. aEle=list[j];
  1623. list.splice(j,1);
  1624. list.push(aEle);
  1625. has=true;
  1626. break;
  1627. }
  1628. }
  1629. if(!has && aEle.href && /^http/i.test(aEle.href) && ((aEle.innerText.trim()!="" && indexReg.test(aEle.innerText.trim())) || /chapter[\-_]?\d/.test(aEle.href))){
  1630. list.push(aEle);
  1631. }
  1632. }
  1633. txtDownContent.style.display="none";
  1634. txtDownContent.style.pointerEvents="";
  1635. txtDownWords.innerHTML="Analysing......";
  1636. if(list.length>2 && !forceSingle){
  1637. useIframe = false;
  1638. filterList(list);
  1639. }else{
  1640. 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"});
  1641. saveAs(blob, document.title+".txt");
  1642. }
  1643. }
  1644.  
  1645. function customDown(urls){
  1646. processFunc = null;
  1647. useIframe = false;
  1648. if(urls){
  1649. urls=decodeURIComponent(urls.replace(/%/g,'%25'));
  1650. GM_setValue("DACrules_"+document.domain, urls);
  1651. var processEles=[];
  1652. let urlsArr=urls.split("@@"),eles=[];
  1653. if(/^http|^ftp/.test(urlsArr[0])){
  1654. [].forEach.call(urlsArr[0].split(","),function(i){
  1655. var curEle;
  1656. var varNum=/\[\d+\-\d+\]/.exec(i);
  1657. if(varNum){
  1658. varNum=varNum[0].trim();
  1659. }else{
  1660. curEle=document.createElement("a");
  1661. curEle.href=i;
  1662. curEle.innerText="Added Url";
  1663. processEles.push(curEle);
  1664. return;
  1665. }
  1666. var num1=/\[(\d+)/.exec(varNum)[1].trim();
  1667. var num2=/(\d+)\]/.exec(varNum)[1].trim();
  1668. var num1Int=parseInt(num1);
  1669. var num2Int=parseInt(num2);
  1670. var numLen=num1.length;
  1671. var needAdd=num1.charAt(0)=="0";
  1672. if(num1Int>=num2Int)return;
  1673. for(var j=num1Int;j<=num2Int;j++){
  1674. var urlIndex=j.toString();
  1675. if(needAdd){
  1676. while(urlIndex.length<numLen)urlIndex="0"+urlIndex;
  1677. }
  1678. var curUrl=i.replace(/\[\d+\-\d+\]/,urlIndex).trim();
  1679. curEle=document.createElement("a");
  1680. curEle.href=curUrl;
  1681. curEle.innerText="Added Url " + processEles.length.toString();
  1682. processEles.push(curEle);
  1683. }
  1684. });
  1685. }else{
  1686. let urlSel=urlsArr[0].split(">>");
  1687. try{
  1688. eles=document.querySelectorAll(urlSel[0]);
  1689. eles=[].filter.call(eles, ele=>{
  1690. return ele.nodeName=='BODY'||(!!ele.offsetParent&&getComputedStyle(ele).display!=='none');
  1691. })
  1692. }catch(e){}
  1693. if(eles.length==0){
  1694. eles=[];
  1695. var eleTxts=urlsArr[0].split(/(?<=[^\\])[,,]/),exmpEles=[],excludeTxts={};
  1696. [].forEach.call(document.querySelectorAll("a"),function(item){
  1697. if(!item.offsetParent)return;
  1698. eleTxts.forEach(txt=>{
  1699. var txtArr=txt.split("!");
  1700. if(item.innerText.indexOf(txtArr[0])!=-1){
  1701. exmpEles.push(item);
  1702. excludeTxts[item]=txtArr.splice(1);
  1703. }
  1704. });
  1705. })
  1706. exmpEles.forEach(e=>{
  1707. var cssSelStr="a",pa=e.parentNode,excludeTxt=excludeTxts[e];
  1708. if(e.className)cssSelStr+="."+CSS.escape(e.className.replace(/\s+/g, ".")).replace(/\\\./g, '.');
  1709. while(pa && pa.nodeName!="BODY"){
  1710. cssSelStr=pa.nodeName+">"+cssSelStr;
  1711. pa=pa.parentNode;
  1712. }
  1713. cssSelStr="body>"+cssSelStr;;
  1714. [].forEach.call(document.querySelectorAll(cssSelStr),function(item){
  1715. if(!item.offsetParent)return;
  1716. var isExclude=false;
  1717. for(var t in excludeTxt){
  1718. if(item.innerText.indexOf(excludeTxt[t])!=-1){
  1719. isExclude=true;
  1720. break;
  1721. }
  1722. }
  1723. if(!isExclude && eles.indexOf(item)==-1){
  1724. eles.push(item);
  1725. }
  1726. });
  1727. });
  1728. }
  1729. function addItem(item) {
  1730. let has=false;
  1731. for(var j=0;j<processEles.length;j++){
  1732. if(processEles[j].href==item.href){
  1733. processEles.splice(j,1);
  1734. processEles.push(item);
  1735. has=true;
  1736. break;
  1737. }
  1738. }
  1739. if((!item.href || item.href.indexOf("javascript")!=-1) && item.dataset.href){
  1740. item.href=item.dataset.href;
  1741. }
  1742. if(!has && item.href && /^http/i.test(item.href)){
  1743. processEles.push(item.cloneNode(1));
  1744. }
  1745. }
  1746. [].forEach.call(eles,function(item){
  1747. if(urlSel[1]){
  1748. item=Function("item",urlSel[1])(item);
  1749. let items;
  1750. if (Array.isArray(item)) {
  1751. items = item;
  1752. } else items = [item];
  1753. items.forEach(item => {
  1754. if(!item || !item.href)return;
  1755. if(!item.nodeName || item.nodeName!="A"){
  1756. let href=item.href;
  1757. let innerText=item.innerText;
  1758. item=document.createElement("a");
  1759. item.href=href;
  1760. item.innerText=innerText;
  1761. }
  1762. addItem(item);
  1763. });
  1764. } else {
  1765. addItem(item);
  1766. }
  1767. });
  1768. }
  1769. if(urlsArr[1]){
  1770. processEles.forEach(ele=>{
  1771. ele.href=ele.href.replace(new RegExp(urlsArr[1]), urlsArr[2]);
  1772. });
  1773. }
  1774. var retainImage=!!GM_getValue("retainImage");
  1775. var evalCode = urlsArr[3];
  1776. if (evalCode) {
  1777. evalCode = evalCode.trim();
  1778. if (/^iframe:/.test(evalCode)) {
  1779. evalCode = evalCode.replace("iframe:", "");
  1780. useIframe = true;
  1781. iframeSandbox = false;
  1782. iframeInit = false;
  1783. while (/^(sandbox|init):/.test(evalCode)) {
  1784. iframeSandbox = evalCode.match(/^sandbox:\{(.*?)\}/);
  1785. if (iframeSandbox) {
  1786. evalCode = evalCode.replace(iframeSandbox[0], "");
  1787. iframeSandbox = iframeSandbox[1];
  1788. }
  1789. iframeInit = evalCode.match(/^init:\{(.*?)\}/);
  1790. if (iframeInit) {
  1791. evalCode = evalCode.replace(iframeInit[0], "");
  1792. iframeInit = iframeInit[1];
  1793. }
  1794. }
  1795. }
  1796. let charsetMatch = evalCode.match(/^charset:{(.+?)}/);
  1797. if (charsetMatch) {
  1798. charset = charsetMatch[1];
  1799. evalCode = evalCode.replace(charsetMatch[0], "");
  1800. }
  1801. let nextMatch = evalCode.match(/^next:(\{+)/);
  1802. if (nextMatch) {
  1803. let splitLen = nextMatch[1].length;
  1804. nextMatch = evalCode.match(new RegExp(`^next:\\{{${splitLen}}(.*?)\\}{${splitLen}}`));
  1805. if (nextMatch) {
  1806. let nextCode = nextMatch[1];
  1807. evalCode = evalCode.replace(nextMatch[0], "");
  1808. nextPageFunc = async (doc, url) => {
  1809. let result;
  1810. if (/\breturn\b/.test(nextCode)) {
  1811. result = await new AsyncFunction('doc', 'url', '"use strict";' + nextCode)(doc, url);
  1812. } else {
  1813. try {
  1814. result = doc.querySelectorAll(nextCode);
  1815. if (result && result.length) {
  1816. [].forEach.call(result, ele => {
  1817. ele.href = canonicalUri(ele.getAttribute("href"), url || location.href);
  1818. });
  1819. } else result = null;
  1820. } catch(e) {}
  1821. }
  1822. return result;
  1823. }
  1824. }
  1825. }
  1826. }
  1827. if(evalCode){
  1828. processFunc=(data, cb, url)=>{
  1829. let doc=data;
  1830. if(evalCode.indexOf("return ")==-1){
  1831. if(evalCode.indexOf("@")==0){
  1832. let content="";
  1833. var selectors=GM_getValue("selectors");
  1834. if(selectors){
  1835. [].forEach.call(data.querySelectorAll(selectors),function(item){
  1836. item.innerHTML="";
  1837. });
  1838. }
  1839. [].forEach.call(data.querySelectorAll("script,style,link,noscript,iframe"),function(item){
  1840. if (item && item.parentNode) {
  1841. item.parentNode.removeChild(item);
  1842. }
  1843. });
  1844. if(retainImage){
  1845. [].forEach.call(data.querySelectorAll("img[src]"), img => {
  1846. let imgTxt=`![img](${canonicalUri(img.getAttribute("src"), location.href)})`;
  1847. let imgTxtNode=document.createTextNode(imgTxt);
  1848. img.parentNode.replaceChild(imgTxtNode, img);
  1849. });
  1850. }
  1851. [].forEach.call(data.querySelectorAll(evalCode.slice(1)), ele=>{
  1852. [].forEach.call(ele.childNodes, child=>{
  1853. if(child.innerHTML){
  1854. child.innerHTML=child.innerHTML.replace(/\<\s*br\s*\>/gi,"\r\n").replace(/\n+/gi,"\n").replace(/\r+/gi,"\r");
  1855. }
  1856. if(child.textContent){
  1857. content+=(child.textContent.replace(/ +/g," ").replace(/([^\r]|^)\n([^\r]|$)/gi,"$1\r\n$2")+"\r\n");
  1858. }
  1859. });
  1860. content+="\r\n";
  1861. });
  1862. return content;
  1863. }else return eval(evalCode);
  1864. }else{
  1865. return Function("data", "doc", "cb", "url", evalCode)(data, doc, cb, url);
  1866. }
  1867. };
  1868. }else{
  1869. if(win.dacProcess){
  1870. processFunc=win.dacProcess;
  1871. }
  1872. }
  1873. filterList(processEles);
  1874. }
  1875. }
  1876. const configPage = "https://hoothin.github.io/UserScripts/DownloadAllContent/";
  1877. 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>';
  1878. function searchRule(){
  1879. GM_openInTab(configPage + "#@" + location.hostname, {active: true});
  1880. }
  1881. var downloadShortcut = GM_getValue("downloadShortcut") || {ctrlKey: true, shiftKey: false, altKey: false, metaKey: false, key: 'F9'};
  1882. var downloadSingleShortcut = GM_getValue("downloadSingleShortcut") || {ctrlKey: true, shiftKey: true, altKey: false, metaKey: false, key: 'F9'};
  1883. var downloadCustomShortcut = GM_getValue("downloadCustomShortcut") || {ctrlKey: true, shiftKey: false, altKey: true, metaKey: false, key: 'F9'};
  1884.  
  1885. var enableTouch = GM_getValue("enableTouch");
  1886. if (enableTouch) {
  1887. const minLength = 256, tg = 0.5, atg = 2;
  1888. var lastX, lastY, signs, lastSign;
  1889. function tracer(e) {
  1890. let curX = e.changedTouches[0].clientX, curY = e.changedTouches[0].clientY;
  1891. let distanceX = curX - lastX, distanceY = curY - lastY;
  1892. let distance = distanceX * distanceX + distanceY * distanceY;
  1893. if (distance > minLength) {
  1894. lastX = curX;
  1895. lastY = curY;
  1896. let direction = "";
  1897. let slope = Math.abs(distanceY / distanceX);
  1898. if (slope > atg) {
  1899. if (distanceY > 0) {
  1900. direction = "↓";
  1901. } else {
  1902. direction = "↑";
  1903. }
  1904. } else if (slope < tg) {
  1905. if (distanceX > 0) {
  1906. direction = "→";
  1907. } else {
  1908. direction = "←";
  1909. }
  1910. }
  1911. if (direction && lastSign != direction) {
  1912. signs += direction;
  1913. lastSign = direction;
  1914. }
  1915. }
  1916. }
  1917. document.addEventListener("touchstart", function(e) {
  1918. lastX = e.changedTouches[0].clientX;
  1919. lastY = e.changedTouches[0].clientY;
  1920. lastSign = signs = "";
  1921. document.addEventListener("touchmove", tracer, false);
  1922. }, false);
  1923. document.addEventListener("touchend", function(e) {
  1924. document.removeEventListener("touchmove", tracer, false);
  1925. if (signs == "→↓←↑") {
  1926. e.stopPropagation();
  1927. e.preventDefault();
  1928. startCustom();
  1929. }
  1930. }, false);
  1931. }
  1932.  
  1933. if (location.origin + location.pathname == configPage) {
  1934. let exampleNode = document.getElementById("example");
  1935. if (!exampleNode) return;
  1936.  
  1937. exampleNode = exampleNode.parentNode;
  1938. let ruleList = exampleNode.nextElementSibling.nextElementSibling;
  1939. let searchInput = document.createElement("input");
  1940. let inputTimer;
  1941. function searchByInput() {
  1942. clearTimeout(inputTimer);
  1943. inputTimer = setTimeout(() => {
  1944. let curValue = searchInput.value;
  1945. let matchRules = [];
  1946. let dontMatchRules = [];
  1947. if (curValue) {
  1948. for (let i = 0; i < ruleList.children.length; i++) {
  1949. let curRule = ruleList.children[i];
  1950. let aHref = curRule.firstChild.href;
  1951. if (aHref.indexOf(curValue) == -1) {
  1952. dontMatchRules.push(curRule);
  1953. } else {
  1954. matchRules.push(curRule);
  1955. }
  1956. }
  1957. } else {
  1958. dontMatchRules = ruleList.children;
  1959. }
  1960. if (matchRules.length) {
  1961. for (let i = 0; i < dontMatchRules.length; i++) {
  1962. let curRule = dontMatchRules[i];
  1963. curRule.style.display = "none";
  1964. }
  1965. for (let i = 0; i < matchRules.length; i++) {
  1966. let curRule = matchRules[i];
  1967. curRule.style.display = "";
  1968. }
  1969. } else {
  1970. for (let i = 0; i < dontMatchRules.length; i++) {
  1971. let curRule = dontMatchRules[i];
  1972. curRule.style.display = "";
  1973. }
  1974. }
  1975. }, 500);
  1976. }
  1977. searchInput.style.margin = "10px";
  1978. searchInput.style.width = "100%";
  1979. searchInput.placeholder = i18n.searchRule;
  1980. searchInput.addEventListener("input", function(e) {
  1981. searchByInput();
  1982. });
  1983. if (location.hash) {
  1984. let hash = location.hash.slice(1);
  1985. if (hash.indexOf("@") == 0) {
  1986. setTimeout(() => {
  1987. exampleNode.scrollIntoView();
  1988. }, 500);
  1989. searchInput.value = hash.slice(1);
  1990. searchByInput();
  1991. }
  1992. }
  1993. [].forEach.call(ruleList.querySelectorAll("div.highlight"), highlight => {
  1994. highlight.style.position = "relative";
  1995. highlight.innerHTML = highlight.innerHTML + copySvg;
  1996. let svg = highlight.children[1];
  1997. svg.addEventListener("click", function(e) {
  1998. GM_setClipboard(highlight.children[0].innerText);
  1999. svg.style.opacity = 0;
  2000. setTimeout(() => {
  2001. svg.style.opacity = 1;
  2002. }, 1000);
  2003. });
  2004. });
  2005. exampleNode.parentNode.insertBefore(searchInput, ruleList);
  2006.  
  2007.  
  2008. let donateNode = document.querySelector("[alt='donate']");
  2009. if (!donateNode) return;
  2010. let insertPos = donateNode.parentNode.nextElementSibling;
  2011. let radioIndex = 0;
  2012. function createOption(_name, _value, _type) {
  2013. if (!_type) _type = "input";
  2014. let con = document.createElement("div");
  2015. let option = document.createElement("input");
  2016. let cap = document.createElement("b");
  2017. option.type = _type;
  2018. option.value = _value;
  2019. option.checked = _value;
  2020. cap.style.margin = "0px 10px 0px 0px";
  2021. if (_type == "radio") {
  2022. let label = document.createElement("label");
  2023. label.innerText = _name;
  2024. radioIndex++;
  2025. option.id = "radio" + radioIndex;
  2026. label.setAttribute("for", option.id);
  2027. cap.appendChild(label);
  2028. } else {
  2029. if (_type == "input") {
  2030. option.style.flexGrow = "1";
  2031. }
  2032. cap.innerText = _name;
  2033. }
  2034. con.style.margin = "10px 0";
  2035. con.style.display = "flex";
  2036. con.style.alignItems = "center";
  2037. con.appendChild(cap);
  2038. con.appendChild(option);
  2039. insertPos.parentNode.insertBefore(con, insertPos);
  2040. return option;
  2041. }
  2042. function formatShortcut(e) {
  2043. let result = [];
  2044. if (e.ctrlKey) {
  2045. result.push("Ctrl");
  2046. }
  2047. if (e.shiftKey) {
  2048. result.push("Shift");
  2049. }
  2050. if (e.altKey) {
  2051. result.push("Alt");
  2052. }
  2053. if (e.metaKey) {
  2054. result.push("Meta");
  2055. }
  2056. result.push(e.key);
  2057. return result.join(" + ");
  2058. }
  2059. function geneShortcutData(str) {
  2060. if (!str) return "";
  2061. let result = {ctrlKey: false, shiftKey: false, altKey: false, metaKey: false, key: ''};
  2062. str.split(" + ").forEach(item => {
  2063. switch(item) {
  2064. case "Ctrl":
  2065. result.ctrlKey = true;
  2066. break;
  2067. case "Shift":
  2068. result.shiftKey = true;
  2069. break;
  2070. case "Alt":
  2071. result.altKey = true;
  2072. break;
  2073. case "Meta":
  2074. result.metaKey = true;
  2075. break;
  2076. default:
  2077. result.key = item;
  2078. break;
  2079. }
  2080. });
  2081. return result;
  2082. }
  2083. let showFilterList = createOption(i18n.showFilterList, !!GM_getValue("showFilterList"), "checkbox");
  2084. let downloadShortcutInput = createOption(i18n.downloadShortcut, formatShortcut(downloadShortcut) || "");
  2085. let downloadSingleShortcutInput = createOption(i18n.downloadSingleShortcut, formatShortcut(downloadSingleShortcut) || "");
  2086. let downloadCustomShortcutInput = createOption(i18n.downloadCustomShortcut, formatShortcut(downloadCustomShortcut) || "");
  2087. downloadShortcutInput.setAttribute("readonly", "true");
  2088. downloadSingleShortcutInput.setAttribute("readonly", "true");
  2089. downloadCustomShortcutInput.setAttribute("readonly", "true");
  2090. downloadShortcutInput.style.cursor = "cell";
  2091. downloadSingleShortcutInput.style.cursor = "cell";
  2092. downloadCustomShortcutInput.style.cursor = "cell";
  2093. let keydonwHandler = e => {
  2094. if (e.key) {
  2095. if (e.key == "Backspace") {
  2096. e.target.value = "";
  2097. } else if (e.key != "Control" && e.key != "Shift" && e.key != "Alt" && e.key != "Meta") {
  2098. e.target.value = formatShortcut(e);
  2099. }
  2100. }
  2101. e.preventDefault();
  2102. e.stopPropagation();
  2103. };
  2104. downloadShortcutInput.addEventListener("keydown", keydonwHandler);
  2105. downloadSingleShortcutInput.addEventListener("keydown", keydonwHandler);
  2106. downloadCustomShortcutInput.addEventListener("keydown", keydonwHandler);
  2107. let enableTouchInput = createOption(i18n.enableTouch, !!enableTouch, "checkbox");
  2108.  
  2109. let delSelector = createOption(i18n.del, GM_getValue("selectors") || "");
  2110. delSelector.setAttribute("placeHolder", ".mask,.ksam");
  2111. let downThreadNum = createOption(i18n.downThreadNum, GM_getValue("downThreadNum") || "20", "number");
  2112. let maxDlPerMin = createOption(i18n.maxDlPerMin, GM_getValue("maxDlPerMin") || "0", "number");
  2113. let customTitle = createOption(i18n.customTitle, GM_getValue("customTitle") || "");
  2114. customTitle.setAttribute("placeHolder", "title");
  2115. let minTxtLength = createOption(i18n.minTxtLength, GM_getValue("minTxtLength") || "100", "number");
  2116. let contentSortUrlValue = GM_getValue("contentSortUrl") || false;
  2117. let contentSortValue = GM_getValue("contentSort") || false;
  2118. let reSortDefault = createOption(i18n.reSortDefault, !contentSortUrlValue && !contentSortValue, "radio");
  2119. let reSortUrl = createOption(i18n.reSortUrl, contentSortUrlValue || false, "radio");
  2120. let contentSort = createOption(i18n.reSort, contentSortValue || false, "radio");
  2121. reSortDefault.name = "sort";
  2122. reSortUrl.name = "sort";
  2123. contentSort.name = "sort";
  2124. let reverse = createOption(i18n.reverseOrder, !!GM_getValue("reverse"), "checkbox");
  2125. let disableNextPage = !!GM_getValue("disableNextPage");
  2126. let nextPage = createOption(i18n.nextPage, !disableNextPage, "checkbox");
  2127. let nextPageReg = createOption(i18n.nextPageReg, GM_getValue("nextPageReg") || "");
  2128. let retainImage = createOption(i18n.retainImage, !!GM_getValue("retainImage"), "checkbox");
  2129. nextPageReg.setAttribute("placeHolder", "^\\s*(下一[页頁张張]|next\\s*page|次のページ)");
  2130. if (disableNextPage) {
  2131. nextPageReg.parentNode.style.display = "none";
  2132. }
  2133. nextPage.onclick = e => {
  2134. nextPageReg.parentNode.style.display = nextPage.checked ? "flex" : "none";
  2135. }
  2136. let saveBtn = document.createElement("button");
  2137. saveBtn.innerText = i18n.saveBtn;
  2138. saveBtn.style.margin = "0 0 20px 0";
  2139. insertPos.parentNode.insertBefore(saveBtn, insertPos);
  2140. saveBtn.onclick = e => {
  2141. GM_setValue("selectors", delSelector.value || "");
  2142. GM_setValue("downThreadNum", parseInt(downThreadNum.value || 20));
  2143. GM_setValue("maxDlPerMin", parseInt(maxDlPerMin.value || 20));
  2144. GM_setValue("minTxtLength", parseInt(minTxtLength.value || 100));
  2145. GM_setValue("customTitle", customTitle.value || "");
  2146. if (reSortUrl.checked) {
  2147. GM_setValue("contentSortUrl", true);
  2148. GM_setValue("contentSort", false);
  2149. } else if (contentSort.checked) {
  2150. GM_setValue("contentSortUrl", false);
  2151. GM_setValue("contentSort", true);
  2152. } else {
  2153. GM_setValue("contentSortUrl", false);
  2154. GM_setValue("contentSort", false);
  2155. }
  2156. GM_setValue("reverse", reverse.checked);
  2157. GM_setValue("enableTouch", enableTouchInput.checked);
  2158. GM_setValue("retainImage", retainImage.checked);
  2159. GM_setValue("showFilterList", showFilterList.checked);
  2160. GM_setValue("disableNextPage", !nextPage.checked);
  2161. GM_setValue("nextPageReg", nextPageReg.value || "");
  2162. GM_setValue("downloadShortcut", geneShortcutData(downloadShortcutInput.value) || "");
  2163. GM_setValue("downloadSingleShortcut", geneShortcutData(downloadSingleShortcutInput.value) || "");
  2164. GM_setValue("downloadCustomShortcut", geneShortcutData(downloadCustomShortcutInput.value) || "");
  2165. alert(i18n.saveOk);
  2166. };
  2167. return;
  2168. }
  2169.  
  2170. function setDel(){
  2171. GM_openInTab(configPage + "#操作說明", {active: true});
  2172. }
  2173.  
  2174. function checkKey(shortcut1, shortcut2) {
  2175. return shortcut1.ctrlKey == shortcut2.ctrlKey && shortcut1.shiftKey == shortcut2.shiftKey && shortcut1.altKey == shortcut2.altKey && shortcut1.metaKey == shortcut2.metaKey && shortcut1.key == shortcut2.key;
  2176. }
  2177.  
  2178. function startCustom() {
  2179. var customRules = GM_getValue("DACrules_" + document.domain);
  2180. var urls = window.prompt(i18n.customInfo + ":\nhttps://xxx.xxx/book-[20-99].html, https://xxx.xxx/book-[01-10].html", customRules || "");
  2181. if (urls) {
  2182. customDown(urls);
  2183. }
  2184. }
  2185.  
  2186. document.addEventListener("keydown", function(e) {
  2187. if (checkKey(downloadCustomShortcut, e)) {
  2188. startCustom();
  2189. } else if (checkKey(downloadSingleShortcut, e)) {
  2190. fetch(true);
  2191. } else if (checkKey(downloadShortcut, e)) {
  2192. fetch(false);
  2193. }
  2194. });
  2195. GM_registerMenuCommand(i18n.custom, () => {
  2196. startCustom();
  2197. });
  2198. GM_registerMenuCommand(i18n.fetch, fetch);
  2199. GM_registerMenuCommand(i18n.setting, setDel);
  2200. GM_registerMenuCommand(i18n.searchRule, searchRule);
  2201. })();