content-main.js 8.0 KB

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