downloads.js 9.5 KB

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