content-main.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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.saveToGDrive) && options.confirmFilename) {
  75. pageData.filename = ui.prompt("Save as", pageData.filename) || 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. } else if (!event.detail.frame) {
  138. if (event.type == event.PAGE_LOADING) {
  139. ui.onPageLoading();
  140. } else if (event.type == event.PAGE_LOADED) {
  141. ui.onLoadPage();
  142. } else if (event.type == event.STAGE_STARTED) {
  143. if (event.detail.step < 3) {
  144. ui.onStartStage(event.detail.step, options);
  145. }
  146. } else if (event.type == event.STAGE_ENDED) {
  147. if (event.detail.step < 3) {
  148. ui.onEndStage(event.detail.step, options);
  149. }
  150. } else if (event.type == event.STAGE_TASK_STARTED) {
  151. ui.onStartStageTask(event.detail.step, event.detail.task);
  152. } else if (event.type == event.STAGE_TASK_ENDED) {
  153. ui.onEndStageTask(event.detail.step, event.detail.task);
  154. }
  155. }
  156. }
  157. };
  158. [options.frames] = await new Promise(async resolve => {
  159. const preInitializationAllPromises = Promise.all(preInitializationPromises);
  160. const cancelProcessor = processor.cancel.bind(processor);
  161. processor.cancel = function () {
  162. cancelProcessor();
  163. resolve([[]]);
  164. };
  165. await preInitializationAllPromises;
  166. resolve(preInitializationAllPromises);
  167. });
  168. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  169. options.win = window;
  170. if (selectedFrame) {
  171. options.content = selectedFrame.content;
  172. options.url = selectedFrame.baseURI;
  173. options.canvases = selectedFrame.canvases;
  174. options.fonts = selectedFrame.fonts;
  175. options.stylesheets = selectedFrame.stylesheets;
  176. options.images = selectedFrame.images;
  177. options.posters = selectedFrame.posters;
  178. options.usedFonts = selectedFrame.usedFonts;
  179. options.shadowRoots = selectedFrame.shadowRoots;
  180. options.imports = selectedFrame.imports;
  181. } else {
  182. options.doc = document;
  183. }
  184. if (!processor.cancelled) {
  185. await processor.run();
  186. }
  187. if (!options.saveRawPage && !options.removeFrames && frames) {
  188. frames.cleanup(options);
  189. }
  190. let page;
  191. if (!processor.cancelled) {
  192. if (options.confirmInfobarContent) {
  193. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  194. }
  195. page = await processor.getPageData();
  196. if (options.selected || options.optionallySelected) {
  197. ui.unmarkSelection();
  198. }
  199. ui.onEndPage();
  200. if (options.displayStats) {
  201. console.log("SingleFile stats"); // eslint-disable-line no-console
  202. console.table(page.stats); // eslint-disable-line no-console
  203. }
  204. }
  205. return page;
  206. }
  207. })();