content.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. try {
  83. const pageData = await processPage(options);
  84. if (pageData) {
  85. if (((!options.backgroundSave && !options.saveToClipboard) || options.saveToGDrive || options.saveToGitHub || options.saveWithCompanion) && options.confirmFilename) {
  86. pageData.filename = ui.prompt("Save as", pageData.filename) || pageData.filename;
  87. }
  88. await download.downloadPage(pageData, options);
  89. }
  90. } catch (error) {
  91. if (!processor.cancelled) {
  92. console.error(error); // eslint-disable-line no-console
  93. browser.runtime.sendMessage({ method: "ui.processError", error });
  94. }
  95. }
  96. } else {
  97. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  98. }
  99. processing = false;
  100. if (bootstrap) {
  101. bootstrap.pageInfo.processing = false;
  102. }
  103. }
  104. }
  105. async function processPage(options) {
  106. const frames = singlefile.processors.frameTree;
  107. let framesSessionId;
  108. singlefile.helper.initDoc(document);
  109. ui.onStartPage(options);
  110. processor = new singlefile.SingleFile(options);
  111. const preInitializationPromises = [];
  112. options.insertCanonicalLink = true;
  113. if (!options.saveRawPage) {
  114. if (!options.removeFrames && frames && globalThis.frames && globalThis.frames.length) {
  115. let frameTreePromise;
  116. if (options.loadDeferredImages) {
  117. frameTreePromise = new Promise(resolve => setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frames.TIMEOUT_INIT_REQUEST_MESSAGE));
  118. } else {
  119. frameTreePromise = frames.getAsync(options);
  120. }
  121. ui.onLoadingFrames(options);
  122. frameTreePromise.then(() => {
  123. if (!processor.cancelled) {
  124. ui.onLoadFrames(options);
  125. }
  126. });
  127. preInitializationPromises.push(frameTreePromise);
  128. }
  129. if (options.loadDeferredImages) {
  130. const lazyLoadPromise = singlefile.processors.lazy.process(options);
  131. ui.onLoadingDeferResources(options);
  132. lazyLoadPromise.then(() => {
  133. if (!processor.cancelled) {
  134. ui.onLoadDeferResources(options);
  135. }
  136. });
  137. preInitializationPromises.push(lazyLoadPromise);
  138. }
  139. }
  140. let index = 0, maxIndex = 0;
  141. options.onprogress = event => {
  142. if (!processor.cancelled) {
  143. if (event.type == event.RESOURCES_INITIALIZED) {
  144. maxIndex = event.detail.max;
  145. if (options.loadDeferredImages) {
  146. singlefile.processors.lazy.resetZoomLevel(options);
  147. }
  148. }
  149. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  150. if (event.type == event.RESOURCE_LOADED) {
  151. index++;
  152. }
  153. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex });
  154. ui.onLoadResource(index, maxIndex, options);
  155. } else if (!event.detail.frame) {
  156. if (event.type == event.PAGE_LOADING) {
  157. ui.onPageLoading();
  158. } else if (event.type == event.PAGE_LOADED) {
  159. ui.onLoadPage();
  160. } else if (event.type == event.STAGE_STARTED) {
  161. if (event.detail.step < 3) {
  162. ui.onStartStage(event.detail.step, options);
  163. }
  164. } else if (event.type == event.STAGE_ENDED) {
  165. if (event.detail.step < 3) {
  166. ui.onEndStage(event.detail.step, options);
  167. }
  168. } else if (event.type == event.STAGE_TASK_STARTED) {
  169. ui.onStartStageTask(event.detail.step, event.detail.task);
  170. } else if (event.type == event.STAGE_TASK_ENDED) {
  171. ui.onEndStageTask(event.detail.step, event.detail.task);
  172. }
  173. }
  174. }
  175. };
  176. [options.frames] = await new Promise(resolve => {
  177. const preInitializationAllPromises = Promise.all(preInitializationPromises);
  178. const cancelProcessor = processor.cancel.bind(processor);
  179. processor.cancel = function () {
  180. cancelProcessor();
  181. resolve([[]]);
  182. };
  183. preInitializationAllPromises.then(() => resolve(preInitializationAllPromises));
  184. });
  185. framesSessionId = options.frames && options.frames.sessionId;
  186. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  187. options.win = globalThis;
  188. if (selectedFrame) {
  189. options.content = selectedFrame.content;
  190. options.url = selectedFrame.baseURI;
  191. options.canvases = selectedFrame.canvases;
  192. options.fonts = selectedFrame.fonts;
  193. options.stylesheets = selectedFrame.stylesheets;
  194. options.images = selectedFrame.images;
  195. options.posters = selectedFrame.posters;
  196. options.usedFonts = selectedFrame.usedFonts;
  197. options.shadowRoots = selectedFrame.shadowRoots;
  198. options.imports = selectedFrame.imports;
  199. } else {
  200. options.doc = document;
  201. }
  202. if (!processor.cancelled) {
  203. await processor.run();
  204. }
  205. if (framesSessionId) {
  206. frames.cleanup(framesSessionId);
  207. }
  208. let page;
  209. if (!processor.cancelled) {
  210. if (options.confirmInfobarContent) {
  211. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  212. }
  213. page = await processor.getPageData();
  214. if (options.selected || options.optionallySelected) {
  215. ui.unmarkSelection();
  216. }
  217. ui.onEndPage();
  218. if (options.displayStats) {
  219. console.log("SingleFile stats"); // eslint-disable-line no-console
  220. console.table(page.stats); // eslint-disable-line no-console
  221. }
  222. }
  223. return page;
  224. }