1
0

single-file-cli-api.js 7.7 KB

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