single-file-cli-api.js 10.0 KB

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