downloads.js 5.7 KB

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