downloads.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /*
  2. * Copyright 2010-2019 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, singlefile, Blob, URL, document */
  24. singlefile.extension.core.bg.downloads = (() => {
  25. const partialContents = new Map();
  26. const MIMETYPE_HTML = "text/html";
  27. const STATE_DOWNLOAD_COMPLETE = "complete";
  28. const STATE_DOWNLOAD_INTERRUPTED = "interrupted";
  29. const STATE_ERROR_CANCELED_CHROMIUM = "USER_CANCELED";
  30. const ERROR_DOWNLOAD_CANCELED_GECKO = "canceled";
  31. const ERROR_CONFLICT_ACTION_GECKO = "conflictaction prompt not yet implemented";
  32. const ERROR_INCOGNITO_GECKO = "'incognito'";
  33. const ERROR_INCOGNITO_GECKO_ALT = "\"incognito\"";
  34. const ERROR_INVALID_FILENAME_GECKO = "illegal characters";
  35. const ERROR_INVALID_FILENAME_CHROMIUM = "invalid filename";
  36. return {
  37. onMessage,
  38. download,
  39. downloadPage
  40. };
  41. async function onMessage(message, sender) {
  42. if (message.method.endsWith(".download")) {
  43. let contents;
  44. if (message.truncated) {
  45. contents = partialContents.get(sender.tab.id);
  46. if (!contents) {
  47. contents = [];
  48. partialContents.set(sender.tab.id, contents);
  49. }
  50. contents.push(message.content);
  51. if (message.finished) {
  52. partialContents.delete(sender.tab.id);
  53. }
  54. } else if (message.content) {
  55. contents = [message.content];
  56. }
  57. if (!message.truncated || message.finished) {
  58. if (message.openEditor) {
  59. await singlefile.extension.core.bg.editor.open({ filename: message.filename, content: contents.join("") }, {
  60. backgroundSave: message.backgroundSave,
  61. saveToClipboard: message.saveToClipboard,
  62. confirmFilename: message.confirmFilename,
  63. incognito: sender.tab.incognito,
  64. filenameConflictAction: message.filenameConflictAction,
  65. filenameReplacementCharacter: message.filenameReplacementCharacter,
  66. compressHTML: message.compressHTML
  67. });
  68. } else {
  69. if (message.saveToClipboard) {
  70. message.content = contents.join("");
  71. saveToClipboard(message);
  72. } else {
  73. message.url = URL.createObjectURL(new Blob([contents], { type: MIMETYPE_HTML }));
  74. try {
  75. await downloadPage(message, {
  76. confirmFilename: message.confirmFilename,
  77. incognito: sender.tab.incognito,
  78. filenameConflictAction: message.filenameConflictAction,
  79. filenameReplacementCharacter: message.filenameReplacementCharacter
  80. });
  81. } catch (error) {
  82. console.error(error); // eslint-disable-line no-console
  83. singlefile.extension.ui.bg.main.onError(sender.tab.id);
  84. } finally {
  85. URL.revokeObjectURL(message.url);
  86. }
  87. }
  88. }
  89. }
  90. return {};
  91. }
  92. if (message.method.endsWith(".end")) {
  93. if (message.autoClose) {
  94. singlefile.extension.core.bg.tabs.remove(sender.tab.id);
  95. }
  96. return {};
  97. }
  98. }
  99. async function downloadPage(pageData, options) {
  100. const downloadInfo = {
  101. url: pageData.url,
  102. saveAs: options.confirmFilename,
  103. filename: pageData.filename,
  104. conflictAction: options.filenameConflictAction
  105. };
  106. if (options.incognito) {
  107. downloadInfo.incognito = true;
  108. }
  109. await download(downloadInfo, options.filenameReplacementCharacter);
  110. }
  111. async function download(downloadInfo, replacementCharacter) {
  112. let downloadId;
  113. try {
  114. downloadId = await browser.downloads.download(downloadInfo);
  115. } catch (error) {
  116. if (error.message) {
  117. const errorMessage = error.message.toLowerCase();
  118. const invalidFilename = errorMessage.includes(ERROR_INVALID_FILENAME_GECKO) || errorMessage.includes(ERROR_INVALID_FILENAME_CHROMIUM);
  119. if (invalidFilename && downloadInfo.filename.startsWith(".")) {
  120. downloadInfo.filename = replacementCharacter + downloadInfo.filename;
  121. return download(downloadInfo, replacementCharacter);
  122. } else if (invalidFilename && downloadInfo.filename.includes(",")) {
  123. downloadInfo.filename = downloadInfo.filename.replace(/,/g, replacementCharacter);
  124. return download(downloadInfo, replacementCharacter);
  125. } else if (invalidFilename && !downloadInfo.filename.match(/^[\x00-\x7F]+$/)) { // eslint-disable-line no-control-regex
  126. downloadInfo.filename = downloadInfo.filename.replace(/[^\x00-\x7F]+/g, replacementCharacter); // eslint-disable-line no-control-regex
  127. return download(downloadInfo, replacementCharacter);
  128. } else if ((errorMessage.includes(ERROR_INCOGNITO_GECKO) || errorMessage.includes(ERROR_INCOGNITO_GECKO_ALT)) && downloadInfo.incognito) {
  129. delete downloadInfo.incognito;
  130. return download(downloadInfo, replacementCharacter);
  131. } else if (errorMessage == ERROR_CONFLICT_ACTION_GECKO && downloadInfo.conflictAction) {
  132. delete downloadInfo.conflictAction;
  133. return download(downloadInfo, replacementCharacter);
  134. } else if (errorMessage.includes(ERROR_DOWNLOAD_CANCELED_GECKO)) {
  135. return {};
  136. } else {
  137. throw error;
  138. }
  139. } else {
  140. throw error;
  141. }
  142. }
  143. return new Promise((resolve, reject) => {
  144. browser.downloads.onChanged.addListener(onChanged);
  145. function onChanged(event) {
  146. if (event.id == downloadId && event.state) {
  147. if (event.state.current == STATE_DOWNLOAD_COMPLETE) {
  148. resolve({});
  149. browser.downloads.onChanged.removeListener(onChanged);
  150. }
  151. if (event.state.current == STATE_DOWNLOAD_INTERRUPTED) {
  152. if (event.error && event.error.current == STATE_ERROR_CANCELED_CHROMIUM) {
  153. resolve({});
  154. } else {
  155. reject(new Error(event.state.current));
  156. }
  157. browser.downloads.onChanged.removeListener(onChanged);
  158. }
  159. }
  160. }
  161. });
  162. }
  163. function saveToClipboard(pageData) {
  164. const command = "copy";
  165. document.addEventListener(command, listener);
  166. document.execCommand(command);
  167. document.removeEventListener(command, listener);
  168. function listener(event) {
  169. event.clipboardData.setData(MIMETYPE_HTML, pageData.content);
  170. event.clipboardData.setData("text/plain", pageData.content);
  171. event.preventDefault();
  172. }
  173. }
  174. })();