single-file 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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 fileUrl = require("file-url");
  26. const fs = require("fs");
  27. const options = require("./args");
  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. options.compressCSS = options.compressCss;
  36. options.compressHTML = options.compressHtml;
  37. options.includeBOM = options.includeBom;
  38. if (options.url && !/^(https?|file):\/\//.test(options.url)) {
  39. options.url = fileUrl(options.url);
  40. }
  41. options.retrieveLinks = true;
  42. options.browserScripts = options.browserScripts.map(path => require.resolve(path));
  43. const backend = require(backEnds[options.backEnd]);
  44. run(options);
  45. async function run(options) {
  46. await backend.initialize(options);
  47. let tasks;
  48. if (options.urlsFile) {
  49. tasks = fs.readFileSync(options.urlsFile).toString().split("\n")
  50. .map(url => ({ url: rewriteURL(url, options.urlRewriteRules), depth: 0 }))
  51. .filter(task => task.url);
  52. } else {
  53. tasks = [{ url: rewriteURL(options.url, options.urlRewriteRules), depth: 0 }];
  54. }
  55. await runTasks(tasks, options);
  56. if (!options.browserDebug) {
  57. return backend.closeBrowser();
  58. }
  59. }
  60. async function runTasks(tasks, options) {
  61. const availableTasks = tasks.filter(task => !task.status).length;
  62. const processingTasks = tasks.filter(task => task.status == "processing").length;
  63. const promisesTasks = [];
  64. for (let workerIndex = 0; workerIndex < Math.min(availableTasks, options.maxParallelWorkers - processingTasks); workerIndex++) {
  65. promisesTasks.push(runNextTask(tasks, options));
  66. }
  67. await Promise.all(promisesTasks);
  68. }
  69. async function runNextTask(tasks, options) {
  70. const task = tasks.find(task => !task.status);
  71. if (task) {
  72. options = JSON.parse(JSON.stringify(options));
  73. options.url = task.url;
  74. options.output = null;
  75. task.status = "processing";
  76. const pageData = await capturePage(options);
  77. task.status = "processed";
  78. if (pageData && options.crawlLinks) {
  79. pageData.links = pageData.links
  80. .map(urlLink => rewriteURL(urlLink, options.urlRewriteRules))
  81. .filter(urlLink => !tasks.find(task => task.url == urlLink));
  82. if (options.crawlInnerLinksOnly) {
  83. const urlHost = getHostURL(options.url);
  84. pageData.links = pageData.links.filter(urlLink => urlLink.startsWith(urlHost));
  85. }
  86. if (task.depth < options.crawlMaxDepth) {
  87. tasks.splice(tasks.length, 0, ...pageData.links.map(url => ({ url, depth: task.depth + 1 })));
  88. }
  89. }
  90. await runTasks(tasks, options);
  91. }
  92. }
  93. function rewriteURL(url, rewriteRules) {
  94. url = url.trim();
  95. rewriteRules.forEach(rewriteRule => {
  96. const parts = rewriteRule.split(/ +/);
  97. if (parts.length == 2) {
  98. url = url.replace(new RegExp(parts[0]), parts[1]).trim();
  99. }
  100. });
  101. return url;
  102. }
  103. function getHostURL(url) {
  104. url = new URL(url);
  105. return url.protocol + "//" + (url.username ? url.username + (url.password || "") + "@" : "") + url.hostname;
  106. }
  107. async function capturePage(options) {
  108. try {
  109. const pageData = await backend.getPageData(options);
  110. if (options.output) {
  111. fs.writeFileSync(getFilename(options.output), pageData.content);
  112. } else {
  113. if (options.filenameTemplate && pageData.filename) {
  114. fs.writeFileSync(getFilename(pageData.filename), pageData.content);
  115. } else {
  116. console.log(pageData.content); // eslint-disable-line no-console
  117. }
  118. }
  119. return pageData;
  120. } catch (error) {
  121. const message = "URL: " + options.url + "\nStack: " + error.stack + "\n";
  122. if (options.errorFile) {
  123. fs.writeFileSync(options.errorFile, message, { flag: "a" });
  124. } else {
  125. console.error(message); // eslint-disable-line no-console
  126. }
  127. }
  128. }
  129. function getFilename(filename, index = 1) {
  130. let newFilename = filename;
  131. if (index > 1) {
  132. const regExpMatchExtension = /(\.[^.]+)$/;
  133. const matchExtension = newFilename.match(regExpMatchExtension);
  134. if (matchExtension && matchExtension[1]) {
  135. newFilename = newFilename.replace(regExpMatchExtension, " - " + index + matchExtension[1]);
  136. } else {
  137. newFilename += " - " + index;
  138. }
  139. }
  140. if (fs.existsSync(newFilename)) {
  141. return getFilename(filename, index + 1);
  142. } else {
  143. return newFilename;
  144. }
  145. }