single-file 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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, URL */
  25. const VALID_URL_TEST = /^(https?|file):\/\//;
  26. const fileUrl = require("file-url");
  27. const fs = require("fs");
  28. const options = require("./args");
  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. };
  36. options.compressCSS = options.compressCss;
  37. options.compressHTML = options.compressHtml;
  38. options.includeBOM = options.includeBom;
  39. options.crawlReplaceURLs = options.crawlReplaceUrls;
  40. if (options.url && !VALID_URL_TEST.test(options.url)) {
  41. options.url = fileUrl(options.url);
  42. }
  43. options.retrieveLinks = true;
  44. options.browserScripts = options.browserScripts.map(path => require.resolve(path));
  45. const backend = require(backEnds[options.backEnd]);
  46. run(options);
  47. async function run(options) {
  48. await backend.initialize(options);
  49. let tasks;
  50. if (options.urlsFile) {
  51. tasks = fs.readFileSync(options.urlsFile).toString().split("\n")
  52. .map(url => ({ url: rewriteURL(url, options.urlRewriteRules), originalUrl: url, depth: 0 }))
  53. .filter(task => task.url);
  54. } else {
  55. tasks = [{ url: rewriteURL(options.url, options.urlRewriteRules), originalUrl: options.url, depth: 0 }];
  56. }
  57. await runTasks(tasks, options);
  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(tasks, options) {
  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, options.maxParallelWorkers - processingTasks); workerIndex++) {
  84. promisesTasks.push(runNextTask(tasks, options));
  85. }
  86. await Promise.all(promisesTasks);
  87. }
  88. async function runNextTask(tasks, options) {
  89. const task = tasks.find(task => !task.status);
  90. if (task) {
  91. options = JSON.parse(JSON.stringify(options));
  92. options.url = task.url;
  93. task.status = "processing";
  94. const pageData = await capturePage(options);
  95. task.status = "processed";
  96. if (pageData) {
  97. task.filename = pageData.filename;
  98. if (options.crawlLinks && task.depth < options.crawlMaxDepth) {
  99. let newTasks = pageData.links
  100. .map(urlLink => ({ url: rewriteURL(urlLink, options.urlRewriteRules), originalUrl: urlLink, depth: task.depth + 1 }))
  101. .filter(task => task.url && VALID_URL_TEST.test(task.url) && !tasks.find(otherTask => otherTask.url == task.url));
  102. if (options.crawlInnerLinksOnly) {
  103. const urlHost = getHostURL(options.url);
  104. newTasks = newTasks.filter(task => task.url.startsWith(urlHost));
  105. }
  106. tasks.splice(tasks.length, 0, ...newTasks);
  107. }
  108. }
  109. await runTasks(tasks, options);
  110. }
  111. }
  112. function rewriteURL(url, rewriteRules) {
  113. url = url.trim();
  114. rewriteRules.forEach(rewriteRule => {
  115. const parts = rewriteRule.trim().split(/ +/);
  116. if (parts.length == 2) {
  117. url = url.replace(new RegExp(parts[0]), parts[1]).trim();
  118. }
  119. });
  120. return url;
  121. }
  122. function getHostURL(url) {
  123. url = new URL(url);
  124. return url.protocol + "//" + (url.username ? url.username + (url.password || "") + "@" : "") + url.hostname;
  125. }
  126. async function capturePage(options) {
  127. try {
  128. const pageData = await backend.getPageData(options);
  129. if (options.output) {
  130. fs.writeFileSync(getFilename(options.output), pageData.content);
  131. } else {
  132. if (options.filenameTemplate && pageData.filename) {
  133. fs.writeFileSync(getFilename(pageData.filename), pageData.content);
  134. } else {
  135. console.log(pageData.content); // eslint-disable-line no-console
  136. }
  137. }
  138. return pageData;
  139. } catch (error) {
  140. const message = "URL: " + options.url + "\nStack: " + error.stack + "\n";
  141. if (options.errorFile) {
  142. fs.writeFileSync(options.errorFile, message, { flag: "a" });
  143. } else {
  144. console.error(message); // eslint-disable-line no-console
  145. }
  146. }
  147. }
  148. function getFilename(filename, index = 1) {
  149. let newFilename = filename;
  150. if (index > 1) {
  151. const regExpMatchExtension = /(\.[^.]+)$/;
  152. const matchExtension = newFilename.match(regExpMatchExtension);
  153. if (matchExtension && matchExtension[1]) {
  154. newFilename = newFilename.replace(regExpMatchExtension, " - " + index + matchExtension[1]);
  155. } else {
  156. newFilename += " - " + index;
  157. }
  158. }
  159. if (fs.existsSync(newFilename)) {
  160. return getFilename(filename, index + 1);
  161. } else {
  162. return newFilename;
  163. }
  164. }
  165. function escapeRegExp(string) {
  166. return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  167. }