content-main.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. let ui;
  27. const MAX_CONTENT_SIZE = 64 * (1024 * 1024);
  28. const SingleFile = singlefile.lib.SingleFile.getClass();
  29. let processing = false;
  30. browser.runtime.onMessage.addListener(async message => {
  31. if (!ui) {
  32. ui = singlefile.extension.ui.content.main;
  33. }
  34. if (message.method == "content.save") {
  35. await savePage(message);
  36. return {};
  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 });
  55. }
  56. } else {
  57. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  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. ui.onStartPage(options);
  66. const processor = new SingleFile(options);
  67. const preInitializationPromises = [];
  68. options.insertSingleFileComment = true;
  69. if (!options.saveRawPage) {
  70. if (!options.removeFrames && frames) {
  71. let frameTreePromise;
  72. if (options.loadDeferredImages) {
  73. frameTreePromise = new Promise(resolve => setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frames.TIMEOUT_INIT_REQUEST_MESSAGE));
  74. } else {
  75. frameTreePromise = frames.getAsync(options);
  76. }
  77. ui.onLoadingFrames(options);
  78. frameTreePromise.then(() => ui.onLoadFrames(options));
  79. preInitializationPromises.push(frameTreePromise);
  80. }
  81. if (options.loadDeferredImages) {
  82. const lazyLoadPromise = singlefile.lib.lazy.content.loader.process(options);
  83. ui.onLoadingDeferResources(options);
  84. lazyLoadPromise.then(() => ui.onLoadDeferResources(options));
  85. preInitializationPromises.push(lazyLoadPromise);
  86. }
  87. }
  88. let index = 0, maxIndex = 0;
  89. options.onprogress = event => {
  90. if (event.type == event.RESOURCES_INITIALIZED) {
  91. maxIndex = event.detail.max;
  92. }
  93. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  94. if (event.type == event.RESOURCE_LOADED) {
  95. index++;
  96. }
  97. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex });
  98. ui.onLoadResource(index, maxIndex, options);
  99. } if (event.type == event.PAGE_ENDED) {
  100. browser.runtime.sendMessage({ method: "ui.processEnd" });
  101. } else if (!event.detail.frame) {
  102. if (event.type == event.PAGE_LOADING) {
  103. ui.onPageLoading();
  104. } else if (event.type == event.PAGE_LOADED) {
  105. ui.onLoadPage();
  106. } else if (event.type == event.STAGE_STARTED) {
  107. if (event.detail.step < 3) {
  108. ui.onStartStage(event.detail.step, options);
  109. }
  110. } else if (event.type == event.STAGE_ENDED) {
  111. if (event.detail.step < 3) {
  112. ui.onEndStage(event.detail.step, options);
  113. }
  114. } else if (event.type == event.STAGE_TASK_STARTED) {
  115. ui.onStartStageTask(event.detail.step, event.detail.task);
  116. } else if (event.type == event.STAGE_TASK_ENDED) {
  117. ui.onEndStageTask(event.detail.step, event.detail.task);
  118. }
  119. }
  120. };
  121. [options.frames] = await Promise.all(preInitializationPromises);
  122. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  123. options.win = window;
  124. if (selectedFrame) {
  125. options.content = selectedFrame.content;
  126. options.url = selectedFrame.baseURI;
  127. options.canvases = selectedFrame.canvases;
  128. options.fonts = selectedFrame.fonts;
  129. options.stylesheets = selectedFrame.stylesheets;
  130. options.images = selectedFrame.images;
  131. options.posters = selectedFrame.posters;
  132. options.usedFonts = selectedFrame.usedFonts;
  133. options.shadowRoots = selectedFrame.shadowRoots;
  134. options.imports = selectedFrame.imports;
  135. } else {
  136. options.doc = document;
  137. }
  138. await processor.run();
  139. if (!options.saveRawPage && !options.removeFrames && frames) {
  140. frames.cleanup(options);
  141. }
  142. if (options.confirmInfobarContent) {
  143. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  144. }
  145. const page = await processor.getPageData();
  146. if (options.selected) {
  147. ui.unmarkSelection();
  148. }
  149. ui.onEndPage(options);
  150. if (options.displayStats) {
  151. console.log("SingleFile stats"); // eslint-disable-line no-console
  152. console.table(page.stats); // eslint-disable-line no-console
  153. }
  154. return page;
  155. }
  156. async function downloadPage(page, options) {
  157. if (options.backgroundSave) {
  158. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < page.content.length; blockIndex++) {
  159. const message = {
  160. method: "downloads.download",
  161. confirmFilename: options.confirmFilename,
  162. filenameConflictAction: options.filenameConflictAction,
  163. filename: page.filename,
  164. saveToClipboard: options.saveToClipboard,
  165. filenameReplacementCharacter: options.filenameReplacementCharacter
  166. };
  167. message.truncated = page.content.length > MAX_CONTENT_SIZE;
  168. if (message.truncated) {
  169. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > page.content.length;
  170. message.content = page.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  171. } else {
  172. message.content = page.content;
  173. }
  174. await browser.runtime.sendMessage(message);
  175. }
  176. } else {
  177. if (options.saveToClipboard) {
  178. saveToClipboard(page);
  179. } else {
  180. downloadPageForeground(page, options);
  181. }
  182. }
  183. }
  184. function downloadPageForeground(page, options) {
  185. if (options.confirmFilename) {
  186. page.filename = ui.prompt("File name", page.filename);
  187. }
  188. if (page.filename && page.filename.length) {
  189. const link = document.createElement("a");
  190. link.download = page.filename;
  191. link.href = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  192. link.dispatchEvent(new MouseEvent("click"));
  193. URL.revokeObjectURL(link.href);
  194. }
  195. }
  196. function saveToClipboard(page) {
  197. const command = "copy";
  198. document.addEventListener(command, listener);
  199. document.execCommand(command);
  200. document.removeEventListener(command, listener);
  201. function listener(event) {
  202. event.clipboardData.setData("text/html", page.content);
  203. event.clipboardData.setData("text/plain", page.content);
  204. event.preventDefault();
  205. }
  206. }
  207. })();