content.js 11 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 browser, document, globalThis, location, URL, Blob, MouseEvent, setTimeout */
  24. import * as download from "./../common/download.js";
  25. import { fetch, frameFetch } from "./../../lib/single-file/fetch/content/content-fetch.js";
  26. import * as ui from "./../../ui/content/content-ui.js";
  27. import { onError, getOpenFileBar, openFile } from "./../../ui/common/common-content-ui.js";
  28. import * as yabson from "./../../lib/yabson/yabson.js";
  29. const singlefile = globalThis.singlefile;
  30. const bootstrap = globalThis.singlefileBootstrap;
  31. const MOZ_EXTENSION_PROTOCOL = "moz-extension:";
  32. let processor, processing, downloadParser, openFileInfobar;
  33. if (!bootstrap || !bootstrap.initializedSingleFile) {
  34. singlefile.init({ fetch, frameFetch });
  35. browser.runtime.onMessage.addListener(message => {
  36. if (message.method == "content.save" || message.method == "content.cancelSave" || message.method == "content.download" || message.method == "content.getSelectedLinks" || message.method == "content.error" || message.method == "content.prompt") {
  37. return onMessage(message);
  38. }
  39. });
  40. if (bootstrap) {
  41. bootstrap.initializedSingleFile = true;
  42. } else {
  43. globalThis.singlefileBootstrap = { initializedSingleFile: true };
  44. }
  45. }
  46. async function onMessage(message) {
  47. if (!location.href.startsWith(MOZ_EXTENSION_PROTOCOL)) {
  48. if (message.method == "content.save") {
  49. await savePage(message);
  50. return {};
  51. }
  52. if (message.method == "content.cancelSave") {
  53. if (processor) {
  54. processor.cancel();
  55. ui.onEndPage();
  56. if (openFileInfobar) {
  57. openFileInfobar.cancel();
  58. openFileInfobar = null;
  59. }
  60. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  61. }
  62. if (message.options.loadDeferredImages) {
  63. singlefile.processors.lazy.resetZoomLevel(message.options);
  64. }
  65. return {};
  66. }
  67. if (message.method == "content.getSelectedLinks") {
  68. return {
  69. urls: ui.getSelectedLinks()
  70. };
  71. }
  72. if (message.method == "content.download") {
  73. if (!downloadParser) {
  74. downloadParser = yabson.getParser();
  75. }
  76. const result = await downloadParser.next(message.data);
  77. if (result.done) {
  78. downloadParser = null;
  79. const link = document.createElement("a");
  80. link.download = result.value.filename;
  81. link.href = URL.createObjectURL(new Blob([result.value.content]), "text/html");
  82. link.dispatchEvent(new MouseEvent("click"));
  83. URL.revokeObjectURL(link.href);
  84. await browser.runtime.sendMessage({ method: "downloads.end", taskId: result.value.taskId });
  85. }
  86. return {};
  87. }
  88. if (message.method == "content.error") {
  89. onError(message.error, message.link);
  90. return {};
  91. }
  92. if (message.method == "content.prompt") {
  93. return ui.prompt(message.message, message.value);
  94. }
  95. }
  96. }
  97. async function savePage(message) {
  98. const options = message.options;
  99. let selectionFound;
  100. if (options.selected || options.optionallySelected) {
  101. selectionFound = await ui.markSelection(options.optionallySelected);
  102. }
  103. if (!processing && (!bootstrap || !bootstrap.pageInfo.processing)) {
  104. options.updatedResources = bootstrap ? bootstrap.pageInfo.updatedResources : {};
  105. options.visitDate = bootstrap ? bootstrap.pageInfo.visitDate : new Date();
  106. Object.keys(options.updatedResources).forEach(url => options.updatedResources[url].retrieved = false);
  107. if (options.optionallySelected && selectionFound) {
  108. options.selected = true;
  109. }
  110. if (!options.selected || selectionFound) {
  111. if (bootstrap) {
  112. bootstrap.pageInfo.processing = true;
  113. }
  114. processing = true;
  115. try {
  116. const pageData = await processPage(options);
  117. if (pageData) {
  118. if (((!options.backgroundSave && !options.saveToClipboard) || options.saveToGDrive || options.saveToGitHub || options.saveWithCompanion || options.saveWithWebDAV || options.saveToDropbox) && options.confirmFilename) {
  119. pageData.filename = ui.prompt("Save as", pageData.filename) || pageData.filename;
  120. }
  121. await download.downloadPage(pageData, options);
  122. }
  123. } catch (error) {
  124. if (!processor.cancelled) {
  125. console.error(error); // eslint-disable-line no-console
  126. const errorMessage = error.toString();
  127. browser.runtime.sendMessage({ method: "ui.processError", error: errorMessage });
  128. onError(errorMessage);
  129. }
  130. }
  131. } else {
  132. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  133. }
  134. processing = false;
  135. if (bootstrap) {
  136. bootstrap.pageInfo.processing = false;
  137. }
  138. }
  139. }
  140. async function processPage(options) {
  141. const frames = singlefile.processors.frameTree;
  142. let framesSessionId;
  143. options.keepFilename = options.saveToGDrive || options.saveToGitHub || options.saveWithWebDAV || options.saveToDropbox;
  144. if (options.delayBeforeProcessing) {
  145. await new Promise(resolve => setTimeout(resolve, options.delayBeforeProcessing * 1000));
  146. }
  147. singlefile.helper.initDoc(document);
  148. ui.onStartPage(options);
  149. processor = new singlefile.SingleFile(options);
  150. const preInitializationPromises = [];
  151. options.insertCanonicalLink = true;
  152. let index = 0, maxIndex = 0;
  153. options.onprogress = event => {
  154. if (!processor.cancelled) {
  155. if (event.type == event.RESOURCES_INITIALIZED) {
  156. maxIndex = event.detail.max;
  157. if (options.loadDeferredImages) {
  158. singlefile.processors.lazy.resetZoomLevel(options);
  159. }
  160. }
  161. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  162. if (event.type == event.RESOURCE_LOADED) {
  163. index++;
  164. }
  165. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex });
  166. ui.onLoadResource(index, maxIndex, options);
  167. } else if (!event.detail.frame) {
  168. if (event.type == event.PAGE_LOADING) {
  169. ui.onPageLoading();
  170. } else if (event.type == event.PAGE_LOADED) {
  171. ui.onLoadPage();
  172. } else if (event.type == event.STAGE_STARTED) {
  173. if (event.detail.step < 3) {
  174. ui.onStartStage(event.detail.step, options);
  175. }
  176. } else if (event.type == event.STAGE_ENDED) {
  177. if (event.detail.step < 3) {
  178. ui.onEndStage(event.detail.step, options);
  179. }
  180. } else if (event.type == event.STAGE_TASK_STARTED) {
  181. ui.onStartStageTask(event.detail.step, event.detail.task);
  182. } else if (event.type == event.STAGE_TASK_ENDED) {
  183. ui.onEndStageTask(event.detail.step, event.detail.task);
  184. }
  185. }
  186. }
  187. };
  188. const cancelProcessor = processor.cancel.bind(processor);
  189. if (options.insertEmbeddedImage && options.compressContent) {
  190. ui.onInsertingEmbeddedImage(options);
  191. openFileInfobar = getOpenFileBar();
  192. const cancelled = await openFileInfobar.display();
  193. if (!cancelled) {
  194. options.embeddedImage = await openFile({ accept: "image/*" });
  195. openFileInfobar.hide();
  196. }
  197. ui.onInsertEmbeddedImage(options);
  198. }
  199. if (!options.saveRawPage && !processor.cancelled) {
  200. let lazyLoadPromise;
  201. if (options.loadDeferredImages) {
  202. lazyLoadPromise = singlefile.processors.lazy.process(options);
  203. ui.onLoadingDeferResources(options);
  204. lazyLoadPromise.then(() => {
  205. if (!processor.cancelled) {
  206. ui.onLoadDeferResources(options);
  207. }
  208. });
  209. if (options.loadDeferredImagesBeforeFrames) {
  210. await lazyLoadPromise;
  211. }
  212. }
  213. if (!options.removeFrames && frames && globalThis.frames) {
  214. let frameTreePromise;
  215. if (options.loadDeferredImages) {
  216. frameTreePromise = new Promise(resolve => globalThis.setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesBeforeFrames || !options.loadDeferredImages ? 0 : options.loadDeferredImagesMaxIdleTime));
  217. } else {
  218. frameTreePromise = frames.getAsync(options);
  219. }
  220. ui.onLoadingFrames(options);
  221. frameTreePromise.then(() => {
  222. if (!processor.cancelled) {
  223. ui.onLoadFrames(options);
  224. }
  225. });
  226. if (options.loadDeferredImagesBeforeFrames) {
  227. options.frames = await new Promise(resolve => {
  228. processor.cancel = function () {
  229. cancelProcessor();
  230. resolve([]);
  231. };
  232. frameTreePromise.then(resolve);
  233. });
  234. } else {
  235. preInitializationPromises.push(frameTreePromise);
  236. }
  237. }
  238. if (options.loadDeferredImages && !options.loadDeferredImagesBeforeFrames) {
  239. preInitializationPromises.push(lazyLoadPromise);
  240. }
  241. }
  242. if (!options.loadDeferredImagesBeforeFrames && !processor.cancelled) {
  243. [options.frames] = await new Promise(resolve => {
  244. const preInitializationAllPromises = Promise.all(preInitializationPromises);
  245. processor.cancel = function () {
  246. cancelProcessor();
  247. resolve([[]]);
  248. };
  249. preInitializationAllPromises.then(() => resolve(preInitializationAllPromises));
  250. });
  251. }
  252. framesSessionId = options.frames && options.frames.sessionId;
  253. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  254. options.win = globalThis;
  255. if (selectedFrame) {
  256. options.content = selectedFrame.content;
  257. options.url = selectedFrame.baseURI;
  258. options.canvases = selectedFrame.canvases;
  259. options.fonts = selectedFrame.fonts;
  260. options.stylesheets = selectedFrame.stylesheets;
  261. options.images = selectedFrame.images;
  262. options.posters = selectedFrame.posters;
  263. options.videos = selectedFrame.videos;
  264. options.usedFonts = selectedFrame.usedFonts;
  265. options.shadowRoots = selectedFrame.shadowRoots;
  266. options.adoptedStyleSheets = selectedFrame.adoptedStyleSheets;
  267. } else {
  268. options.doc = document;
  269. }
  270. if (!processor.cancelled) {
  271. await processor.run();
  272. }
  273. if (framesSessionId) {
  274. frames.cleanup(framesSessionId);
  275. }
  276. let page;
  277. if (!processor.cancelled) {
  278. if (options.confirmInfobarContent) {
  279. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  280. }
  281. page = await processor.getPageData();
  282. if (options.selected || options.optionallySelected) {
  283. ui.unmarkSelection();
  284. }
  285. ui.onEndPage();
  286. if (options.displayStats) {
  287. console.log("SingleFile stats"); // eslint-disable-line no-console
  288. console.table(page.stats); // eslint-disable-line no-console
  289. }
  290. }
  291. return page;
  292. }