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