content-main.js 7.7 KB

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