single-file-cli-api.js 8.6 KB

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