downloads.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. * Copyright 2010-2020 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 CONFLICT_ACTION_SKIP = "skip";
  39. const CONFLICT_ACTION_UNIQUIFY = "uniquify";
  40. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  41. const manifest = browser.runtime.getManifest();
  42. const requestPermissionIdentity = manifest.optional_permissions && manifest.optional_permissions.includes("identity");
  43. const gDrive = new GDrive(CLIENT_ID, SCOPES);
  44. return {
  45. onMessage,
  46. download,
  47. downloadPage,
  48. uploadPage
  49. };
  50. async function onMessage(message, sender) {
  51. if (message.method.endsWith(".download")) {
  52. return downloadTabPage(message, sender.tab);
  53. }
  54. if (message.method.endsWith(".disableGDrive")) {
  55. const authInfo = await singlefile.extension.core.bg.config.getAuthInfo();
  56. singlefile.extension.core.bg.config.removeAuthInfo();
  57. await gDrive.revokeAuthToken(authInfo && (authInfo.accessToken || authInfo.revokableAccessToken));
  58. return {};
  59. }
  60. if (message.method.endsWith(".end")) {
  61. if (message.hash) {
  62. await woleet.anchor(message.hash);
  63. }
  64. singlefile.extension.core.bg.business.onSaveEnd(message.taskId);
  65. return {};
  66. }
  67. if (message.method.endsWith(".getInfo")) {
  68. return singlefile.extension.core.bg.business.getTasksInfo();
  69. }
  70. if (message.method.endsWith(".cancel")) {
  71. singlefile.extension.core.bg.business.cancelTask(message.taskId);
  72. return {};
  73. }
  74. if (message.method.endsWith(".cancelAll")) {
  75. singlefile.extension.core.bg.business.cancelAllTasks();
  76. return {};
  77. }
  78. if (message.method.endsWith(".saveUrls")) {
  79. singlefile.extension.core.bg.business.saveUrls(message.urls);
  80. return {};
  81. }
  82. }
  83. async function downloadTabPage(message, tab) {
  84. let contents;
  85. if (message.truncated) {
  86. contents = partialContents.get(tab.id);
  87. if (!contents) {
  88. contents = [];
  89. partialContents.set(tab.id, contents);
  90. }
  91. contents.push(message.content);
  92. if (message.finished) {
  93. partialContents.delete(tab.id);
  94. }
  95. } else if (message.content) {
  96. contents = [message.content];
  97. }
  98. if (!message.truncated || message.finished) {
  99. if (message.openEditor) {
  100. singlefile.extension.ui.bg.main.onEdit(tab.id);
  101. await singlefile.extension.core.bg.editor.open({ tabIndex: tab.index + 1, filename: message.filename, content: contents.join("") }, {
  102. backgroundSave: message.backgroundSave,
  103. saveToClipboard: message.saveToClipboard,
  104. saveToGDrive: message.saveToGDrive,
  105. confirmFilename: message.confirmFilename,
  106. incognito: tab.incognito,
  107. filenameConflictAction: message.filenameConflictAction,
  108. filenameReplacementCharacter: message.filenameReplacementCharacter,
  109. compressHTML: message.compressHTML,
  110. bookmarkId: message.bookmarkId,
  111. replaceBookmarkURL: message.replaceBookmarkURL,
  112. applySystemTheme: message.applySystemTheme,
  113. defaultEditorMode: message.defaultEditorMode,
  114. includeInfobar: message.includeInfobar,
  115. warnUnsavedPage: message.warnUnsavedPage
  116. });
  117. } else {
  118. if (message.saveToClipboard) {
  119. message.content = contents.join("");
  120. saveToClipboard(message);
  121. singlefile.extension.ui.bg.main.onEnd(tab.id);
  122. } else {
  123. await downloadBlob(new Blob([contents], { type: MIMETYPE_HTML }), tab.id, tab.incognito, message);
  124. }
  125. }
  126. }
  127. return {};
  128. }
  129. async function downloadBlob(blob, tabId, incognito, message) {
  130. try {
  131. if (message.saveToGDrive) {
  132. await uploadPage(message.taskId, message.filename, blob, {
  133. forceWebAuthFlow: message.forceWebAuthFlow,
  134. extractAuthCode: message.extractAuthCode
  135. }, {
  136. onProgress: (offset, size) => singlefile.extension.ui.bg.main.onUploadProgress(tabId, offset, size)
  137. });
  138. } else {
  139. message.url = URL.createObjectURL(blob);
  140. await downloadPage(message, {
  141. confirmFilename: message.confirmFilename,
  142. incognito,
  143. filenameConflictAction: message.filenameConflictAction,
  144. filenameReplacementCharacter: message.filenameReplacementCharacter,
  145. includeInfobar: message.includeInfobar
  146. });
  147. }
  148. singlefile.extension.ui.bg.main.onEnd(tabId);
  149. } catch (error) {
  150. if (!error.message || error.message != "upload_cancelled") {
  151. console.error(error); // eslint-disable-line no-console
  152. singlefile.extension.ui.bg.main.onError(tabId);
  153. }
  154. } finally {
  155. if (message.url) {
  156. URL.revokeObjectURL(message.url);
  157. }
  158. }
  159. }
  160. function getRegExp(string) {
  161. return string.replace(REGEXP_ESCAPE, "\\$1");
  162. }
  163. async function getAuthInfo(authOptions, force) {
  164. let authInfo = await singlefile.extension.core.bg.config.getAuthInfo();
  165. const options = {
  166. interactive: true,
  167. auto: authOptions.extractAuthCode,
  168. forceWebAuthFlow: authOptions.forceWebAuthFlow,
  169. requestPermissionIdentity,
  170. launchWebAuthFlow: options => singlefile.extension.core.bg.tabs.launchWebAuthFlow(options),
  171. extractAuthCode: authURL => singlefile.extension.core.bg.tabs.extractAuthCode(authURL),
  172. promptAuthCode: () => singlefile.extension.core.bg.tabs.promptValue("Please enter the access code for Google Drive")
  173. };
  174. gDrive.setAuthInfo(authInfo, options);
  175. if (!authInfo || !authInfo.accessToken || force) {
  176. authInfo = await gDrive.auth(options);
  177. if (authInfo) {
  178. await singlefile.extension.core.bg.config.setAuthInfo(authInfo);
  179. } else {
  180. await singlefile.extension.core.bg.config.removeAuthInfo();
  181. }
  182. }
  183. return authInfo;
  184. }
  185. async function uploadPage(taskId, filename, blob, authOptions, uploadOptions) {
  186. try {
  187. await getAuthInfo(authOptions);
  188. const taskInfo = singlefile.extension.core.bg.business.getTaskInfo(taskId);
  189. if (taskInfo && !taskInfo.cancelled) {
  190. const uploadInfo = await gDrive.upload(filename, blob, uploadOptions);
  191. singlefile.extension.core.bg.business.setCancelCallback(taskId, uploadInfo.cancelUpload);
  192. return await uploadInfo.uploadPromise;
  193. }
  194. }
  195. catch (error) {
  196. if (error.message == "invalid_token") {
  197. let authInfo;
  198. try {
  199. authInfo = await gDrive.refreshAuthToken();
  200. } catch (error) {
  201. if (error.message == "unknown_token") {
  202. authInfo = await getAuthInfo(authOptions, true);
  203. } else {
  204. throw error;
  205. }
  206. }
  207. if (authInfo) {
  208. await singlefile.extension.core.bg.config.setAuthInfo(authInfo);
  209. } else {
  210. await singlefile.extension.core.bg.config.removeAuthInfo();
  211. }
  212. await uploadPage(taskId, filename, blob, authOptions, uploadOptions);
  213. } else {
  214. throw error;
  215. }
  216. }
  217. }
  218. async function downloadPage(pageData, options) {
  219. const filenameConflictAction = options.filenameConflictAction;
  220. let skipped;
  221. if (filenameConflictAction == CONFLICT_ACTION_SKIP) {
  222. const downloadItems = await browser.downloads.search({
  223. filenameRegex: "(\\\\|/)" + getRegExp(pageData.filename) + "$",
  224. exists: true
  225. });
  226. if (downloadItems.length) {
  227. skipped = true;
  228. } else {
  229. options.filenameConflictAction = CONFLICT_ACTION_UNIQUIFY;
  230. }
  231. }
  232. if (!skipped) {
  233. const downloadInfo = {
  234. url: pageData.url,
  235. saveAs: options.confirmFilename,
  236. filename: pageData.filename,
  237. conflictAction: options.filenameConflictAction
  238. };
  239. if (options.incognito) {
  240. downloadInfo.incognito = true;
  241. }
  242. const downloadData = await download(downloadInfo, options.filenameReplacementCharacter);
  243. if (downloadData.filename && pageData.bookmarkId && pageData.replaceBookmarkURL) {
  244. if (!downloadData.filename.startsWith("file:")) {
  245. if (downloadData.filename.startsWith("/")) {
  246. downloadData.filename = downloadData.filename.substring(1);
  247. }
  248. downloadData.filename = "file:///" + downloadData.filename;
  249. }
  250. await singlefile.extension.core.bg.bookmarks.update(pageData.bookmarkId, { url: downloadData.filename });
  251. }
  252. }
  253. }
  254. async function download(downloadInfo, replacementCharacter) {
  255. let downloadId;
  256. try {
  257. downloadId = await browser.downloads.download(downloadInfo);
  258. } catch (error) {
  259. if (error.message) {
  260. const errorMessage = error.message.toLowerCase();
  261. const invalidFilename = errorMessage.includes(ERROR_INVALID_FILENAME_GECKO) || errorMessage.includes(ERROR_INVALID_FILENAME_CHROMIUM);
  262. if (invalidFilename && downloadInfo.filename.startsWith(".")) {
  263. downloadInfo.filename = replacementCharacter + downloadInfo.filename;
  264. return download(downloadInfo, replacementCharacter);
  265. } else if (invalidFilename && downloadInfo.filename.includes(",")) {
  266. downloadInfo.filename = downloadInfo.filename.replace(/,/g, replacementCharacter);
  267. return download(downloadInfo, replacementCharacter);
  268. } else if (invalidFilename && !downloadInfo.filename.match(/^[\x00-\x7F]+$/)) { // eslint-disable-line no-control-regex
  269. downloadInfo.filename = downloadInfo.filename.replace(/[^\x00-\x7F]+/g, replacementCharacter); // eslint-disable-line no-control-regex
  270. return download(downloadInfo, replacementCharacter);
  271. } else if ((errorMessage.includes(ERROR_INCOGNITO_GECKO) || errorMessage.includes(ERROR_INCOGNITO_GECKO_ALT)) && downloadInfo.incognito) {
  272. delete downloadInfo.incognito;
  273. return download(downloadInfo, replacementCharacter);
  274. } else if (errorMessage == ERROR_CONFLICT_ACTION_GECKO && downloadInfo.conflictAction) {
  275. delete downloadInfo.conflictAction;
  276. return download(downloadInfo, replacementCharacter);
  277. } else if (errorMessage.includes(ERROR_DOWNLOAD_CANCELED_GECKO)) {
  278. return {};
  279. } else {
  280. throw error;
  281. }
  282. } else {
  283. throw error;
  284. }
  285. }
  286. return new Promise((resolve, reject) => {
  287. browser.downloads.onChanged.addListener(onChanged);
  288. function onChanged(event) {
  289. if (event.id == downloadId && event.state) {
  290. if (event.state.current == STATE_DOWNLOAD_COMPLETE) {
  291. browser.downloads.search({ id: downloadId })
  292. .then(downloadItems => resolve({ filename: downloadItems[0] && downloadItems[0].filename }))
  293. .catch(() => resolve({}));
  294. browser.downloads.onChanged.removeListener(onChanged);
  295. }
  296. if (event.state.current == STATE_DOWNLOAD_INTERRUPTED) {
  297. if (event.error && event.error.current == STATE_ERROR_CANCELED_CHROMIUM) {
  298. resolve({});
  299. } else {
  300. reject(new Error(event.state.current));
  301. }
  302. browser.downloads.onChanged.removeListener(onChanged);
  303. }
  304. }
  305. }
  306. });
  307. }
  308. function saveToClipboard(pageData) {
  309. const command = "copy";
  310. document.addEventListener(command, listener);
  311. document.execCommand(command);
  312. document.removeEventListener(command, listener);
  313. function listener(event) {
  314. event.clipboardData.setData(MIMETYPE_HTML, pageData.content);
  315. event.clipboardData.setData("text/plain", pageData.content);
  316. event.preventDefault();
  317. }
  318. }
  319. })();