1
0

single-file-cli-api.js 10.0 KB

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