content-main.js 8.0 KB

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