content.js 8.3 KB

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