single-file-cli-api.js 10 KB

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