content-main.js 7.4 KB

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