downloads.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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, GDrive */
  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. const CLIENT_ID = "207618107333-bktohpfmdfnv5hfavi1ll18h74gqi27v.apps.googleusercontent.com";
  37. const SCOPES = ["https://www.googleapis.com/auth/drive.file"];
  38. const manifest = browser.runtime.getManifest();
  39. const gDrive = new GDrive(CLIENT_ID, SCOPES);
  40. return {
  41. onMessage,
  42. download,
  43. downloadPage
  44. };
  45. async function onMessage(message, sender) {
  46. if (message.method.endsWith(".download")) {
  47. let contents;
  48. if (message.truncated) {
  49. contents = partialContents.get(sender.tab.id);
  50. if (!contents) {
  51. contents = [];
  52. partialContents.set(sender.tab.id, contents);
  53. }
  54. contents.push(message.content);
  55. if (message.finished) {
  56. partialContents.delete(sender.tab.id);
  57. }
  58. } else if (message.content) {
  59. contents = [message.content];
  60. }
  61. if (!message.truncated || message.finished) {
  62. if (message.openEditor) {
  63. singlefile.extension.ui.bg.main.onEdit(sender.tab.id);
  64. await singlefile.extension.core.bg.editor.open({ filename: message.filename, content: contents.join("") }, {
  65. backgroundSave: message.backgroundSave,
  66. saveToClipboard: message.saveToClipboard,
  67. saveToGDrive: message.saveToGDrive,
  68. confirmFilename: message.confirmFilename,
  69. incognito: sender.tab.incognito,
  70. filenameConflictAction: message.filenameConflictAction,
  71. filenameReplacementCharacter: message.filenameReplacementCharacter,
  72. compressHTML: message.compressHTML
  73. });
  74. } else {
  75. if (message.saveToClipboard) {
  76. message.content = contents.join("");
  77. saveToClipboard(message);
  78. } else {
  79. const blob = new Blob([contents], { type: MIMETYPE_HTML });
  80. try {
  81. if (message.saveToGDrive) {
  82. await uploadPage(message.filename, blob, sender.tab.id);
  83. } else {
  84. message.url = URL.createObjectURL(blob);
  85. await downloadPage(message, {
  86. confirmFilename: message.confirmFilename,
  87. incognito: sender.tab.incognito,
  88. filenameConflictAction: message.filenameConflictAction,
  89. filenameReplacementCharacter: message.filenameReplacementCharacter
  90. });
  91. }
  92. singlefile.extension.ui.bg.main.onEnd(sender.tab.id);
  93. } catch (error) {
  94. console.error(error); // eslint-disable-line no-console
  95. singlefile.extension.ui.bg.main.onError(sender.tab.id);
  96. } finally {
  97. if (message.url) {
  98. URL.revokeObjectURL(message.url);
  99. }
  100. }
  101. }
  102. }
  103. }
  104. return {};
  105. }
  106. if (message.method.endsWith(".enableGDrive")) {
  107. if (!manifest.permissions || !manifest.permissions.includes("identity")) {
  108. await browser.permissions.request({ permissions: ["identity"] });
  109. }
  110. return {};
  111. }
  112. if (message.method.endsWith(".disableGDrive")) {
  113. const authInfo = await singlefile.extension.core.bg.config.getAuthInfo();
  114. await gDrive.revokeAuthToken(authInfo.accessToken);
  115. singlefile.extension.core.bg.config.setAuthInfo({});
  116. return {};
  117. }
  118. if (message.method.endsWith(".end")) {
  119. if (message.autoClose) {
  120. singlefile.extension.core.bg.tabs.remove(sender.tab.id);
  121. }
  122. return {};
  123. }
  124. }
  125. async function getAuthInfo(force) {
  126. let code, cancelled, authInfo = await singlefile.extension.core.bg.config.getAuthInfo();
  127. gDrive.setAuthInfo(authInfo);
  128. const options = { interactive: true, auto: true };
  129. if (!authInfo || force || gDrive.managedToken()) {
  130. try {
  131. if (!gDrive.managedToken()) {
  132. singlefile.extension.core.bg.tabs.getAuthCode(gDrive.getAuthURL(options))
  133. .then(authCode => code = authCode)
  134. .catch(() => { cancelled = true; });
  135. }
  136. authInfo = await gDrive.auth(options);
  137. } catch (error) {
  138. if (!cancelled && error.message == "code_required" && !code) {
  139. code = await singlefile.extension.core.bg.tabs.promptValue("Please enter the access code for Google Drive");
  140. }
  141. if (code) {
  142. options.code = code;
  143. authInfo = await gDrive.auth(options);
  144. } else {
  145. throw error;
  146. }
  147. }
  148. await singlefile.extension.core.bg.config.setAuthInfo(authInfo);
  149. }
  150. return authInfo;
  151. }
  152. async function uploadPage(filename, blob, tabId) {
  153. try {
  154. await getAuthInfo();
  155. await gDrive.upload(filename, blob);
  156. }
  157. catch (error) {
  158. if (error.message == "invalid_token") {
  159. let authInfo;
  160. try {
  161. authInfo = await gDrive.refreshAuthToken();
  162. } catch (error) {
  163. if (error.message == "unknown_token") {
  164. authInfo = await getAuthInfo(true);
  165. } else {
  166. throw error;
  167. }
  168. }
  169. await singlefile.extension.core.bg.config.setAuthInfo(authInfo);
  170. await uploadPage(filename, blob, tabId);
  171. } else {
  172. throw error;
  173. }
  174. }
  175. }
  176. async function downloadPage(pageData, options) {
  177. const downloadInfo = {
  178. url: pageData.url,
  179. saveAs: options.confirmFilename,
  180. filename: pageData.filename,
  181. conflictAction: options.filenameConflictAction
  182. };
  183. if (options.incognito) {
  184. downloadInfo.incognito = true;
  185. }
  186. await download(downloadInfo, options.filenameReplacementCharacter);
  187. }
  188. async function download(downloadInfo, replacementCharacter) {
  189. let downloadId;
  190. try {
  191. downloadId = await browser.downloads.download(downloadInfo);
  192. } catch (error) {
  193. if (error.message) {
  194. const errorMessage = error.message.toLowerCase();
  195. const invalidFilename = errorMessage.includes(ERROR_INVALID_FILENAME_GECKO) || errorMessage.includes(ERROR_INVALID_FILENAME_CHROMIUM);
  196. if (invalidFilename && downloadInfo.filename.startsWith(".")) {
  197. downloadInfo.filename = replacementCharacter + downloadInfo.filename;
  198. return download(downloadInfo, replacementCharacter);
  199. } else if (invalidFilename && downloadInfo.filename.includes(",")) {
  200. downloadInfo.filename = downloadInfo.filename.replace(/,/g, replacementCharacter);
  201. return download(downloadInfo, replacementCharacter);
  202. } else if (invalidFilename && !downloadInfo.filename.match(/^[\x00-\x7F]+$/)) { // eslint-disable-line no-control-regex
  203. downloadInfo.filename = downloadInfo.filename.replace(/[^\x00-\x7F]+/g, replacementCharacter); // eslint-disable-line no-control-regex
  204. return download(downloadInfo, replacementCharacter);
  205. } else if ((errorMessage.includes(ERROR_INCOGNITO_GECKO) || errorMessage.includes(ERROR_INCOGNITO_GECKO_ALT)) && downloadInfo.incognito) {
  206. delete downloadInfo.incognito;
  207. return download(downloadInfo, replacementCharacter);
  208. } else if (errorMessage == ERROR_CONFLICT_ACTION_GECKO && downloadInfo.conflictAction) {
  209. delete downloadInfo.conflictAction;
  210. return download(downloadInfo, replacementCharacter);
  211. } else if (errorMessage.includes(ERROR_DOWNLOAD_CANCELED_GECKO)) {
  212. return {};
  213. } else {
  214. throw error;
  215. }
  216. } else {
  217. throw error;
  218. }
  219. }
  220. return new Promise((resolve, reject) => {
  221. browser.downloads.onChanged.addListener(onChanged);
  222. function onChanged(event) {
  223. if (event.id == downloadId && event.state) {
  224. if (event.state.current == STATE_DOWNLOAD_COMPLETE) {
  225. resolve({});
  226. browser.downloads.onChanged.removeListener(onChanged);
  227. }
  228. if (event.state.current == STATE_DOWNLOAD_INTERRUPTED) {
  229. if (event.error && event.error.current == STATE_ERROR_CANCELED_CHROMIUM) {
  230. resolve({});
  231. } else {
  232. reject(new Error(event.state.current));
  233. }
  234. browser.downloads.onChanged.removeListener(onChanged);
  235. }
  236. }
  237. }
  238. });
  239. }
  240. function saveToClipboard(pageData) {
  241. const command = "copy";
  242. document.addEventListener(command, listener);
  243. document.execCommand(command);
  244. document.removeEventListener(command, listener);
  245. function listener(event) {
  246. event.clipboardData.setData(MIMETYPE_HTML, pageData.content);
  247. event.clipboardData.setData("text/plain", pageData.content);
  248. event.preventDefault();
  249. }
  250. }
  251. })();