content-main.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. const MAX_CONTENT_SIZE = 32 * (1024 * 1024);
  27. const SingleFile = singlefile.lib.SingleFile.getClass();
  28. let ui, processing = false, processor;
  29. browser.runtime.onMessage.addListener(async message => {
  30. if (!ui) {
  31. ui = singlefile.extension.ui.content.main;
  32. }
  33. if (message.method == "content.save") {
  34. await savePage(message);
  35. return {};
  36. }
  37. if (message.method == "content.cancelSave") {
  38. if (processor) {
  39. processor.cancel();
  40. ui.onEndPage();
  41. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  42. }
  43. return {};
  44. }
  45. });
  46. return {};
  47. async function savePage(message) {
  48. const options = message.options;
  49. if (!processing) {
  50. options.updatedResources = singlefile.extension.core.content.updatedResources || {};
  51. Object.keys(options.updatedResources).forEach(url => options.updatedResources[url].retrieved = false);
  52. let selectionFound;
  53. if (options.selected) {
  54. selectionFound = await ui.markSelection();
  55. }
  56. if (!options.selected || selectionFound) {
  57. processing = true;
  58. try {
  59. const pageData = await processPage(options);
  60. if (pageData) {
  61. await downloadPage(pageData, options);
  62. }
  63. } catch (error) {
  64. if (!processor.cancelled) {
  65. console.error(error); // eslint-disable-line no-console
  66. browser.runtime.sendMessage({ method: "ui.processError", error });
  67. }
  68. }
  69. } else {
  70. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  71. }
  72. processing = false;
  73. }
  74. }
  75. async function processPage(options) {
  76. const frames = singlefile.lib.frameTree.content.frames;
  77. singlefile.lib.helper.initDoc(document);
  78. ui.onStartPage(options);
  79. processor = new SingleFile(options);
  80. const preInitializationPromises = [];
  81. options.insertSingleFileComment = true;
  82. if (!options.saveRawPage) {
  83. if (!options.removeFrames && frames && window.frames && window.frames.length) {
  84. let frameTreePromise;
  85. if (options.loadDeferredImages) {
  86. frameTreePromise = new Promise(resolve => setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frames.TIMEOUT_INIT_REQUEST_MESSAGE));
  87. } else {
  88. frameTreePromise = frames.getAsync(options);
  89. }
  90. ui.onLoadingFrames(options);
  91. frameTreePromise.then(() => {
  92. if (!processor.cancelled) {
  93. ui.onLoadFrames(options);
  94. }
  95. });
  96. preInitializationPromises.push(frameTreePromise);
  97. }
  98. if (options.loadDeferredImages) {
  99. const lazyLoadPromise = singlefile.lib.lazy.content.loader.process(options);
  100. ui.onLoadingDeferResources(options);
  101. lazyLoadPromise.then(() => {
  102. if (!processor.cancelled) {
  103. ui.onLoadDeferResources(options);
  104. }
  105. });
  106. preInitializationPromises.push(lazyLoadPromise);
  107. }
  108. }
  109. let index = 0, maxIndex = 0;
  110. options.onprogress = event => {
  111. if (!processor.cancelled) {
  112. if (event.type == event.RESOURCES_INITIALIZED) {
  113. maxIndex = event.detail.max;
  114. }
  115. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  116. if (event.type == event.RESOURCE_LOADED) {
  117. index++;
  118. }
  119. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex });
  120. ui.onLoadResource(index, maxIndex, options);
  121. } if (event.type == event.PAGE_ENDED) {
  122. browser.runtime.sendMessage({ method: "ui.processEnd" });
  123. } else if (!event.detail.frame) {
  124. if (event.type == event.PAGE_LOADING) {
  125. ui.onPageLoading();
  126. } else if (event.type == event.PAGE_LOADED) {
  127. ui.onLoadPage();
  128. } else if (event.type == event.STAGE_STARTED) {
  129. if (event.detail.step < 3) {
  130. ui.onStartStage(event.detail.step, options);
  131. }
  132. } else if (event.type == event.STAGE_ENDED) {
  133. if (event.detail.step < 3) {
  134. ui.onEndStage(event.detail.step, options);
  135. }
  136. } else if (event.type == event.STAGE_TASK_STARTED) {
  137. ui.onStartStageTask(event.detail.step, event.detail.task);
  138. } else if (event.type == event.STAGE_TASK_ENDED) {
  139. ui.onEndStageTask(event.detail.step, event.detail.task);
  140. }
  141. }
  142. }
  143. };
  144. [options.frames] = await new Promise(async resolve => {
  145. const preInitializationAllPromises = Promise.all(preInitializationPromises);
  146. const cancelProcessor = processor.cancel.bind(processor);
  147. processor.cancel = function () {
  148. cancelProcessor();
  149. resolve([[]]);
  150. };
  151. await preInitializationAllPromises;
  152. resolve(preInitializationAllPromises);
  153. });
  154. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  155. options.win = window;
  156. if (selectedFrame) {
  157. options.content = selectedFrame.content;
  158. options.url = selectedFrame.baseURI;
  159. options.canvases = selectedFrame.canvases;
  160. options.fonts = selectedFrame.fonts;
  161. options.stylesheets = selectedFrame.stylesheets;
  162. options.images = selectedFrame.images;
  163. options.posters = selectedFrame.posters;
  164. options.usedFonts = selectedFrame.usedFonts;
  165. options.shadowRoots = selectedFrame.shadowRoots;
  166. options.imports = selectedFrame.imports;
  167. } else {
  168. options.doc = document;
  169. }
  170. if (!processor.cancelled) {
  171. await processor.run();
  172. }
  173. if (!options.saveRawPage && !options.removeFrames && frames) {
  174. frames.cleanup(options);
  175. }
  176. let page;
  177. if (!processor.cancelled) {
  178. if (options.confirmInfobarContent) {
  179. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  180. }
  181. page = await processor.getPageData();
  182. if (options.selected) {
  183. ui.unmarkSelection();
  184. }
  185. ui.onEndPage();
  186. if (options.displayStats) {
  187. console.log("SingleFile stats"); // eslint-disable-line no-console
  188. console.table(page.stats); // eslint-disable-line no-console
  189. }
  190. }
  191. return page;
  192. }
  193. async function downloadPage(pageData, options) {
  194. if (options.includeInfobar) {
  195. await singlefile.common.ui.content.infobar.includeScript(pageData);
  196. }
  197. if (options.backgroundSave) {
  198. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < pageData.content.length; blockIndex++) {
  199. const message = {
  200. method: "downloads.download",
  201. confirmFilename: options.confirmFilename,
  202. filenameConflictAction: options.filenameConflictAction,
  203. filename: pageData.filename,
  204. saveToClipboard: options.saveToClipboard,
  205. filenameReplacementCharacter: options.filenameReplacementCharacter
  206. };
  207. message.truncated = pageData.content.length > MAX_CONTENT_SIZE;
  208. if (message.truncated) {
  209. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > pageData.content.length;
  210. message.content = pageData.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  211. } else {
  212. message.content = pageData.content;
  213. }
  214. await browser.runtime.sendMessage(message);
  215. }
  216. } else {
  217. if (options.saveToClipboard) {
  218. saveToClipboard(pageData);
  219. } else {
  220. downloadPageForeground(pageData, options);
  221. }
  222. }
  223. await browser.runtime.sendMessage({ method: "downloads.end" });
  224. }
  225. function downloadPageForeground(pageData, options) {
  226. if (options.confirmFilename) {
  227. pageData.filename = ui.prompt("File name", pageData.filename);
  228. }
  229. if (pageData.filename && pageData.filename.length) {
  230. const link = document.createElement("a");
  231. link.download = pageData.filename;
  232. link.href = URL.createObjectURL(new Blob([pageData.content], { type: "text/html" }));
  233. link.dispatchEvent(new MouseEvent("click"));
  234. URL.revokeObjectURL(link.href);
  235. }
  236. }
  237. function saveToClipboard(page) {
  238. const command = "copy";
  239. document.addEventListener(command, listener);
  240. document.execCommand(command);
  241. document.removeEventListener(command, listener);
  242. function listener(event) {
  243. event.clipboardData.setData("text/html", page.content);
  244. event.clipboardData.setData("text/plain", page.content);
  245. event.preventDefault();
  246. }
  247. }
  248. })();