downloads.js 5.8 KB

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