content-main.js 7.9 KB

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