downloads.js 9.8 KB

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