content-main.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /*
  2. * Copyright 2010-2019 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, window, location, setTimeout */
  24. this.singlefile.extension.core.content.main = this.singlefile.extension.core.content.main || (() => {
  25. const singlefile = this.singlefile;
  26. const MOZ_EXTENSION_PROTOCOL = "moz-extension:";
  27. let ui, processing = false, processor;
  28. singlefile.lib.main.init({
  29. fetch: singlefile.extension.lib.fetch.content.resources.fetch,
  30. frameFetch: singlefile.extension.lib.fetch.content.resources.frameFetch
  31. });
  32. browser.runtime.onMessage.addListener(message => {
  33. if (message.method == "content.save" || message.method == "content.cancelSave") {
  34. return onMessage(message);
  35. }
  36. });
  37. return {};
  38. async function onMessage(message) {
  39. if (!ui) {
  40. ui = singlefile.extension.ui.content.main;
  41. }
  42. if (!location.href.startsWith(MOZ_EXTENSION_PROTOCOL)) {
  43. if (message.method == "content.save") {
  44. await savePage(message);
  45. return {};
  46. }
  47. if (message.method == "content.cancelSave") {
  48. if (processor) {
  49. processor.cancel();
  50. ui.onEndPage();
  51. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  52. }
  53. return {};
  54. }
  55. }
  56. }
  57. async function savePage(message) {
  58. const options = message.options;
  59. if (!processing) {
  60. options.updatedResources = singlefile.extension.core.content.updatedResources || {};
  61. Object.keys(options.updatedResources).forEach(url => options.updatedResources[url].retrieved = false);
  62. let selectionFound;
  63. if (options.selected || options.optionallySelected) {
  64. selectionFound = await ui.markSelection(options.optionallySelected);
  65. }
  66. if (options.optionallySelected && selectionFound) {
  67. options.selected = true;
  68. }
  69. if (!options.selected || selectionFound) {
  70. processing = true;
  71. try {
  72. const pageData = await processPage(options);
  73. if (pageData) {
  74. if (!options.backgroundSave && !options.saveToClipboard && options.confirmFilename) {
  75. pageData.filename = ui.prompt("File name", pageData.filename);
  76. }
  77. await singlefile.extension.core.content.download.downloadPage(pageData, options);
  78. }
  79. } catch (error) {
  80. if (!processor.cancelled) {
  81. console.error(error); // eslint-disable-line no-console
  82. browser.runtime.sendMessage({ method: "ui.processError", error });
  83. }
  84. }
  85. } else {
  86. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  87. }
  88. processing = false;
  89. }
  90. }
  91. async function processPage(options) {
  92. const frames = singlefile.lib.processors.frameTree.content.frames;
  93. singlefile.lib.helper.initDoc(document);
  94. ui.onStartPage(options);
  95. processor = new singlefile.lib.SingleFile(options);
  96. const preInitializationPromises = [];
  97. options.insertSingleFileComment = true;
  98. if (!options.saveRawPage) {
  99. if (!options.removeFrames && frames && window.frames && window.frames.length) {
  100. let frameTreePromise;
  101. if (options.loadDeferredImages) {
  102. frameTreePromise = new Promise(resolve => setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frames.TIMEOUT_INIT_REQUEST_MESSAGE));
  103. } else {
  104. frameTreePromise = frames.getAsync(options);
  105. }
  106. ui.onLoadingFrames(options);
  107. frameTreePromise.then(() => {
  108. if (!processor.cancelled) {
  109. ui.onLoadFrames(options);
  110. }
  111. });
  112. preInitializationPromises.push(frameTreePromise);
  113. }
  114. if (options.loadDeferredImages) {
  115. const lazyLoadPromise = singlefile.lib.processors.lazy.content.loader.process(options);
  116. ui.onLoadingDeferResources(options);
  117. lazyLoadPromise.then(() => {
  118. if (!processor.cancelled) {
  119. ui.onLoadDeferResources(options);
  120. }
  121. });
  122. preInitializationPromises.push(lazyLoadPromise);
  123. }
  124. }
  125. let index = 0, maxIndex = 0;
  126. options.onprogress = event => {
  127. if (!processor.cancelled) {
  128. if (event.type == event.RESOURCES_INITIALIZED) {
  129. maxIndex = event.detail.max;
  130. }
  131. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  132. if (event.type == event.RESOURCE_LOADED) {
  133. index++;
  134. }
  135. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex });
  136. ui.onLoadResource(index, maxIndex, options);
  137. } if (event.type == event.PAGE_ENDED) {
  138. browser.runtime.sendMessage({ method: "ui.processEnd" });
  139. } else if (!event.detail.frame) {
  140. if (event.type == event.PAGE_LOADING) {
  141. ui.onPageLoading();
  142. } else if (event.type == event.PAGE_LOADED) {
  143. ui.onLoadPage();
  144. } else if (event.type == event.STAGE_STARTED) {
  145. if (event.detail.step < 3) {
  146. ui.onStartStage(event.detail.step, options);
  147. }
  148. } else if (event.type == event.STAGE_ENDED) {
  149. if (event.detail.step < 3) {
  150. ui.onEndStage(event.detail.step, options);
  151. }
  152. } else if (event.type == event.STAGE_TASK_STARTED) {
  153. ui.onStartStageTask(event.detail.step, event.detail.task);
  154. } else if (event.type == event.STAGE_TASK_ENDED) {
  155. ui.onEndStageTask(event.detail.step, event.detail.task);
  156. }
  157. }
  158. }
  159. };
  160. [options.frames] = await new Promise(async resolve => {
  161. const preInitializationAllPromises = Promise.all(preInitializationPromises);
  162. const cancelProcessor = processor.cancel.bind(processor);
  163. processor.cancel = function () {
  164. cancelProcessor();
  165. resolve([[]]);
  166. };
  167. await preInitializationAllPromises;
  168. resolve(preInitializationAllPromises);
  169. });
  170. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  171. options.win = window;
  172. if (selectedFrame) {
  173. options.content = selectedFrame.content;
  174. options.url = selectedFrame.baseURI;
  175. options.canvases = selectedFrame.canvases;
  176. options.fonts = selectedFrame.fonts;
  177. options.stylesheets = selectedFrame.stylesheets;
  178. options.images = selectedFrame.images;
  179. options.posters = selectedFrame.posters;
  180. options.usedFonts = selectedFrame.usedFonts;
  181. options.shadowRoots = selectedFrame.shadowRoots;
  182. options.imports = selectedFrame.imports;
  183. } else {
  184. options.doc = document;
  185. }
  186. if (!processor.cancelled) {
  187. await processor.run();
  188. }
  189. if (!options.saveRawPage && !options.removeFrames && frames) {
  190. frames.cleanup(options);
  191. }
  192. let page;
  193. if (!processor.cancelled) {
  194. if (options.confirmInfobarContent) {
  195. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  196. }
  197. page = await processor.getPageData();
  198. if (options.selected || options.optionallySelected) {
  199. ui.unmarkSelection();
  200. }
  201. ui.onEndPage();
  202. if (options.displayStats) {
  203. console.log("SingleFile stats"); // eslint-disable-line no-console
  204. console.table(page.stats); // eslint-disable-line no-console
  205. }
  206. }
  207. return page;
  208. }
  209. })();