downloads.js 6.1 KB

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