downloads.js 10 KB

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