downloads.js 10 KB

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