single-file-cli-api.js 10 KB

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