single-file 5.0 KB

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