content-main.js 8.1 KB

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