1
0

content-main.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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, setTimeout, URL, Blob, MouseEvent */
  24. this.singlefile.extension.core.content.main = this.singlefile.extension.core.content.main || (() => {
  25. const singlefile = this.singlefile;
  26. const MAX_CONTENT_SIZE = 32 * (1024 * 1024);
  27. const SingleFile = singlefile.lib.SingleFile.getClass();
  28. let ui, processing = false, processor;
  29. browser.runtime.onMessage.addListener(async message => {
  30. if (!ui) {
  31. ui = singlefile.extension.ui.content.main;
  32. }
  33. if (message.method == "content.save") {
  34. await savePage(message);
  35. return {};
  36. }
  37. if (message.method == "content.cancelSave") {
  38. if (processor) {
  39. processor.cancel();
  40. ui.onEndPage();
  41. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  42. }
  43. return {};
  44. }
  45. });
  46. return {};
  47. async function savePage(message) {
  48. const options = message.options;
  49. if (!processing) {
  50. let selectionFound;
  51. if (options.selected) {
  52. selectionFound = await ui.markSelection();
  53. }
  54. if (!options.selected || selectionFound) {
  55. processing = true;
  56. try {
  57. const page = await processPage(options);
  58. if (page) {
  59. await downloadPage(page, options);
  60. }
  61. } catch (error) {
  62. if (!processor.cancelled) {
  63. console.error(error); // eslint-disable-line no-console
  64. browser.runtime.sendMessage({ method: "ui.processError", error });
  65. }
  66. }
  67. } else {
  68. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  69. }
  70. processing = false;
  71. }
  72. }
  73. async function processPage(options) {
  74. const frames = singlefile.lib.frameTree.content.frames;
  75. singlefile.lib.helper.initDoc(document);
  76. ui.onStartPage(options);
  77. processor = new SingleFile(options);
  78. const preInitializationPromises = [];
  79. options.insertSingleFileComment = true;
  80. if (!options.saveRawPage) {
  81. if (!options.removeFrames && frames && window.frames && window.frames.length) {
  82. let frameTreePromise;
  83. if (options.loadDeferredImages) {
  84. frameTreePromise = new Promise(resolve => setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frames.TIMEOUT_INIT_REQUEST_MESSAGE));
  85. } else {
  86. frameTreePromise = frames.getAsync(options);
  87. }
  88. ui.onLoadingFrames(options);
  89. frameTreePromise.then(() => {
  90. if (!processor.cancelled) {
  91. ui.onLoadFrames(options);
  92. }
  93. });
  94. preInitializationPromises.push(frameTreePromise);
  95. }
  96. if (options.loadDeferredImages) {
  97. const lazyLoadPromise = singlefile.lib.lazy.content.loader.process(options);
  98. ui.onLoadingDeferResources(options);
  99. lazyLoadPromise.then(() => {
  100. if (!processor.cancelled) {
  101. ui.onLoadDeferResources(options);
  102. }
  103. });
  104. preInitializationPromises.push(lazyLoadPromise);
  105. }
  106. }
  107. let index = 0, maxIndex = 0;
  108. options.onprogress = event => {
  109. if (!processor.cancelled) {
  110. if (event.type == event.RESOURCES_INITIALIZED) {
  111. maxIndex = event.detail.max;
  112. }
  113. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  114. if (event.type == event.RESOURCE_LOADED) {
  115. index++;
  116. }
  117. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex });
  118. ui.onLoadResource(index, maxIndex, options);
  119. } if (event.type == event.PAGE_ENDED) {
  120. browser.runtime.sendMessage({ method: "ui.processEnd" });
  121. } else if (!event.detail.frame) {
  122. if (event.type == event.PAGE_LOADING) {
  123. ui.onPageLoading();
  124. } else if (event.type == event.PAGE_LOADED) {
  125. ui.onLoadPage();
  126. } else if (event.type == event.STAGE_STARTED) {
  127. if (event.detail.step < 3) {
  128. ui.onStartStage(event.detail.step, options);
  129. }
  130. } else if (event.type == event.STAGE_ENDED) {
  131. if (event.detail.step < 3) {
  132. ui.onEndStage(event.detail.step, options);
  133. }
  134. } else if (event.type == event.STAGE_TASK_STARTED) {
  135. ui.onStartStageTask(event.detail.step, event.detail.task);
  136. } else if (event.type == event.STAGE_TASK_ENDED) {
  137. ui.onEndStageTask(event.detail.step, event.detail.task);
  138. }
  139. }
  140. }
  141. };
  142. [options.frames] = await new Promise(async resolve => {
  143. const preInitializationAllPromises = Promise.all(preInitializationPromises);
  144. const cancelProcessor = processor.cancel.bind(processor);
  145. processor.cancel = function () {
  146. cancelProcessor();
  147. resolve([[]]);
  148. };
  149. await preInitializationAllPromises;
  150. resolve(preInitializationAllPromises);
  151. });
  152. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  153. options.win = window;
  154. if (selectedFrame) {
  155. options.content = selectedFrame.content;
  156. options.url = selectedFrame.baseURI;
  157. options.canvases = selectedFrame.canvases;
  158. options.fonts = selectedFrame.fonts;
  159. options.stylesheets = selectedFrame.stylesheets;
  160. options.images = selectedFrame.images;
  161. options.posters = selectedFrame.posters;
  162. options.usedFonts = selectedFrame.usedFonts;
  163. options.shadowRoots = selectedFrame.shadowRoots;
  164. options.imports = selectedFrame.imports;
  165. } else {
  166. options.doc = document;
  167. }
  168. if (!processor.cancelled) {
  169. await processor.run();
  170. }
  171. if (!options.saveRawPage && !options.removeFrames && frames) {
  172. frames.cleanup(options);
  173. }
  174. let page;
  175. if (!processor.cancelled) {
  176. if (options.confirmInfobarContent) {
  177. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  178. }
  179. page = await processor.getPageData();
  180. if (options.selected) {
  181. ui.unmarkSelection();
  182. }
  183. ui.onEndPage();
  184. if (options.displayStats) {
  185. console.log("SingleFile stats"); // eslint-disable-line no-console
  186. console.table(page.stats); // eslint-disable-line no-console
  187. }
  188. }
  189. return page;
  190. }
  191. async function downloadPage(page, options) {
  192. if (options.includeInfobar) {
  193. await singlefile.extension.core.common.infobar.includeScript(page);
  194. }
  195. if (options.backgroundSave) {
  196. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < page.content.length; blockIndex++) {
  197. const message = {
  198. method: "downloads.download",
  199. confirmFilename: options.confirmFilename,
  200. filenameConflictAction: options.filenameConflictAction,
  201. filename: page.filename,
  202. saveToClipboard: options.saveToClipboard,
  203. filenameReplacementCharacter: options.filenameReplacementCharacter
  204. };
  205. message.truncated = page.content.length > MAX_CONTENT_SIZE;
  206. if (message.truncated) {
  207. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > page.content.length;
  208. message.content = page.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  209. } else {
  210. message.content = page.content;
  211. }
  212. await browser.runtime.sendMessage(message);
  213. }
  214. } else {
  215. if (options.saveToClipboard) {
  216. saveToClipboard(page);
  217. } else {
  218. downloadPageForeground(page, options);
  219. }
  220. }
  221. }
  222. function downloadPageForeground(page, options) {
  223. if (options.confirmFilename) {
  224. page.filename = ui.prompt("File name", page.filename);
  225. }
  226. if (page.filename && page.filename.length) {
  227. const link = document.createElement("a");
  228. link.download = page.filename;
  229. link.href = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  230. link.dispatchEvent(new MouseEvent("click"));
  231. URL.revokeObjectURL(link.href);
  232. }
  233. }
  234. function saveToClipboard(page) {
  235. const command = "copy";
  236. document.addEventListener(command, listener);
  237. document.execCommand(command);
  238. document.removeEventListener(command, listener);
  239. function listener(event) {
  240. event.clipboardData.setData("text/html", page.content);
  241. event.clipboardData.setData("text/plain", page.content);
  242. event.preventDefault();
  243. }
  244. }
  245. })();