single-file-cli-api.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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, exports, URL */
  24. const fs = require("fs");
  25. const path = require("path");
  26. const scripts = require("./back-ends/common/scripts.js");
  27. const VALID_URL_TEST = /^(https?|file):\/\//;
  28. const DEFAULT_OPTIONS = {
  29. removeHiddenElements: true,
  30. removeUnusedStyles: true,
  31. removeUnusedFonts: true,
  32. removeFrames: false,
  33. removeImports: true,
  34. compressHTML: true,
  35. compressCSS: false,
  36. loadDeferredImages: true,
  37. loadDeferredImagesMaxIdleTime: 1500,
  38. loadDeferredImagesBlockCookies: false,
  39. loadDeferredImagesBlockStorage: false,
  40. loadDeferredImagesKeepZoomLevel: false,
  41. loadDeferredImagesDispatchScrollEvent: false,
  42. filenameTemplate: "{page-title} ({date-locale} {time-locale}).html",
  43. infobarTemplate: "",
  44. includeInfobar: false,
  45. filenameMaxLength: 192,
  46. filenameMaxLengthUnit: "bytes",
  47. filenameReplacedCharacters: ["~", "+", "\\\\", "?", "%", "*", ":", "|", "\"", "<", ">", "\x00-\x1f", "\x7F"],
  48. filenameReplacementCharacter: "_",
  49. maxResourceSizeEnabled: false,
  50. maxResourceSize: 10,
  51. backgroundSave: true,
  52. removeAlternativeFonts: true,
  53. removeAlternativeMedias: true,
  54. removeAlternativeImages: true,
  55. groupDuplicateImages: true,
  56. saveRawPage: false,
  57. resolveFragmentIdentifierURLs: false,
  58. userScriptEnabled: false,
  59. saveFavicon: true,
  60. includeBOM: false,
  61. insertMetaCSP: true,
  62. insertMetaNoIndex: false,
  63. insertSingleFileComment: true,
  64. blockImages: false,
  65. blockStylesheets: false,
  66. blockFont: false,
  67. blockScripts: true,
  68. blockVideos: true,
  69. blockAudios: true
  70. };
  71. const STATE_PROCESSING = "processing";
  72. const STATE_PROCESSED = "processed";
  73. const backEnds = {
  74. jsdom: "./back-ends/jsdom.js",
  75. puppeteer: "./back-ends/puppeteer.js",
  76. "puppeteer-firefox": "./back-ends/puppeteer-firefox.js",
  77. "webdriver-chromium": "./back-ends/webdriver-chromium.js",
  78. "webdriver-gecko": "./back-ends/webdriver-gecko.js",
  79. "playwright-firefox": "./back-ends/playwright-firefox.js",
  80. "playwright-chromium": "./back-ends/playwright-chromium.js"
  81. };
  82. let backend, tasks = [], maxParallelWorkers = 8, sessionFilename;
  83. exports.getBackEnd = backEndName => require(backEnds[backEndName]);
  84. exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
  85. exports.VALID_URL_TEST = VALID_URL_TEST;
  86. exports.initialize = initialize;
  87. async function initialize(options) {
  88. options = Object.assign({}, DEFAULT_OPTIONS, options);
  89. maxParallelWorkers = options.maxParallelWorkers;
  90. backend = require(backEnds[options.backEnd]);
  91. await backend.initialize(options);
  92. if (options.crawlSyncSession || options.crawlLoadSession) {
  93. try {
  94. tasks = JSON.parse(fs.readFileSync(options.crawlSyncSession || options.crawlLoadSession).toString());
  95. } catch (error) {
  96. if (options.crawlLoadSession) {
  97. throw error;
  98. }
  99. }
  100. }
  101. if (options.crawlSyncSession || options.crawlSaveSession) {
  102. sessionFilename = options.crawlSyncSession || options.crawlSaveSession;
  103. }
  104. return {
  105. capture: urls => capture(urls, options),
  106. finish: () => finish(options),
  107. };
  108. }
  109. async function capture(urls, options) {
  110. let newTasks;
  111. const taskUrls = tasks.map(task => task.url);
  112. newTasks = urls.map(url => createTask(url, options));
  113. newTasks = newTasks.filter(task => task && !taskUrls.includes(task.url));
  114. if (newTasks.length) {
  115. tasks = tasks.concat(newTasks);
  116. saveTasks();
  117. }
  118. await runTasks();
  119. }
  120. async function finish(options) {
  121. const promiseTasks = tasks.map(task => task.promise);
  122. await Promise.all(promiseTasks);
  123. if (options.crawlReplaceURLs) {
  124. tasks.forEach(task => {
  125. try {
  126. let pageContent = fs.readFileSync(task.filename).toString();
  127. tasks.forEach(otherTask => {
  128. if (otherTask.filename) {
  129. pageContent = pageContent.replace(new RegExp(escapeRegExp("\"" + otherTask.originalUrl + "\""), "gi"), "\"" + otherTask.filename + "\"");
  130. pageContent = pageContent.replace(new RegExp(escapeRegExp("'" + otherTask.originalUrl + "'"), "gi"), "'" + otherTask.filename + "'");
  131. const filename = otherTask.filename.replace(/ /g, "%20");
  132. pageContent = pageContent.replace(new RegExp(escapeRegExp("=" + otherTask.originalUrl + " "), "gi"), "=" + filename + " ");
  133. pageContent = pageContent.replace(new RegExp(escapeRegExp("=" + otherTask.originalUrl + ">"), "gi"), "=" + filename + ">");
  134. }
  135. });
  136. fs.writeFileSync(task.filename, pageContent);
  137. } catch (error) {
  138. // ignored
  139. }
  140. });
  141. }
  142. if (!options.browserDebug) {
  143. return backend.closeBrowser();
  144. }
  145. }
  146. async function runTasks() {
  147. const availableTasks = tasks.filter(task => !task.status).length;
  148. const processingTasks = tasks.filter(task => task.status == STATE_PROCESSING).length;
  149. const promisesTasks = [];
  150. for (let workerIndex = 0; workerIndex < Math.min(availableTasks, maxParallelWorkers - processingTasks); workerIndex++) {
  151. promisesTasks.push(runNextTask());
  152. }
  153. return Promise.all(promisesTasks);
  154. }
  155. async function runNextTask() {
  156. const task = tasks.find(task => !task.status);
  157. if (task) {
  158. const options = task.options;
  159. let taskOptions = JSON.parse(JSON.stringify(options));
  160. taskOptions.url = task.url;
  161. task.status = STATE_PROCESSING;
  162. saveTasks();
  163. task.promise = capturePage(taskOptions);
  164. const pageData = await task.promise;
  165. task.status = STATE_PROCESSED;
  166. if (pageData) {
  167. task.filename = pageData.filename;
  168. if (options.crawlLinks && testMaxDepth(task)) {
  169. let newTasks = pageData.links
  170. .map(urlLink => createTask(urlLink, options, task, tasks[0]))
  171. .filter(task => task &&
  172. testMaxDepth(task) &&
  173. !tasks.find(otherTask => otherTask.url == task.url) &&
  174. (!options.crawlInnerLinksOnly || task.isInnerLink) &&
  175. (!options.crawlNoParent || (task.isChild || !task.isInnerLink)));
  176. tasks.splice(tasks.length, 0, ...newTasks);
  177. }
  178. }
  179. saveTasks();
  180. await runTasks();
  181. }
  182. }
  183. function testMaxDepth(task) {
  184. const options = task.options;
  185. return (options.crawlMaxDepth == 0 || task.depth <= options.crawlMaxDepth) &&
  186. (options.crawlExternalLinksMaxDepth == 0 || task.externalLinkDepth < options.crawlExternalLinksMaxDepth);
  187. }
  188. function createTask(url, options, parentTask, rootTask) {
  189. url = parentTask ? rewriteURL(url, options.crawlRemoveURLFragment, options.crawlRewriteRules) : url;
  190. if (VALID_URL_TEST.test(url)) {
  191. const isInnerLink = rootTask && url.startsWith(getHostURL(rootTask.url));
  192. const rootBaseURIMatch = rootTask && rootTask.url.match(/(.*?)[^/]*$/);
  193. const isChild = isInnerLink && rootBaseURIMatch && rootBaseURIMatch[1] && url.startsWith(rootBaseURIMatch[1]);
  194. return {
  195. url,
  196. isInnerLink,
  197. isChild,
  198. originalUrl: url,
  199. rootBaseURI: rootBaseURIMatch && rootBaseURIMatch[1],
  200. depth: parentTask ? parentTask.depth + 1 : 0,
  201. externalLinkDepth: isInnerLink ? -1 : parentTask ? parentTask.externalLinkDepth + 1 : -1,
  202. options
  203. };
  204. }
  205. }
  206. function saveTasks() {
  207. if (sessionFilename) {
  208. fs.writeFileSync(sessionFilename, JSON.stringify(
  209. tasks.map(task => Object.assign({}, task, {
  210. status: task.status == STATE_PROCESSING ? undefined : task.status,
  211. promise: undefined,
  212. options: task.status && task.status == STATE_PROCESSED ? undefined : task.options
  213. }))
  214. ));
  215. }
  216. }
  217. function rewriteURL(url, crawlRemoveURLFragment, crawlRewriteRules) {
  218. url = url.trim();
  219. if (crawlRemoveURLFragment) {
  220. url = url.replace(/^(.*?)#.*$/, "$1");
  221. }
  222. crawlRewriteRules.forEach(rewriteRule => {
  223. const parts = rewriteRule.trim().split(/ +/);
  224. if (parts.length) {
  225. url = url.replace(new RegExp(parts[0]), parts[1] || "").trim();
  226. }
  227. });
  228. return url;
  229. }
  230. function getHostURL(url) {
  231. url = new URL(url);
  232. return url.protocol + "//" + (url.username ? url.username + (url.password || "") + "@" : "") + url.hostname;
  233. }
  234. async function capturePage(options) {
  235. try {
  236. let filename;
  237. const pageData = await backend.getPageData(options);
  238. if (options.includeInfobar) {
  239. await includeInfobarScript(pageData);
  240. }
  241. if (options.output) {
  242. filename = getFilename(options.output, options);
  243. } else if (options.dumpContent) {
  244. console.log(pageData.content); // eslint-disable-line no-console
  245. } else {
  246. filename = getFilename(pageData.filename, options);
  247. }
  248. if (filename) {
  249. const dirname = path.dirname(filename);
  250. if (dirname) {
  251. fs.mkdirSync(dirname, { recursive: true });
  252. }
  253. fs.writeFileSync(filename, pageData.content);
  254. }
  255. return pageData;
  256. } catch (error) {
  257. const message = "URL: " + options.url + "\nStack: " + error.stack + "\n";
  258. if (options.errorFile) {
  259. fs.writeFileSync(options.errorFile, message, { flag: "a" });
  260. } else {
  261. console.error(error.message || error, message); // eslint-disable-line no-console
  262. }
  263. }
  264. }
  265. function getFilename(filename, options, index = 1) {
  266. if (Array.isArray(options.outputDirectory)) {
  267. const outputDirectory = options.outputDirectory.pop();
  268. if (outputDirectory.startsWith("/")) {
  269. options.outputDirectory = outputDirectory;
  270. } else {
  271. options.outputDirectory = options.outputDirectory[0] + outputDirectory;
  272. }
  273. }
  274. let outputDirectory = options.outputDirectory || "";
  275. if (outputDirectory && !outputDirectory.endsWith("/")) {
  276. outputDirectory += "/";
  277. }
  278. let newFilename = outputDirectory + filename;
  279. if (options.filenameConflictAction == "overwrite") {
  280. return filename;
  281. } else if (options.filenameConflictAction == "uniquify" && index > 1) {
  282. const regExpMatchExtension = /(\.[^.]+)$/;
  283. const matchExtension = newFilename.match(regExpMatchExtension);
  284. if (matchExtension && matchExtension[1]) {
  285. newFilename = newFilename.replace(regExpMatchExtension, " (" + index + ")" + matchExtension[1]);
  286. } else {
  287. newFilename += " (" + index + ")";
  288. }
  289. }
  290. if (fs.existsSync(newFilename)) {
  291. if (options.filenameConflictAction != "skip") {
  292. return getFilename(filename, options, index + 1);
  293. }
  294. } else {
  295. return newFilename;
  296. }
  297. }
  298. function escapeRegExp(string) {
  299. return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  300. }
  301. async function includeInfobarScript(pageData) {
  302. let infobarContent = await scripts.getInfobarScript();
  303. let lastInfobarContent;
  304. while (lastInfobarContent != infobarContent) {
  305. lastInfobarContent = infobarContent;
  306. infobarContent = infobarContent.replace(/\/\*(.|\n)*?\*\//, "");
  307. }
  308. infobarContent = infobarContent.replace(/\t+/g, " ").replace(/\nthis\.[^(]*/gi, "\n").replace(/\n+/g, "");
  309. pageData.content += "<script>document.currentScript.remove();" + infobarContent + "</script>";
  310. }