downloads.js 10 KB

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