content-main.js 8.9 KB

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