1
0

single-file 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #!/usr/bin/env node
  2. /*
  3. * Copyright 2010-2020 Gildas Lormeau
  4. * contact : gildas.lormeau <at> gmail.com
  5. *
  6. * This file is part of SingleFile.
  7. *
  8. * The code in this file is free software: you can redistribute it and/or
  9. * modify it under the terms of the GNU Affero General Public License
  10. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  11. * of the License, or (at your option) any later version.
  12. *
  13. * The code in this file is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  16. * General Public License for more details.
  17. *
  18. * As additional permission under GNU AGPL version 3 section 7, you may
  19. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  20. * AGPL normally required by section 4, provided you include this license
  21. * notice and a URL through which recipients can access the Corresponding
  22. * Source.
  23. */
  24. /* global require, URL */
  25. const VALID_URL_TEST = /^(https?|file):\/\//;
  26. const fileUrl = require("file-url");
  27. const fs = require("fs");
  28. const options = require("./args");
  29. const backEnds = {
  30. jsdom: "./back-ends/jsdom.js",
  31. puppeteer: "./back-ends/puppeteer.js",
  32. "puppeteer-firefox": "./back-ends/puppeteer-firefox.js",
  33. "webdriver-chromium": "./back-ends/webdriver-chromium.js",
  34. "webdriver-gecko": "./back-ends/webdriver-gecko.js"
  35. };
  36. if (options.url && !VALID_URL_TEST.test(options.url)) {
  37. options.url = fileUrl(options.url);
  38. }
  39. options.retrieveLinks = true;
  40. options.browserScripts = options.browserScripts.map(path => require.resolve(path));
  41. const backend = require(backEnds[options.backEnd]);
  42. run(options);
  43. async function run(options) {
  44. await backend.initialize(options);
  45. let tasks;
  46. if (options.urlsFile) {
  47. tasks = fs.readFileSync(options.urlsFile).toString().split("\n")
  48. .map(url => createTask(url));
  49. } else {
  50. tasks = [createTask(options.url)];
  51. }
  52. tasks = tasks.filter(task => task);
  53. await runTasks(tasks);
  54. if (options.crawlReplaceURLs) {
  55. tasks.forEach(task => {
  56. try {
  57. let pageContent = fs.readFileSync(task.filename).toString();
  58. tasks.forEach(otherTask => {
  59. pageContent = pageContent.replace(new RegExp(escapeRegExp("\"" + otherTask.originalUrl + "\""), "gi"), "\"" + otherTask.filename + "\"");
  60. pageContent = pageContent.replace(new RegExp(escapeRegExp("'" + otherTask.originalUrl + "'"), "gi"), "'" + otherTask.filename + "'");
  61. const filename = otherTask.filename.replace(/ /g, "%20");
  62. pageContent = pageContent.replace(new RegExp(escapeRegExp("=" + otherTask.originalUrl + " "), "gi"), "=" + filename + " ");
  63. pageContent = pageContent.replace(new RegExp(escapeRegExp("=" + otherTask.originalUrl + ">"), "gi"), "=" + filename + ">");
  64. });
  65. fs.writeFileSync(task.filename, pageContent);
  66. } catch (error) {
  67. // ignored
  68. }
  69. });
  70. }
  71. if (!options.browserDebug) {
  72. return backend.closeBrowser();
  73. }
  74. }
  75. async function runTasks(tasks) {
  76. const availableTasks = tasks.filter(task => !task.status).length;
  77. const processingTasks = tasks.filter(task => task.status == "processing").length;
  78. const promisesTasks = [];
  79. for (let workerIndex = 0; workerIndex < Math.min(availableTasks, options.maxParallelWorkers - processingTasks); workerIndex++) {
  80. promisesTasks.push(runNextTask(tasks));
  81. }
  82. return Promise.all(promisesTasks);
  83. }
  84. async function runNextTask(tasks) {
  85. const task = tasks.find(task => !task.status);
  86. if (task) {
  87. let taskOptions = JSON.parse(JSON.stringify(options));
  88. taskOptions.url = task.url;
  89. task.status = "processing";
  90. const pageData = await capturePage(taskOptions);
  91. task.status = "processed";
  92. if (pageData) {
  93. task.filename = pageData.filename;
  94. if (options.crawlLinks && testMaxDepth(task)) {
  95. let newTasks = pageData.links
  96. .map(urlLink => createTask(urlLink, task, tasks[0]))
  97. .filter(task => task &&
  98. testMaxDepth(task) &&
  99. !tasks.find(otherTask => otherTask.url == task.url) &&
  100. (!options.crawlInnerLinksOnly || task.isInnerLink));
  101. tasks.splice(tasks.length, 0, ...newTasks);
  102. }
  103. }
  104. await runTasks(tasks);
  105. }
  106. }
  107. function testMaxDepth(task) {
  108. return (options.crawlMaxDepth == 0 || task.depth < options.crawlMaxDepth) &&
  109. (options.crawlExternalLinksMaxDepth == 0 || task.externalLinkDepth < options.crawlExternalLinksMaxDepth);
  110. }
  111. function createTask(url, parentTask, rootTask) {
  112. url = parentTask ? rewriteURL(url) : url;
  113. if (VALID_URL_TEST.test(url)) {
  114. const isInnerLink = rootTask && url.startsWith(getHostURL(rootTask.url));
  115. return {
  116. url,
  117. isInnerLink,
  118. originalUrl: url,
  119. depth: parentTask ? parentTask.depth + 1 : 0,
  120. externalLinkDepth: isInnerLink ? -1 : parentTask ? parentTask.externalLinkDepth + 1 : -1
  121. };
  122. }
  123. }
  124. function rewriteURL(url) {
  125. url = url.trim();
  126. options.urlRewriteRules.forEach(rewriteRule => {
  127. const parts = rewriteRule.trim().split(/ +/);
  128. if (parts.length == 2) {
  129. url = url.replace(new RegExp(parts[0]), parts[1]).trim();
  130. }
  131. });
  132. return url;
  133. }
  134. function getHostURL(url) {
  135. url = new URL(url);
  136. return url.protocol + "//" + (url.username ? url.username + (url.password || "") + "@" : "") + url.hostname;
  137. }
  138. async function capturePage(options) {
  139. try {
  140. const pageData = await backend.getPageData(options);
  141. if (options.output) {
  142. fs.writeFileSync(getFilename(options.output), pageData.content);
  143. } else {
  144. if (options.filenameTemplate && pageData.filename) {
  145. fs.writeFileSync(getFilename(pageData.filename), pageData.content);
  146. } else {
  147. console.log(pageData.content); // eslint-disable-line no-console
  148. }
  149. }
  150. return pageData;
  151. } catch (error) {
  152. const message = "URL: " + options.url + "\nStack: " + error.stack + "\n";
  153. if (options.errorFile) {
  154. fs.writeFileSync(options.errorFile, message, { flag: "a" });
  155. } else {
  156. console.error(message); // eslint-disable-line no-console
  157. }
  158. }
  159. }
  160. function getFilename(filename, index = 1) {
  161. let newFilename = filename;
  162. if (index > 1) {
  163. const regExpMatchExtension = /(\.[^.]+)$/;
  164. const matchExtension = newFilename.match(regExpMatchExtension);
  165. if (matchExtension && matchExtension[1]) {
  166. newFilename = newFilename.replace(regExpMatchExtension, " - " + index + matchExtension[1]);
  167. } else {
  168. newFilename += " - " + index;
  169. }
  170. }
  171. if (fs.existsSync(newFilename)) {
  172. return getFilename(filename, index + 1);
  173. } else {
  174. return newFilename;
  175. }
  176. }
  177. function escapeRegExp(string) {
  178. return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  179. }