怠惰小说下载器

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

当前为 2024-12-03 提交的版本,查看 最新版本

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