content.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. /*
  2. * Copyright 2010-2020 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, globalThis, location, setTimeout */
  24. import * as download from "./../common/download.js";
  25. import { fetch, frameFetch } from "./../../lib/single-file/fetch/content/content-fetch.js";
  26. import * as ui from "./../../ui/content/content-ui.js";
  27. const singlefile = globalThis.singlefile;
  28. const bootstrap = globalThis.singlefileBootstrap;
  29. const MOZ_EXTENSION_PROTOCOL = "moz-extension:";
  30. let processor, processing;
  31. singlefile.init({ fetch, frameFetch });
  32. browser.runtime.onMessage.addListener(message => {
  33. if (message.method == "content.save" || message.method == "content.cancelSave" || message.method == "content.getSelectedLinks") {
  34. return onMessage(message);
  35. }
  36. });
  37. async function onMessage(message) {
  38. if (!location.href.startsWith(MOZ_EXTENSION_PROTOCOL)) {
  39. if (message.method == "content.save") {
  40. await savePage(message);
  41. return {};
  42. }
  43. if (message.method == "content.cancelSave") {
  44. if (processor) {
  45. processor.cancel();
  46. ui.onEndPage();
  47. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  48. }
  49. if (message.options.loadDeferredImages) {
  50. singlefile.processors.lazy.resetZoomLevel(message.options);
  51. }
  52. return {};
  53. }
  54. if (message.method == "content.getSelectedLinks") {
  55. return {
  56. urls: ui.getSelectedLinks()
  57. };
  58. }
  59. }
  60. }
  61. async function savePage(message) {
  62. const options = message.options;
  63. let selectionFound;
  64. if (options.selected || options.optionallySelected) {
  65. selectionFound = await ui.markSelection(options.optionallySelected);
  66. }
  67. if (!processing && (!bootstrap || !bootstrap.pageInfo.processing)) {
  68. options.updatedResources = bootstrap ? bootstrap.pageInfo.updatedResources : {};
  69. options.visitDate = bootstrap ? bootstrap.pageInfo.visitDate : new Date();
  70. Object.keys(options.updatedResources).forEach(url => options.updatedResources[url].retrieved = false);
  71. if (options.optionallySelected && selectionFound) {
  72. options.selected = true;
  73. }
  74. if (!options.selected || selectionFound) {
  75. if (bootstrap) {
  76. bootstrap.pageInfo.processing = true;
  77. }
  78. try {
  79. const pageData = await processPage(options);
  80. if (pageData) {
  81. if (((!options.backgroundSave && !options.saveToClipboard) || options.saveToGDrive) && options.confirmFilename) {
  82. pageData.filename = ui.prompt("Save as", pageData.filename) || pageData.filename;
  83. }
  84. await download.downloadPage(pageData, options);
  85. }
  86. } catch (error) {
  87. if (!processor.cancelled) {
  88. console.error(error); // eslint-disable-line no-console
  89. browser.runtime.sendMessage({ method: "ui.processError", error });
  90. }
  91. }
  92. } else {
  93. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  94. }
  95. processing = false;
  96. if (bootstrap) {
  97. bootstrap.pageInfo.processing = false;
  98. }
  99. }
  100. }
  101. async function processPage(options) {
  102. const frames = singlefile.processors.frameTree;
  103. let framesSessionId;
  104. singlefile.helper.initDoc(document);
  105. ui.onStartPage(options);
  106. processor = new singlefile.SingleFile(options);
  107. const preInitializationPromises = [];
  108. options.insertSingleFileComment = true;
  109. options.insertCanonicalLink = true;
  110. if (!options.saveRawPage) {
  111. if (!options.removeFrames && frames && globalThis.frames && globalThis.frames.length) {
  112. let frameTreePromise;
  113. if (options.loadDeferredImages) {
  114. frameTreePromise = new Promise(resolve => setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frames.TIMEOUT_INIT_REQUEST_MESSAGE));
  115. } else {
  116. frameTreePromise = frames.getAsync(options);
  117. }
  118. ui.onLoadingFrames(options);
  119. frameTreePromise.then(() => {
  120. if (!processor.cancelled) {
  121. ui.onLoadFrames(options);
  122. }
  123. });
  124. preInitializationPromises.push(frameTreePromise);
  125. }
  126. if (options.loadDeferredImages) {
  127. const lazyLoadPromise = singlefile.processors.lazy.process(options);
  128. ui.onLoadingDeferResources(options);
  129. lazyLoadPromise.then(() => {
  130. if (!processor.cancelled) {
  131. ui.onLoadDeferResources(options);
  132. }
  133. });
  134. preInitializationPromises.push(lazyLoadPromise);
  135. }
  136. }
  137. let index = 0, maxIndex = 0;
  138. options.onprogress = event => {
  139. if (!processor.cancelled) {
  140. if (event.type == event.RESOURCES_INITIALIZED) {
  141. maxIndex = event.detail.max;
  142. if (options.loadDeferredImages) {
  143. singlefile.processors.lazy.resetZoomLevel(options);
  144. }
  145. }
  146. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  147. if (event.type == event.RESOURCE_LOADED) {
  148. index++;
  149. }
  150. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex });
  151. ui.onLoadResource(index, maxIndex, options);
  152. } else if (!event.detail.frame) {
  153. if (event.type == event.PAGE_LOADING) {
  154. ui.onPageLoading();
  155. } else if (event.type == event.PAGE_LOADED) {
  156. ui.onLoadPage();
  157. } else if (event.type == event.STAGE_STARTED) {
  158. if (event.detail.step < 3) {
  159. ui.onStartStage(event.detail.step, options);
  160. }
  161. } else if (event.type == event.STAGE_ENDED) {
  162. if (event.detail.step < 3) {
  163. ui.onEndStage(event.detail.step, options);
  164. }
  165. } else if (event.type == event.STAGE_TASK_STARTED) {
  166. ui.onStartStageTask(event.detail.step, event.detail.task);
  167. } else if (event.type == event.STAGE_TASK_ENDED) {
  168. ui.onEndStageTask(event.detail.step, event.detail.task);
  169. }
  170. }
  171. }
  172. };
  173. [options.frames] = await new Promise(resolve => {
  174. const preInitializationAllPromises = Promise.all(preInitializationPromises);
  175. const cancelProcessor = processor.cancel.bind(processor);
  176. processor.cancel = function () {
  177. cancelProcessor();
  178. resolve([[]]);
  179. };
  180. preInitializationAllPromises.then(() => resolve(preInitializationAllPromises));
  181. });
  182. framesSessionId = options.frames && options.frames.sessionId;
  183. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  184. options.win = globalThis;
  185. if (selectedFrame) {
  186. options.content = selectedFrame.content;
  187. options.url = selectedFrame.baseURI;
  188. options.canvases = selectedFrame.canvases;
  189. options.fonts = selectedFrame.fonts;
  190. options.stylesheets = selectedFrame.stylesheets;
  191. options.images = selectedFrame.images;
  192. options.posters = selectedFrame.posters;
  193. options.usedFonts = selectedFrame.usedFonts;
  194. options.shadowRoots = selectedFrame.shadowRoots;
  195. options.imports = selectedFrame.imports;
  196. } else {
  197. options.doc = document;
  198. }
  199. if (!processor.cancelled) {
  200. await processor.run();
  201. }
  202. if (framesSessionId) {
  203. frames.cleanup(framesSessionId);
  204. }
  205. let page;
  206. if (!processor.cancelled) {
  207. if (options.confirmInfobarContent) {
  208. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  209. }
  210. page = await processor.getPageData();
  211. if (options.selected || options.optionallySelected) {
  212. ui.unmarkSelection();
  213. }
  214. ui.onEndPage();
  215. if (options.displayStats) {
  216. console.log("SingleFile stats"); // eslint-disable-line no-console
  217. console.table(page.stats); // eslint-disable-line no-console
  218. }
  219. }
  220. return page;
  221. }