singlefile-cli-api.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. pageContent = pageContent.replace(new RegExp(escapeRegExp("\"" + otherTask.originalUrl + "\""), "gi"), "\"" + otherTask.filename + "\"");
  63. pageContent = pageContent.replace(new RegExp(escapeRegExp("'" + otherTask.originalUrl + "'"), "gi"), "'" + otherTask.filename + "'");
  64. const filename = otherTask.filename.replace(/ /g, "%20");
  65. pageContent = pageContent.replace(new RegExp(escapeRegExp("=" + otherTask.originalUrl + " "), "gi"), "=" + filename + " ");
  66. pageContent = pageContent.replace(new RegExp(escapeRegExp("=" + otherTask.originalUrl + ">"), "gi"), "=" + filename + ">");
  67. });
  68. fs.writeFileSync(task.filename, pageContent);
  69. } catch (error) {
  70. // ignored
  71. }
  72. });
  73. }
  74. if (!options.browserDebug) {
  75. return backend.closeBrowser();
  76. }
  77. }
  78. async function runTasks() {
  79. const availableTasks = tasks.filter(task => !task.status).length;
  80. const processingTasks = tasks.filter(task => task.status == "processing").length;
  81. const promisesTasks = [];
  82. for (let workerIndex = 0; workerIndex < Math.min(availableTasks, maxParallelWorkers - processingTasks); workerIndex++) {
  83. promisesTasks.push(runNextTask());
  84. }
  85. return Promise.all(promisesTasks);
  86. }
  87. async function runNextTask() {
  88. const task = tasks.find(task => !task.status);
  89. if (task) {
  90. const options = task.options;
  91. let taskOptions = JSON.parse(JSON.stringify(options));
  92. taskOptions.url = task.url;
  93. task.status = "processing";
  94. task.promise = capturePage(taskOptions);
  95. const pageData = await task.promise;
  96. task.status = "processed";
  97. if (pageData) {
  98. task.filename = pageData.filename;
  99. if (options.crawlLinks && testMaxDepth(task)) {
  100. let newTasks = pageData.links
  101. .map(urlLink => createTask(urlLink, options, task, tasks[0]))
  102. .filter(task => task &&
  103. testMaxDepth(task) &&
  104. !tasks.find(otherTask => otherTask.url == task.url) &&
  105. (!options.crawlInnerLinksOnly || task.isInnerLink));
  106. tasks.splice(tasks.length, 0, ...newTasks);
  107. }
  108. }
  109. await runTasks();
  110. }
  111. }
  112. function testMaxDepth(task) {
  113. const options = task.options;
  114. return (options.crawlMaxDepth == 0 || task.depth < options.crawlMaxDepth) &&
  115. (options.crawlExternalLinksMaxDepth == 0 || task.externalLinkDepth < options.crawlExternalLinksMaxDepth);
  116. }
  117. function createTask(url, options, parentTask, rootTask) {
  118. url = parentTask ? rewriteURL(url, options.crawlRemoveURLFragment, options.crawlRewriteRules) : url;
  119. if (VALID_URL_TEST.test(url)) {
  120. const isInnerLink = rootTask && url.startsWith(getHostURL(rootTask.url));
  121. return {
  122. url,
  123. isInnerLink,
  124. originalUrl: url,
  125. depth: parentTask ? parentTask.depth + 1 : 0,
  126. externalLinkDepth: isInnerLink ? -1 : parentTask ? parentTask.externalLinkDepth + 1 : -1,
  127. options
  128. };
  129. }
  130. }
  131. function rewriteURL(url, crawlRemoveURLFragment, crawlRewriteRules) {
  132. url = url.trim();
  133. if (crawlRemoveURLFragment) {
  134. url = url.replace(/^(.*?)#.*$/, "$1");
  135. }
  136. crawlRewriteRules.forEach(rewriteRule => {
  137. const parts = rewriteRule.trim().split(/ +/);
  138. if (parts.length) {
  139. url = url.replace(new RegExp(parts[0]), parts[1] || "").trim();
  140. }
  141. });
  142. return url;
  143. }
  144. function getHostURL(url) {
  145. url = new URL(url);
  146. return url.protocol + "//" + (url.username ? url.username + (url.password || "") + "@" : "") + url.hostname;
  147. }
  148. async function capturePage(options) {
  149. try {
  150. const pageData = await backend.getPageData(options);
  151. if (options.output) {
  152. fs.writeFileSync(getFilename(options.output), pageData.content);
  153. } else {
  154. if (options.filenameTemplate && pageData.filename) {
  155. fs.writeFileSync(getFilename(pageData.filename), pageData.content);
  156. } else {
  157. console.log(pageData.content); // eslint-disable-line no-console
  158. }
  159. }
  160. return pageData;
  161. } catch (error) {
  162. const message = "URL: " + options.url + "\nStack: " + error.stack + "\n";
  163. if (options.errorFile) {
  164. fs.writeFileSync(options.errorFile, message, { flag: "a" });
  165. } else {
  166. console.error(message); // eslint-disable-line no-console
  167. }
  168. }
  169. }
  170. function getFilename(filename, index = 1) {
  171. let newFilename = filename;
  172. if (index > 1) {
  173. const regExpMatchExtension = /(\.[^.]+)$/;
  174. const matchExtension = newFilename.match(regExpMatchExtension);
  175. if (matchExtension && matchExtension[1]) {
  176. newFilename = newFilename.replace(regExpMatchExtension, " - " + index + matchExtension[1]);
  177. } else {
  178. newFilename += " - " + index;
  179. }
  180. }
  181. if (fs.existsSync(newFilename)) {
  182. return getFilename(filename, index + 1);
  183. } else {
  184. return newFilename;
  185. }
  186. }
  187. function escapeRegExp(string) {
  188. return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  189. }