downloads.js 9.5 KB

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