content-main.js 9.2 KB

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