downloads.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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.saveToClipboard) {
  59. message.content = contents.join("");
  60. saveToClipboard(message);
  61. } else {
  62. message.url = URL.createObjectURL(new Blob([contents], { type: MIMETYPE_HTML }));
  63. try {
  64. await downloadPage(message, {
  65. confirmFilename: message.confirmFilename,
  66. incognito: sender.tab.incognito,
  67. filenameConflictAction: message.filenameConflictAction,
  68. filenameReplacementCharacter: message.filenameReplacementCharacter
  69. });
  70. } catch (error) {
  71. console.error(error); // eslint-disable-line no-console
  72. singlefile.extension.ui.bg.main.onError(sender.tab.id);
  73. } finally {
  74. URL.revokeObjectURL(message.url);
  75. }
  76. }
  77. }
  78. return {};
  79. }
  80. if (message.method.endsWith(".end")) {
  81. const options = await singlefile.extension.core.bg.config.getOptions(sender.tab.url, true);
  82. if (options.autoClose) {
  83. singlefile.extension.core.bg.tabs.remove(sender.tab.id);
  84. }
  85. return {};
  86. }
  87. }
  88. async function downloadPage(pageData, options) {
  89. const downloadInfo = {
  90. url: pageData.url,
  91. saveAs: options.confirmFilename,
  92. filename: pageData.filename,
  93. conflictAction: options.filenameConflictAction
  94. };
  95. if (options.incognito) {
  96. downloadInfo.incognito = true;
  97. }
  98. await download(downloadInfo, options.filenameReplacementCharacter);
  99. }
  100. async function download(downloadInfo, replacementCharacter) {
  101. let downloadId;
  102. try {
  103. downloadId = await browser.downloads.download(downloadInfo);
  104. } catch (error) {
  105. if (error.message) {
  106. const errorMessage = error.message.toLowerCase();
  107. const invalidFilename = errorMessage.includes(ERROR_INVALID_FILENAME_GECKO) || errorMessage.includes(ERROR_INVALID_FILENAME_CHROMIUM);
  108. if (invalidFilename && downloadInfo.filename.startsWith(".")) {
  109. downloadInfo.filename = replacementCharacter + downloadInfo.filename;
  110. return download(downloadInfo, replacementCharacter);
  111. } else if (invalidFilename && downloadInfo.filename.includes(",")) {
  112. downloadInfo.filename = downloadInfo.filename.replace(/,/g, replacementCharacter);
  113. return download(downloadInfo, replacementCharacter);
  114. } else if (invalidFilename && !downloadInfo.filename.match(/^[\x00-\x7F]+$/)) { // eslint-disable-line no-control-regex
  115. downloadInfo.filename = downloadInfo.filename.replace(/[^\x00-\x7F]+/g, replacementCharacter); // eslint-disable-line no-control-regex
  116. return download(downloadInfo, replacementCharacter);
  117. } else if ((errorMessage.includes(ERROR_INCOGNITO_GECKO) || errorMessage.includes(ERROR_INCOGNITO_GECKO_ALT)) && downloadInfo.incognito) {
  118. delete downloadInfo.incognito;
  119. return download(downloadInfo, replacementCharacter);
  120. } else if (errorMessage == ERROR_CONFLICT_ACTION_GECKO && downloadInfo.conflictAction) {
  121. delete downloadInfo.conflictAction;
  122. return download(downloadInfo, replacementCharacter);
  123. } else if (errorMessage.includes(ERROR_DOWNLOAD_CANCELED_GECKO)) {
  124. return {};
  125. } else {
  126. throw error;
  127. }
  128. } else {
  129. throw error;
  130. }
  131. }
  132. return new Promise((resolve, reject) => {
  133. browser.downloads.onChanged.addListener(onChanged);
  134. function onChanged(event) {
  135. if (event.id == downloadId && event.state) {
  136. if (event.state.current == STATE_DOWNLOAD_COMPLETE) {
  137. resolve({});
  138. browser.downloads.onChanged.removeListener(onChanged);
  139. }
  140. if (event.state.current == STATE_DOWNLOAD_INTERRUPTED) {
  141. if (event.error && event.error.current == STATE_ERROR_CANCELED_CHROMIUM) {
  142. resolve({});
  143. } else {
  144. reject(new Error(event.state.current));
  145. }
  146. browser.downloads.onChanged.removeListener(onChanged);
  147. }
  148. }
  149. }
  150. });
  151. }
  152. function saveToClipboard(pageData) {
  153. const command = "copy";
  154. document.addEventListener(command, listener);
  155. document.execCommand(command);
  156. document.removeEventListener(command, listener);
  157. function listener(event) {
  158. event.clipboardData.setData(MIMETYPE_HTML, pageData.content);
  159. event.clipboardData.setData("text/plain", pageData.content);
  160. event.preventDefault();
  161. }
  162. }
  163. })();