downloads.js 9.6 KB

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