content-main.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. options.imports = selectedFrame.imports;
  140. } else {
  141. options.doc = document;
  142. }
  143. await processor.run();
  144. if (!options.saveRawPage && !options.removeFrames && frames) {
  145. frames.cleanup(options);
  146. }
  147. if (options.confirmInfobarContent) {
  148. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  149. }
  150. const page = await processor.getPageData();
  151. if (options.selected) {
  152. ui.unmarkSelection();
  153. }
  154. ui.onEndPage(options);
  155. if (options.displayStats) {
  156. console.log("SingleFile stats"); // eslint-disable-line no-console
  157. console.table(page.stats); // eslint-disable-line no-console
  158. }
  159. return page;
  160. }
  161. async function downloadPage(page, options) {
  162. if (options.backgroundSave) {
  163. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < page.content.length; blockIndex++) {
  164. const message = {
  165. method: "downloads.download",
  166. confirmFilename: options.confirmFilename,
  167. filenameConflictAction: options.filenameConflictAction,
  168. filename: page.filename,
  169. saveToClipboard: options.saveToClipboard,
  170. filenameReplacementCharacter: options.filenameReplacementCharacter
  171. };
  172. message.truncated = page.content.length > MAX_CONTENT_SIZE;
  173. if (message.truncated) {
  174. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > page.content.length;
  175. message.content = page.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  176. } else {
  177. message.content = page.content;
  178. }
  179. await browser.runtime.sendMessage(message);
  180. }
  181. } else {
  182. if (options.saveToClipboard) {
  183. saveToClipboard(page);
  184. } else {
  185. downloadPageForeground(page, options);
  186. }
  187. }
  188. }
  189. function downloadPageForeground(page, options) {
  190. if (options.confirmFilename) {
  191. page.filename = ui.prompt("File name", page.filename);
  192. }
  193. if (page.filename && page.filename.length) {
  194. const iframe = document.createElement("iframe");
  195. iframe.id = DOWNLOADER_FRAME_ID;
  196. iframe.style.setProperty("display", "inline-block", "important");
  197. iframe.style.setProperty("max-width", "0", "important");
  198. iframe.style.setProperty("max-height", "0", "important");
  199. iframe.style.setProperty("border-width", "0", "important");
  200. iframe.style.setProperty("margin", "0", "important");
  201. iframe.src = browser.runtime.getURL("/extension/core/pages/downloader.html");
  202. iframe.onload = () => iframe.contentWindow.postMessage(JSON.stringify([page.filename, page.content]), "*");
  203. document.body.appendChild(iframe);
  204. }
  205. }
  206. function saveToClipboard(page) {
  207. const command = "copy";
  208. document.addEventListener(command, listener);
  209. document.execCommand(command);
  210. document.removeEventListener(command, listener);
  211. function listener(event) {
  212. event.clipboardData.setData("text/html", page.content);
  213. event.clipboardData.setData("text/plain", page.content);
  214. event.preventDefault();
  215. }
  216. }
  217. })();