content.js 8.1 KB

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