download.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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, URL, Blob, MouseEvent, setTimeout, open, navigator, File, setInterval, clearInterval */
  24. import * as yabson from "./../../lib/yabson/yabson.js";
  25. import * as ui from "./../../ui/content/content-ui.js";
  26. import { getSharePageBar, setLabels } from "./../../ui/common/common-content-ui.js";
  27. const MAX_CONTENT_SIZE = 16 * (1024 * 1024);
  28. let EMBEDDED_IMAGE_BUTTON_MESSAGE, SHARE_PAGE_BUTTON_MESSAGE, SHARE_SELECTION_BUTTON_MESSAGE, ERROR_TITLE_MESSAGE;
  29. try {
  30. EMBEDDED_IMAGE_BUTTON_MESSAGE = browser.i18n.getMessage("topPanelEmbeddedImageButton");
  31. SHARE_PAGE_BUTTON_MESSAGE = browser.i18n.getMessage("topPanelSharePageButton");
  32. SHARE_SELECTION_BUTTON_MESSAGE = browser.i18n.getMessage("topPanelShareSelectionButton");
  33. ERROR_TITLE_MESSAGE = browser.i18n.getMessage("topPanelError");
  34. } catch (error) {
  35. // ignored
  36. }
  37. let sharePageBar;
  38. setLabels({
  39. EMBEDDED_IMAGE_BUTTON_MESSAGE,
  40. SHARE_PAGE_BUTTON_MESSAGE,
  41. SHARE_SELECTION_BUTTON_MESSAGE,
  42. ERROR_TITLE_MESSAGE
  43. });
  44. export {
  45. downloadPage,
  46. downloadPageForeground
  47. };
  48. async function downloadPage(pageData, options) {
  49. if (options.includeBOM) {
  50. pageData.content = "\ufeff" + pageData.content;
  51. }
  52. const embeddedImage = options.embeddedImage;
  53. const message = {
  54. method: "downloads.download",
  55. taskId: options.taskId,
  56. insertTextBody: options.insertTextBody,
  57. confirmFilename: options.confirmFilename,
  58. filenameConflictAction: options.filenameConflictAction,
  59. filename: pageData.filename,
  60. mimeType: pageData.mimeType,
  61. saveToClipboard: options.saveToClipboard,
  62. saveToGDrive: options.saveToGDrive,
  63. saveToDropbox: options.saveToDropbox,
  64. saveWithWebDAV: options.saveWithWebDAV,
  65. webDAVURL: options.webDAVURL,
  66. webDAVUser: options.webDAVUser,
  67. webDAVPassword: options.webDAVPassword,
  68. saveToGitHub: options.saveToGitHub,
  69. githubToken: options.githubToken,
  70. githubUser: options.githubUser,
  71. githubRepository: options.githubRepository,
  72. githubBranch: options.githubBranch,
  73. saveWithCompanion: options.saveWithCompanion,
  74. forceWebAuthFlow: options.forceWebAuthFlow,
  75. filenameReplacementCharacter: options.filenameReplacementCharacter,
  76. openEditor: options.openEditor,
  77. openSavedPage: options.openSavedPage,
  78. compressHTML: options.compressHTML,
  79. backgroundSave: options.backgroundSave,
  80. bookmarkId: options.bookmarkId,
  81. replaceBookmarkURL: options.replaceBookmarkURL,
  82. applySystemTheme: options.applySystemTheme,
  83. defaultEditorMode: options.defaultEditorMode,
  84. includeInfobar: options.includeInfobar,
  85. warnUnsavedPage: options.warnUnsavedPage,
  86. createRootDirectory: options.createRootDirectory,
  87. selfExtractingArchive: options.selfExtractingArchive,
  88. embeddedImage: embeddedImage ? Array.from(embeddedImage) : null,
  89. preventAppendedData: options.preventAppendedData,
  90. extractDataFromPage: options.extractDataFromPage,
  91. insertCanonicalLink: options.insertCanonicalLink,
  92. insertMetaNoIndex: options.insertMetaNoIndex,
  93. insertMetaCSP: options.insertMetaCSP,
  94. password: options.password,
  95. compressContent: options.compressContent,
  96. foregroundSave: options.foregroundSave,
  97. sharePage: options.sharePage,
  98. saveToRestFormApi: options.saveToRestFormApi,
  99. saveToRestFormApiUrl: options.saveToRestFormApiUrl,
  100. saveToRestFormApiFileFieldName: options.saveToRestFormApiFileFieldName,
  101. saveToRestFormApiUrlFieldName: options.saveToRestFormApiUrlFieldName,
  102. saveToRestFormApiToken: options.saveToRestFormApiToken
  103. };
  104. const pingInterval = setInterval(() => {
  105. browser.runtime.sendMessage({ method: "ping" }).then(() => { });
  106. }, 15000);
  107. if (options.compressContent) {
  108. const blob = new Blob([await yabson.serialize(pageData)], { type: pageData.mimeType });
  109. const blobURL = URL.createObjectURL(blob);
  110. message.blobURL = blobURL;
  111. const result = await browser.runtime.sendMessage(message);
  112. URL.revokeObjectURL(blobURL);
  113. if (result.error) {
  114. message.embeddedImage = embeddedImage;
  115. message.blobURL = null;
  116. message.pageData = pageData;
  117. const serializer = yabson.getSerializer(message);
  118. for await (const chunk of serializer) {
  119. await browser.runtime.sendMessage({
  120. method: "downloads.download",
  121. compressContent: true,
  122. data: Array.from(chunk)
  123. });
  124. }
  125. await browser.runtime.sendMessage({
  126. method: "downloads.download",
  127. compressContent: true,
  128. mimeType: pageData.mimeType
  129. });
  130. }
  131. if (options.backgroundSave) {
  132. await browser.runtime.sendMessage({ method: "downloads.end", taskId: options.taskId });
  133. }
  134. } else {
  135. if ((options.backgroundSave && !options.sharePage) || options.openEditor || options.saveToGDrive || options.saveToGitHub || options.saveWithCompanion || options.saveWithWebDAV || options.saveToDropbox || options.saveToRestFormApi) {
  136. let filename = pageData.filename;
  137. if ((options.saveToGDrive || options.saveToGitHub || options.saveWithCompanion || options.saveWithWebDAV || options.saveToDropbox || options.saveToRestFormApi) && options.confirmFilename && !options.openEditor) {
  138. filename = ui.prompt("Save as", pageData.filename);
  139. }
  140. if (filename) {
  141. message.filename = pageData.filename = filename;
  142. const blobURL = URL.createObjectURL(new Blob([pageData.content], { type: pageData.mimeType }));
  143. message.blobURL = blobURL;
  144. const result = await browser.runtime.sendMessage(message);
  145. URL.revokeObjectURL(blobURL);
  146. if (result.error) {
  147. message.blobURL = null;
  148. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < pageData.content.length; blockIndex++) {
  149. message.truncated = pageData.content.length > MAX_CONTENT_SIZE;
  150. if (message.truncated) {
  151. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > pageData.content.length;
  152. message.content = pageData.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  153. } else {
  154. message.content = pageData.content;
  155. }
  156. await browser.runtime.sendMessage(message);
  157. }
  158. }
  159. } else {
  160. browser.runtime.sendMessage({ method: "downloads.cancel" });
  161. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  162. }
  163. } else {
  164. if (options.saveToClipboard) {
  165. saveToClipboard(pageData);
  166. } else {
  167. await downloadPageForeground(pageData, options);
  168. }
  169. if (options.openSavedPage) {
  170. open(URL.createObjectURL(new Blob([pageData.content], { type: pageData.mimeType })));
  171. }
  172. browser.runtime.sendMessage({ method: "ui.processEnd" });
  173. }
  174. await browser.runtime.sendMessage({ method: "downloads.end", taskId: options.taskId, hash: pageData.hash, woleetKey: options.woleetKey });
  175. }
  176. clearInterval(pingInterval);
  177. }
  178. async function downloadPageForeground(pageData, options) {
  179. if (Array.isArray(pageData.content)) {
  180. pageData.content = new Uint8Array(pageData.content);
  181. }
  182. if (options.sharePage && navigator.share) {
  183. await sharePage(pageData, options);
  184. } else {
  185. let filename = pageData.filename;
  186. if (options.confirmFilename) {
  187. filename = ui.prompt("Save as", pageData.filename);
  188. if (filename) {
  189. pageData.filename = filename;
  190. } else {
  191. browser.runtime.sendMessage({ method: "downloads.cancel" });
  192. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  193. }
  194. }
  195. if (filename) {
  196. const link = document.createElement("a");
  197. link.download = pageData.filename;
  198. link.href = URL.createObjectURL(new Blob([pageData.content], { type: pageData.mimeType }));
  199. link.dispatchEvent(new MouseEvent("click"));
  200. return new Promise(resolve => setTimeout(() => { URL.revokeObjectURL(link.href); resolve(); }, 1000));
  201. }
  202. }
  203. }
  204. async function sharePage(pageData, options) {
  205. sharePageBar = getSharePageBar();
  206. const cancelled = await sharePageBar.display(options.selected);
  207. if (!cancelled) {
  208. const data = { files: [new File([pageData.content], pageData.filename, { type: pageData.mimeType })] };
  209. try {
  210. await navigator.share(data);
  211. sharePageBar.hide();
  212. } catch (error) {
  213. sharePageBar.hide();
  214. if (error.name === "AbortError") {
  215. await sharePage(pageData, options);
  216. } else {
  217. throw error;
  218. }
  219. }
  220. }
  221. }
  222. function saveToClipboard(pageData) {
  223. const command = "copy";
  224. document.addEventListener(command, listener);
  225. document.execCommand(command);
  226. document.removeEventListener(command, listener);
  227. function listener(event) {
  228. event.clipboardData.setData(pageData.mimeType, pageData.content);
  229. event.clipboardData.setData("text/plain", pageData.content);
  230. event.preventDefault();
  231. }
  232. }