content-main.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 */
  24. this.singlefile.extension.core.content.main = this.singlefile.extension.core.content.main || (() => {
  25. const singlefile = this.singlefile;
  26. let ui;
  27. const MAX_CONTENT_SIZE = 64 * (1024 * 1024);
  28. const DOWNLOADER_FRAME_ID = "single-file-downloader";
  29. const SingleFile = singlefile.lib.SingleFile.getClass();
  30. let processing = false;
  31. browser.runtime.onMessage.addListener(message => {
  32. if (!ui) {
  33. ui = singlefile.extension.ui.content.main;
  34. }
  35. if (message.method == "content.save") {
  36. savePage(message);
  37. }
  38. });
  39. return {};
  40. async function savePage(message) {
  41. const options = message.options;
  42. if (!processing) {
  43. let selectionFound;
  44. if (options.selected) {
  45. selectionFound = await ui.markSelection();
  46. }
  47. if (!options.selected || selectionFound) {
  48. processing = true;
  49. try {
  50. const page = await processPage(options);
  51. await downloadPage(page, options);
  52. } catch (error) {
  53. console.error(error); // eslint-disable-line no-console
  54. browser.runtime.sendMessage({ method: "ui.processError", error, options: {} });
  55. }
  56. } else {
  57. browser.runtime.sendMessage({ method: "ui.processCancelled", options: {} });
  58. }
  59. processing = false;
  60. }
  61. }
  62. async function processPage(options) {
  63. const frames = singlefile.lib.frameTree.content.frames;
  64. singlefile.lib.helper.initDoc(document);
  65. const iframe = document.getElementById(DOWNLOADER_FRAME_ID);
  66. if (iframe) {
  67. iframe.remove();
  68. }
  69. ui.onStartPage(options);
  70. const processor = new SingleFile(options);
  71. const preInitializationPromises = [];
  72. options.insertSingleFileComment = true;
  73. if (!options.saveRawPage) {
  74. if (!options.removeFrames && frames) {
  75. let frameTreePromise;
  76. if (options.loadDeferredImages) {
  77. frameTreePromise = new Promise(resolve => setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frames.TIMEOUT_INIT_REQUEST_MESSAGE));
  78. } else {
  79. frameTreePromise = frames.getAsync(options);
  80. }
  81. ui.onLoadingFrames();
  82. frameTreePromise.then(() => ui.onLoadFrames());
  83. preInitializationPromises.push(frameTreePromise);
  84. }
  85. if (options.loadDeferredImages) {
  86. const lazyLoadPromise = singlefile.lib.lazy.content.loader.process(options);
  87. ui.onLoadingDeferResources();
  88. lazyLoadPromise.then(() => ui.onLoadDeferResources());
  89. preInitializationPromises.push(lazyLoadPromise);
  90. }
  91. }
  92. let index = 0, maxIndex = 0;
  93. options.onprogress = event => {
  94. if (event.type == event.RESOURCES_INITIALIZED) {
  95. maxIndex = event.detail.max;
  96. }
  97. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  98. if (event.type == event.RESOURCE_LOADED) {
  99. index++;
  100. }
  101. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex, options: {} });
  102. ui.onLoadResource(index, maxIndex, options);
  103. } if (event.type == event.PAGE_ENDED) {
  104. browser.runtime.sendMessage({ method: "ui.processEnd", options: {} });
  105. } else if (!event.detail.frame) {
  106. if (event.type == event.PAGE_LOADING) {
  107. ui.onPageLoading();
  108. } else if (event.type == event.PAGE_LOADED) {
  109. ui.onLoadPage();
  110. } else if (event.type == event.STAGE_STARTED) {
  111. if (event.detail.step < 3) {
  112. ui.onStartStage(event.detail.step);
  113. }
  114. } else if (event.type == event.STAGE_ENDED) {
  115. if (event.detail.step < 3) {
  116. ui.onEndStage(event.detail.step);
  117. }
  118. } else if (event.type == event.STAGE_TASK_STARTED) {
  119. ui.onStartStageTask(event.detail.step, event.detail.task);
  120. } else if (event.type == event.STAGE_TASK_ENDED) {
  121. ui.onEndStageTask(event.detail.step, event.detail.task);
  122. }
  123. }
  124. };
  125. [options.framesData] = await Promise.all(preInitializationPromises);
  126. const selectedFrame = options.framesData && options.framesData.find(frameData => frameData.requestedFrame);
  127. options.win = window;
  128. if (selectedFrame) {
  129. options.content = selectedFrame.content;
  130. options.url = selectedFrame.baseURI;
  131. options.canvasData = selectedFrame.canvasData;
  132. options.fontsData = selectedFrame.fontsData;
  133. options.stylesheetsData = selectedFrame.stylesheetsData;
  134. options.imagesData = selectedFrame.imagesData;
  135. options.postersData = selectedFrame.postersData;
  136. options.usedFonts = selectedFrame.usedFonts;
  137. options.shadowRootsData = selectedFrame.shadowRootsData;
  138. } else {
  139. options.doc = document;
  140. }
  141. await processor.run();
  142. if (!options.saveRawPage && !options.removeFrames && frames) {
  143. frames.cleanup(options);
  144. }
  145. if (options.confirmInfobarContent) {
  146. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  147. }
  148. const page = await processor.getPageData();
  149. if (options.selected) {
  150. ui.unmarkSelection();
  151. }
  152. ui.onEndPage(options);
  153. if (options.displayStats) {
  154. console.log("SingleFile stats"); // eslint-disable-line no-console
  155. console.table(page.stats); // eslint-disable-line no-console
  156. }
  157. return page;
  158. }
  159. async function downloadPage(page, options) {
  160. if (options.backgroundSave) {
  161. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < page.content.length; blockIndex++) {
  162. const message = { method: "downloads.download", confirmFilename: options.confirmFilename, filenameConflictAction: options.filenameConflictAction, filename: page.filename, saveToClipboard: options.saveToClipboard };
  163. message.truncated = page.content.length > MAX_CONTENT_SIZE;
  164. if (message.truncated) {
  165. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > page.content.length;
  166. message.content = page.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  167. } else {
  168. message.content = page.content;
  169. }
  170. await browser.runtime.sendMessage(message);
  171. }
  172. } else {
  173. if (options.saveToClipboard) {
  174. saveToClipboard(page);
  175. } else {
  176. downloadPageForeground(page, options);
  177. }
  178. }
  179. }
  180. function downloadPageForeground(page, options) {
  181. if (options.confirmFilename) {
  182. page.filename = ui.prompt("File name", page.filename);
  183. }
  184. if (page.filename && page.filename.length) {
  185. const iframe = document.createElement("iframe");
  186. iframe.id = DOWNLOADER_FRAME_ID;
  187. iframe.style.setProperty("display", "inline-block", "important");
  188. iframe.style.setProperty("max-width", "0", "important");
  189. iframe.style.setProperty("max-height", "0", "important");
  190. iframe.style.setProperty("border-width", "0", "important");
  191. iframe.style.setProperty("margin", "0", "important");
  192. iframe.src = browser.runtime.getURL("/extension/core/pages/downloader.html");
  193. iframe.onload = () => iframe.contentWindow.postMessage(JSON.stringify([page.filename, page.content]), "*");
  194. document.body.appendChild(iframe);
  195. }
  196. }
  197. function saveToClipboard(page) {
  198. const command = "copy";
  199. document.addEventListener(command, listener);
  200. document.execCommand(command);
  201. document.removeEventListener(command, listener);
  202. function listener(event) {
  203. event.clipboardData.setData("text/html", page.content);
  204. event.clipboardData.setData("text/plain", page.content);
  205. event.preventDefault();
  206. }
  207. }
  208. })();