single-file-cli-api.js 7.7 KB

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