core.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global browser, SingleFile, singlefile, Blob */
  21. singlefile.core = (() => {
  22. const FORBIDDEN_URLS = ["https://chrome.google.com", "https://addons.mozilla.org"];
  23. const contentScriptFiles = [
  24. "/lib/browser-polyfill/custom-browser-polyfill.js",
  25. "/lib/single-file/doc-helper.js",
  26. "/lib/single-file/base64.js",
  27. "/lib/single-file/parse-srcset.js",
  28. "/lib/fetch/content/fetch.js",
  29. "/lib/single-file/single-file-core.js",
  30. "/lib/single-file/single-file-browser.js",
  31. "/extension/index.js",
  32. "/extension/ui/content/content-ui.js",
  33. "/extension/core/content/content.js"
  34. ];
  35. const frameScriptFiles = [
  36. "/lib/browser-polyfill/custom-browser-polyfill.js",
  37. "/extension/index.js",
  38. "/lib/single-file/doc-helper.js",
  39. "/lib/single-file/timeout.js",
  40. "/lib/single-file/frame-tree.js",
  41. "/extension/core/content/content-frame.js"
  42. ];
  43. const optionalContentScriptFiles = {
  44. compressHTML: [
  45. "/lib/single-file/htmlmini.js",
  46. "/lib/single-file/serializer.js"
  47. ],
  48. compressCSS: [
  49. "/lib/single-file/uglifycss.js"
  50. ],
  51. removeAlternativeFonts: [
  52. "/lib/single-file/fonts-minifier.js"
  53. ],
  54. removeUnusedStyles: [
  55. "/lib/single-file/css-what.js",
  56. "/lib/single-file/parse-css.js",
  57. "/lib/single-file/rules-matcher.js",
  58. "/lib/single-file/css-minifier.js"
  59. ],
  60. lazyLoadImages: [
  61. "/lib/single-file/lazy-loader.js",
  62. ]
  63. };
  64. browser.runtime.onMessage.addListener((request, sender) => {
  65. if (request.getConfig) {
  66. return singlefile.config.get();
  67. }
  68. if (request.download) {
  69. try {
  70. if (request.content) {
  71. request.url = URL.createObjectURL(new Blob([request.content], { type: "text/html" }));
  72. }
  73. return downloadPage(request, { confirmFilename: request.confirmFilename, incognito: sender.tab.incognito })
  74. .catch(error => {
  75. if (error.message && error.message.includes("'incognito'")) {
  76. return downloadPage(request, { confirmFilename: request.confirmFilename });
  77. } else {
  78. return { notSupported: true };
  79. }
  80. });
  81. } catch (error) {
  82. return Promise.resolve({ notSupported: true });
  83. }
  84. }
  85. if (request.processContent) {
  86. processBackgroundTab(sender.tab, request);
  87. }
  88. });
  89. browser.tabs.onRemoved.addListener(async tabId => {
  90. const tabsData = await singlefile.storage.get();
  91. delete tabsData[tabId];
  92. await singlefile.storage.set(tabsData);
  93. });
  94. return { saveTab, autoSaveTab, isAllowedURL };
  95. async function saveTab(tab, processOptions) {
  96. const options = await singlefile.config.get();
  97. Object.keys(processOptions).forEach(key => options[key] = processOptions[key]);
  98. return new Promise(async (resolve, reject) => {
  99. const processPromise = saveStart(tab, options);
  100. try {
  101. await processPromise;
  102. } catch (error) {
  103. reject(error);
  104. }
  105. resolve();
  106. });
  107. }
  108. async function autoSaveTab(tab) {
  109. const options = await singlefile.config.get();
  110. return new Promise(async (resolve, reject) => {
  111. const processPromise = autoSaveStart(tab, options);
  112. try {
  113. await processPromise;
  114. } catch (error) {
  115. reject(error);
  116. }
  117. resolve();
  118. });
  119. }
  120. function isAllowedURL(url) {
  121. return url && (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("file://")) && !FORBIDDEN_URLS.find(storeUrl => url.startsWith(storeUrl));
  122. }
  123. async function processBackgroundTab(tab, message) {
  124. const options = await singlefile.config.get();
  125. options.content = message.content;
  126. options.url = message.url;
  127. options.framesData = message.framesData;
  128. options.canvasData = message.canvasData;
  129. options.stylesheetContents = message.stylesheetContents;
  130. options.imageData = message.imageData;
  131. options.insertSingleFileComment = true;
  132. options.insertFaviconLink = true;
  133. options.backgroundTab = true;
  134. options.autoSave = true;
  135. options.incognito = tab.incognito;
  136. let index = 0, maxIndex = 0;
  137. options.onprogress = async event => {
  138. if (event.type == event.RESOURCES_INITIALIZED) {
  139. maxIndex = event.details.max;
  140. }
  141. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  142. index++;
  143. singlefile.ui.button.onProgress(tab.id, index, maxIndex, { autoSave: true });
  144. } else if (event.type == event.PAGE_ENDED) {
  145. singlefile.ui.button.onEnd(tab.id, { autoSave: true });
  146. }
  147. };
  148. const processor = new (SingleFile.getClass())(options);
  149. await processor.initialize();
  150. await processor.preparePageData();
  151. const page = processor.getPageData();
  152. const date = new Date();
  153. page.filename = page.title + (options.appendSaveDate ? " (" + date.toISOString().split("T")[0] + " " + date.toLocaleTimeString() + ")" : "") + ".html";
  154. page.url = URL.createObjectURL(new Blob([page.content], { type: "text/html" }));
  155. return downloadPage(page, options);
  156. }
  157. async function downloadPage(page, options) {
  158. const downloadInfo = {
  159. url: page.url,
  160. saveAs: options.confirmFilename,
  161. filename: page.filename.replace(/[/\\?%*:|"<>\x7F]+/g, "_")
  162. };
  163. if (options.incognito) {
  164. downloadInfo.incognito = true;
  165. }
  166. const downloadId = await browser.downloads.download(downloadInfo);
  167. return new Promise((resolve, reject) => {
  168. browser.downloads.onChanged.addListener(onChanged);
  169. function onChanged(event) {
  170. if (event.id == downloadId && event.state) {
  171. if (event.state.current == "complete") {
  172. URL.revokeObjectURL(page.url);
  173. resolve({});
  174. browser.downloads.onChanged.removeListener(onChanged);
  175. }
  176. if (event.state.current == "interrupted") {
  177. URL.revokeObjectURL(page.url);
  178. reject(new Error(event.state.current));
  179. browser.downloads.onChanged.removeListener(onChanged);
  180. }
  181. }
  182. }
  183. });
  184. }
  185. async function saveStart(tab, options) {
  186. if (!options.removeFrames) {
  187. await executeScripts(tab.id, frameScriptFiles, true);
  188. }
  189. await executeScripts(tab.id, getContentScriptFiles(options), false);
  190. if (options.frameId) {
  191. await browser.tabs.sendMessage(tab.id, { saveFrame: true, options }, { frameId: options.frameId });
  192. } else {
  193. await browser.tabs.sendMessage(tab.id, { savePage: true, options });
  194. }
  195. }
  196. async function autoSaveStart(tab, options) {
  197. await browser.tabs.sendMessage(tab.id, { autoSavePage: true, options });
  198. }
  199. async function executeScripts(tabId, scriptFiles, allFrames) {
  200. return Promise.all(scriptFiles.map(file => browser.tabs.executeScript(tabId, { file, allFrames })));
  201. }
  202. function getContentScriptFiles(options) {
  203. let files = contentScriptFiles;
  204. Object.keys(optionalContentScriptFiles).forEach(option => {
  205. if (options[option]) {
  206. files = optionalContentScriptFiles[option].concat(files);
  207. }
  208. });
  209. return files;
  210. }
  211. })();