1
0

single-file-cli-api.js 9.9 KB

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