content.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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, URL, Blob, MouseEvent */
  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, getOpenFileBar, openFile } from "./../../ui/common/common-content-ui.js";
  28. import * as yabson from "./../../lib/yabson/yabson.js";
  29. const singlefile = globalThis.singlefile;
  30. const bootstrap = globalThis.singlefileBootstrap;
  31. const MOZ_EXTENSION_PROTOCOL = "moz-extension:";
  32. let processor, processing, downloadParser, openFileInfobar;
  33. if (!bootstrap || !bootstrap.initializedSingleFile) {
  34. singlefile.init({ fetch, frameFetch });
  35. browser.runtime.onMessage.addListener(message => {
  36. if (message.method == "content.save" || message.method == "content.cancelSave" || message.method == "content.download" || message.method == "content.getSelectedLinks" || message.method == "content.error" || message.method == "content.prompt") {
  37. return onMessage(message);
  38. }
  39. });
  40. if (bootstrap) {
  41. bootstrap.initializedSingleFile = true;
  42. } else {
  43. globalThis.singlefileBootstrap = { initializedSingleFile: true };
  44. }
  45. }
  46. async function onMessage(message) {
  47. if (!location.href.startsWith(MOZ_EXTENSION_PROTOCOL)) {
  48. if (message.method == "content.save") {
  49. await savePage(message);
  50. return {};
  51. }
  52. if (message.method == "content.cancelSave") {
  53. if (processor) {
  54. processor.cancel();
  55. ui.onEndPage();
  56. if (openFileInfobar) {
  57. openFileInfobar.cancel();
  58. openFileInfobar = null;
  59. }
  60. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  61. }
  62. if (message.options.loadDeferredImages) {
  63. singlefile.processors.lazy.resetZoomLevel(message.options);
  64. }
  65. return {};
  66. }
  67. if (message.method == "content.getSelectedLinks") {
  68. return {
  69. urls: ui.getSelectedLinks()
  70. };
  71. }
  72. if (message.method == "content.download") {
  73. if (!downloadParser) {
  74. downloadParser = yabson.getParser();
  75. }
  76. const result = await downloadParser.next(message.data);
  77. if (result.done) {
  78. downloadParser = null;
  79. const link = document.createElement("a");
  80. link.download = result.value.filename;
  81. link.href = URL.createObjectURL(new Blob([result.value.content]), "text/html");
  82. link.dispatchEvent(new MouseEvent("click"));
  83. URL.revokeObjectURL(link.href);
  84. await browser.runtime.sendMessage({ method: "downloads.end", taskId: result.value.taskId });
  85. }
  86. return {};
  87. }
  88. if (message.method == "content.error") {
  89. onError(message.error, message.link);
  90. return {};
  91. }
  92. if (message.method == "content.prompt") {
  93. return ui.prompt(message.message, message.value);
  94. }
  95. }
  96. }
  97. async function savePage(message) {
  98. const options = message.options;
  99. let selectionFound;
  100. if (options.selected || options.optionallySelected) {
  101. selectionFound = await ui.markSelection(options.optionallySelected);
  102. }
  103. if (!processing && (!bootstrap || !bootstrap.pageInfo.processing)) {
  104. options.updatedResources = bootstrap ? bootstrap.pageInfo.updatedResources : {};
  105. options.visitDate = bootstrap ? bootstrap.pageInfo.visitDate : new Date();
  106. Object.keys(options.updatedResources).forEach(url => options.updatedResources[url].retrieved = false);
  107. if (options.optionallySelected && selectionFound) {
  108. options.selected = true;
  109. }
  110. if (!options.selected || selectionFound) {
  111. if (bootstrap) {
  112. bootstrap.pageInfo.processing = true;
  113. }
  114. processing = true;
  115. try {
  116. const pageData = await processPage(options);
  117. if (pageData) {
  118. if (((!options.backgroundSave && !options.saveToClipboard) || options.saveToGDrive || options.saveToGitHub || options.saveWithCompanion || options.saveWithWebDAV || options.saveToDropbox) && options.confirmFilename) {
  119. pageData.filename = ui.prompt("Save as", pageData.filename) || pageData.filename;
  120. }
  121. await download.downloadPage(pageData, options);
  122. }
  123. } catch (error) {
  124. if (!processor.cancelled) {
  125. console.error(error); // eslint-disable-line no-console
  126. const errorMessage = error.toString();
  127. browser.runtime.sendMessage({ method: "ui.processError", error: errorMessage });
  128. onError(errorMessage);
  129. }
  130. }
  131. } else {
  132. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  133. }
  134. processing = false;
  135. if (bootstrap) {
  136. bootstrap.pageInfo.processing = false;
  137. }
  138. }
  139. }
  140. async function processPage(options) {
  141. const frames = singlefile.processors.frameTree;
  142. let framesSessionId;
  143. options.keepFilename = options.saveToGDrive || options.saveToGitHub || options.saveWithWebDAV || options.saveToDropbox;
  144. singlefile.helper.initDoc(document);
  145. ui.onStartPage(options);
  146. processor = new singlefile.SingleFile(options);
  147. const preInitializationPromises = [];
  148. options.insertCanonicalLink = true;
  149. let index = 0, maxIndex = 0;
  150. options.onprogress = event => {
  151. if (!processor.cancelled) {
  152. if (event.type == event.RESOURCES_INITIALIZED) {
  153. maxIndex = event.detail.max;
  154. if (options.loadDeferredImages) {
  155. singlefile.processors.lazy.resetZoomLevel(options);
  156. }
  157. }
  158. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  159. if (event.type == event.RESOURCE_LOADED) {
  160. index++;
  161. }
  162. browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex });
  163. ui.onLoadResource(index, maxIndex, options);
  164. } else if (!event.detail.frame) {
  165. if (event.type == event.PAGE_LOADING) {
  166. ui.onPageLoading();
  167. } else if (event.type == event.PAGE_LOADED) {
  168. ui.onLoadPage();
  169. } else if (event.type == event.STAGE_STARTED) {
  170. if (event.detail.step < 3) {
  171. ui.onStartStage(event.detail.step, options);
  172. }
  173. } else if (event.type == event.STAGE_ENDED) {
  174. if (event.detail.step < 3) {
  175. ui.onEndStage(event.detail.step, options);
  176. }
  177. } else if (event.type == event.STAGE_TASK_STARTED) {
  178. ui.onStartStageTask(event.detail.step, event.detail.task);
  179. } else if (event.type == event.STAGE_TASK_ENDED) {
  180. ui.onEndStageTask(event.detail.step, event.detail.task);
  181. }
  182. }
  183. }
  184. };
  185. const cancelProcessor = processor.cancel.bind(processor);
  186. if (options.insertEmbeddedImage) {
  187. ui.onInsertingEmbeddedImage(options);
  188. openFileInfobar = getOpenFileBar();
  189. const cancelled = await openFileInfobar.display();
  190. if (!cancelled) {
  191. options.embeddedImage = await openFile({ accept: "image/*" });
  192. openFileInfobar.hide();
  193. }
  194. ui.onInsertEmbeddedImage(options);
  195. }
  196. if (!options.saveRawPage && !processor.cancelled) {
  197. let lazyLoadPromise;
  198. if (options.loadDeferredImages) {
  199. lazyLoadPromise = singlefile.processors.lazy.process(options);
  200. ui.onLoadingDeferResources(options);
  201. lazyLoadPromise.then(() => {
  202. if (!processor.cancelled) {
  203. ui.onLoadDeferResources(options);
  204. }
  205. });
  206. if (options.loadDeferredImagesBeforeFrames) {
  207. await lazyLoadPromise;
  208. }
  209. }
  210. if (!options.removeFrames && frames && globalThis.frames) {
  211. let frameTreePromise;
  212. if (options.loadDeferredImages) {
  213. frameTreePromise = new Promise(resolve => globalThis.setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesBeforeFrames || !options.loadDeferredImages ? 0 : options.loadDeferredImagesMaxIdleTime));
  214. } else {
  215. frameTreePromise = frames.getAsync(options);
  216. }
  217. ui.onLoadingFrames(options);
  218. frameTreePromise.then(() => {
  219. if (!processor.cancelled) {
  220. ui.onLoadFrames(options);
  221. }
  222. });
  223. if (options.loadDeferredImagesBeforeFrames) {
  224. options.frames = await new Promise(resolve => {
  225. processor.cancel = function () {
  226. cancelProcessor();
  227. resolve([]);
  228. };
  229. frameTreePromise.then(resolve);
  230. });
  231. } else {
  232. preInitializationPromises.push(frameTreePromise);
  233. }
  234. }
  235. if (options.loadDeferredImages && !options.loadDeferredImagesBeforeFrames) {
  236. preInitializationPromises.push(lazyLoadPromise);
  237. }
  238. }
  239. if (!options.loadDeferredImagesBeforeFrames && !processor.cancelled) {
  240. [options.frames] = await new Promise(resolve => {
  241. const preInitializationAllPromises = Promise.all(preInitializationPromises);
  242. processor.cancel = function () {
  243. cancelProcessor();
  244. resolve([[]]);
  245. };
  246. preInitializationAllPromises.then(() => resolve(preInitializationAllPromises));
  247. });
  248. }
  249. framesSessionId = options.frames && options.frames.sessionId;
  250. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  251. options.win = globalThis;
  252. if (selectedFrame) {
  253. options.content = selectedFrame.content;
  254. options.url = selectedFrame.baseURI;
  255. options.canvases = selectedFrame.canvases;
  256. options.fonts = selectedFrame.fonts;
  257. options.stylesheets = selectedFrame.stylesheets;
  258. options.images = selectedFrame.images;
  259. options.posters = selectedFrame.posters;
  260. options.videos = selectedFrame.videos;
  261. options.usedFonts = selectedFrame.usedFonts;
  262. options.shadowRoots = selectedFrame.shadowRoots;
  263. options.adoptedStyleSheets = selectedFrame.adoptedStyleSheets;
  264. } else {
  265. options.doc = document;
  266. }
  267. if (!processor.cancelled) {
  268. await processor.run();
  269. }
  270. if (framesSessionId) {
  271. frames.cleanup(framesSessionId);
  272. }
  273. let page;
  274. if (!processor.cancelled) {
  275. if (options.confirmInfobarContent) {
  276. options.infobarContent = ui.prompt("Infobar content", options.infobarContent) || "";
  277. }
  278. page = await processor.getPageData();
  279. if (options.selected || options.optionallySelected) {
  280. ui.unmarkSelection();
  281. }
  282. ui.onEndPage();
  283. if (options.displayStats) {
  284. console.log("SingleFile stats"); // eslint-disable-line no-console
  285. console.table(page.stats); // eslint-disable-line no-console
  286. }
  287. }
  288. return page;
  289. }