singlefile-cli-api.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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, module, URL */
  25. const fs = require("fs");
  26. const VALID_URL_TEST = /^(https?|file):\/\//;
  27. const backEnds = {
  28. jsdom: "./back-ends/jsdom.js",
  29. puppeteer: "./back-ends/puppeteer.js",
  30. "puppeteer-firefox": "./back-ends/puppeteer-firefox.js",
  31. "webdriver-chromium": "./back-ends/webdriver-chromium.js",
  32. "webdriver-gecko": "./back-ends/webdriver-gecko.js"
  33. };
  34. let backend, tasks = [], maxParallelWorkers = 8;
  35. module.exports = initialize;
  36. async function initialize(options) {
  37. maxParallelWorkers = options.maxParallelWorkers;
  38. backend = require(backEnds[options.backEnd]);
  39. await backend.initialize(options);
  40. return {
  41. capture: urls => capture(urls, options),
  42. finish: () => finish(options),
  43. VALID_URL_TEST
  44. };
  45. }
  46. async function capture(urls, options) {
  47. let newTasks;
  48. newTasks = urls.map(url => createTask(url, options));
  49. newTasks = newTasks.filter(task => task);
  50. if (newTasks.length) {
  51. tasks = tasks.concat(newTasks);
  52. await runTasks();
  53. }
  54. }
  55. async function finish(options) {
  56. const promiseTasks = tasks.map(task => task.promise);
  57. await Promise.all(promiseTasks);
  58. if (options.crawlReplaceURLs) {
  59. tasks.forEach(task => {
  60. try {
  61. let pageContent = fs.readFileSync(task.filename).toString();
  62. tasks.forEach(otherTask => {
  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. fs.writeFileSync(task.filename, pageContent);
  70. } catch (error) {
  71. // ignored
  72. }
  73. });
  74. }
  75. if (!options.browserDebug) {
  76. return backend.closeBrowser();
  77. }
  78. }
  79. async function runTasks() {
  80. const availableTasks = tasks.filter(task => !task.status).length;
  81. const processingTasks = tasks.filter(task => task.status == "processing").length;
  82. const promisesTasks = [];
  83. for (let workerIndex = 0; workerIndex < Math.min(availableTasks, maxParallelWorkers - processingTasks); workerIndex++) {
  84. promisesTasks.push(runNextTask());
  85. }
  86. return Promise.all(promisesTasks);
  87. }
  88. async function runNextTask() {
  89. const task = tasks.find(task => !task.status);
  90. if (task) {
  91. const options = task.options;
  92. let taskOptions = JSON.parse(JSON.stringify(options));
  93. taskOptions.url = task.url;
  94. task.status = "processing";
  95. task.promise = capturePage(taskOptions);
  96. const pageData = await task.promise;
  97. task.status = "processed";
  98. if (pageData) {
  99. task.filename = pageData.filename;
  100. if (options.crawlLinks && testMaxDepth(task)) {
  101. let newTasks = pageData.links
  102. .map(urlLink => createTask(urlLink, options, task, tasks[0]))
  103. .filter(task => task &&
  104. testMaxDepth(task) &&
  105. !tasks.find(otherTask => otherTask.url == task.url) &&
  106. (!options.crawlInnerLinksOnly || task.isInnerLink));
  107. tasks.splice(tasks.length, 0, ...newTasks);
  108. }
  109. }
  110. await runTasks();
  111. }
  112. }
  113. function testMaxDepth(task) {
  114. const options = task.options;
  115. return (options.crawlMaxDepth == 0 || task.depth < options.crawlMaxDepth) &&
  116. (options.crawlExternalLinksMaxDepth == 0 || task.externalLinkDepth < options.crawlExternalLinksMaxDepth);
  117. }
  118. function createTask(url, options, parentTask, rootTask) {
  119. url = parentTask ? rewriteURL(url, options.crawlRemoveURLFragment, options.crawlRewriteRules) : url;
  120. if (VALID_URL_TEST.test(url)) {
  121. const isInnerLink = rootTask && url.startsWith(getHostURL(rootTask.url));
  122. return {
  123. url,
  124. isInnerLink,
  125. originalUrl: url,
  126. depth: parentTask ? parentTask.depth + 1 : 0,
  127. externalLinkDepth: isInnerLink ? -1 : parentTask ? parentTask.externalLinkDepth + 1 : -1,
  128. options
  129. };
  130. }
  131. }
  132. function rewriteURL(url, crawlRemoveURLFragment, crawlRewriteRules) {
  133. url = url.trim();
  134. if (crawlRemoveURLFragment) {
  135. url = url.replace(/^(.*?)#.*$/, "$1");
  136. }
  137. crawlRewriteRules.forEach(rewriteRule => {
  138. const parts = rewriteRule.trim().split(/ +/);
  139. if (parts.length) {
  140. url = url.replace(new RegExp(parts[0]), parts[1] || "").trim();
  141. }
  142. });
  143. return url;
  144. }
  145. function getHostURL(url) {
  146. url = new URL(url);
  147. return url.protocol + "//" + (url.username ? url.username + (url.password || "") + "@" : "") + url.hostname;
  148. }
  149. async function capturePage(options) {
  150. try {
  151. const pageData = await backend.getPageData(options);
  152. if (options.output) {
  153. fs.writeFileSync(getFilename(options.output), pageData.content);
  154. } else {
  155. if (options.filenameTemplate && pageData.filename) {
  156. fs.writeFileSync(getFilename(pageData.filename), pageData.content);
  157. } else {
  158. console.log(pageData.content); // eslint-disable-line no-console
  159. }
  160. }
  161. return pageData;
  162. } catch (error) {
  163. const message = "URL: " + options.url + "\nStack: " + error.stack + "\n";
  164. if (options.errorFile) {
  165. fs.writeFileSync(options.errorFile, message, { flag: "a" });
  166. } else {
  167. console.error(message); // eslint-disable-line no-console
  168. }
  169. }
  170. }
  171. function getFilename(filename, index = 1) {
  172. let newFilename = filename;
  173. if (index > 1) {
  174. const regExpMatchExtension = /(\.[^.]+)$/;
  175. const matchExtension = newFilename.match(regExpMatchExtension);
  176. if (matchExtension && matchExtension[1]) {
  177. newFilename = newFilename.replace(regExpMatchExtension, " - " + index + matchExtension[1]);
  178. } else {
  179. newFilename += " - " + index;
  180. }
  181. }
  182. if (fs.existsSync(newFilename)) {
  183. return getFilename(filename, index + 1);
  184. } else {
  185. return newFilename;
  186. }
  187. }
  188. function escapeRegExp(string) {
  189. return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  190. }