content-main.js 9.3 KB

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