single-file-cli-api.js 6.7 KB

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