downloads.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. includeInfobar: message.includeInfobar
  114. });
  115. } else {
  116. if (message.saveToClipboard) {
  117. message.content = contents.join("");
  118. saveToClipboard(message);
  119. singlefile.extension.ui.bg.main.onEnd(tab.id);
  120. } else {
  121. await downloadBlob(new Blob([contents], { type: MIMETYPE_HTML }), tab.id, tab.incognito, message);
  122. }
  123. }
  124. }
  125. return {};
  126. }
  127. async function downloadBlob(blob, tabId, incognito, message) {
  128. try {
  129. if (message.saveToGDrive) {
  130. await uploadPage(message.taskId, message.filename, blob, {
  131. forceWebAuthFlow: message.forceWebAuthFlow,
  132. extractAuthCode: message.extractAuthCode
  133. }, {
  134. onProgress: (offset, size) => singlefile.extension.ui.bg.main.onUploadProgress(tabId, offset, size)
  135. });
  136. } else {
  137. message.url = URL.createObjectURL(blob);
  138. await downloadPage(message, {
  139. confirmFilename: message.confirmFilename,
  140. incognito,
  141. filenameConflictAction: message.filenameConflictAction,
  142. filenameReplacementCharacter: message.filenameReplacementCharacter,
  143. includeInfobar: message.includeInfobar
  144. });
  145. }
  146. singlefile.extension.ui.bg.main.onEnd(tabId);
  147. } catch (error) {
  148. if (!error.message || error.message != "upload_cancelled") {
  149. console.error(error); // eslint-disable-line no-console
  150. singlefile.extension.ui.bg.main.onError(tabId);
  151. }
  152. } finally {
  153. if (message.url) {
  154. URL.revokeObjectURL(message.url);
  155. }
  156. }
  157. }
  158. function getRegExp(string) {
  159. return string.replace(REGEXP_ESCAPE, "\\$1");
  160. }
  161. async function getAuthInfo(authOptions, force) {
  162. let authInfo = await singlefile.extension.core.bg.config.getAuthInfo();
  163. const options = {
  164. interactive: true,
  165. auto: authOptions.extractAuthCode,
  166. forceWebAuthFlow: authOptions.forceWebAuthFlow,
  167. requestPermissionIdentity,
  168. launchWebAuthFlow: options => singlefile.extension.core.bg.tabs.launchWebAuthFlow(options),
  169. extractAuthCode: authURL => singlefile.extension.core.bg.tabs.extractAuthCode(authURL),
  170. promptAuthCode: () => singlefile.extension.core.bg.tabs.promptValue("Please enter the access code for Google Drive")
  171. };
  172. gDrive.setAuthInfo(authInfo, options);
  173. if (!authInfo || !authInfo.accessToken || force) {
  174. authInfo = await gDrive.auth(options);
  175. if (authInfo) {
  176. await singlefile.extension.core.bg.config.setAuthInfo(authInfo);
  177. } else {
  178. await singlefile.extension.core.bg.config.removeAuthInfo();
  179. }
  180. }
  181. return authInfo;
  182. }
  183. async function uploadPage(taskId, filename, blob, authOptions, uploadOptions) {
  184. try {
  185. await getAuthInfo(authOptions);
  186. const taskInfo = singlefile.extension.core.bg.business.getTaskInfo(taskId);
  187. if (taskInfo && !taskInfo.cancelled) {
  188. const uploadInfo = await gDrive.upload(filename, blob, uploadOptions);
  189. singlefile.extension.core.bg.business.setCancelCallback(taskId, uploadInfo.cancelUpload);
  190. return await uploadInfo.uploadPromise;
  191. }
  192. }
  193. catch (error) {
  194. if (error.message == "invalid_token") {
  195. let authInfo;
  196. try {
  197. authInfo = await gDrive.refreshAuthToken();
  198. } catch (error) {
  199. if (error.message == "unknown_token") {
  200. authInfo = await getAuthInfo(authOptions, true);
  201. } else {
  202. throw error;
  203. }
  204. }
  205. if (authInfo) {
  206. await singlefile.extension.core.bg.config.setAuthInfo(authInfo);
  207. } else {
  208. await singlefile.extension.core.bg.config.removeAuthInfo();
  209. }
  210. await uploadPage(taskId, filename, blob, authOptions, uploadOptions);
  211. } else {
  212. throw error;
  213. }
  214. }
  215. }
  216. async function downloadPage(pageData, options) {
  217. const filenameConflictAction = options.filenameConflictAction;
  218. let skipped;
  219. if (filenameConflictAction == CONFLICT_ACTION_SKIP) {
  220. const downloadItems = await browser.downloads.search({
  221. filenameRegex: "(\\\\|/)" + getRegExp(pageData.filename) + "$",
  222. exists: true
  223. });
  224. if (downloadItems.length) {
  225. skipped = true;
  226. } else {
  227. options.filenameConflictAction = CONFLICT_ACTION_UNIQUIFY;
  228. }
  229. }
  230. if (!skipped) {
  231. const downloadInfo = {
  232. url: pageData.url,
  233. saveAs: options.confirmFilename,
  234. filename: pageData.filename,
  235. conflictAction: options.filenameConflictAction
  236. };
  237. if (options.incognito) {
  238. downloadInfo.incognito = true;
  239. }
  240. const downloadData = await download(downloadInfo, options.filenameReplacementCharacter);
  241. if (downloadData.filename && pageData.bookmarkId && pageData.replaceBookmarkURL) {
  242. if (!downloadData.filename.startsWith("file:")) {
  243. if (downloadData.filename.startsWith("/")) {
  244. downloadData.filename = downloadData.filename.substring(1);
  245. }
  246. downloadData.filename = "file:///" + downloadData.filename;
  247. }
  248. await singlefile.extension.core.bg.bookmarks.update(pageData.bookmarkId, { url: downloadData.filename });
  249. }
  250. }
  251. }
  252. async function download(downloadInfo, replacementCharacter) {
  253. let downloadId;
  254. try {
  255. downloadId = await browser.downloads.download(downloadInfo);
  256. } catch (error) {
  257. if (error.message) {
  258. const errorMessage = error.message.toLowerCase();
  259. const invalidFilename = errorMessage.includes(ERROR_INVALID_FILENAME_GECKO) || errorMessage.includes(ERROR_INVALID_FILENAME_CHROMIUM);
  260. if (invalidFilename && downloadInfo.filename.startsWith(".")) {
  261. downloadInfo.filename = replacementCharacter + downloadInfo.filename;
  262. return download(downloadInfo, replacementCharacter);
  263. } else if (invalidFilename && downloadInfo.filename.includes(",")) {
  264. downloadInfo.filename = downloadInfo.filename.replace(/,/g, replacementCharacter);
  265. return download(downloadInfo, replacementCharacter);
  266. } else if (invalidFilename && !downloadInfo.filename.match(/^[\x00-\x7F]+$/)) { // eslint-disable-line no-control-regex
  267. downloadInfo.filename = downloadInfo.filename.replace(/[^\x00-\x7F]+/g, replacementCharacter); // eslint-disable-line no-control-regex
  268. return download(downloadInfo, replacementCharacter);
  269. } else if ((errorMessage.includes(ERROR_INCOGNITO_GECKO) || errorMessage.includes(ERROR_INCOGNITO_GECKO_ALT)) && downloadInfo.incognito) {
  270. delete downloadInfo.incognito;
  271. return download(downloadInfo, replacementCharacter);
  272. } else if (errorMessage == ERROR_CONFLICT_ACTION_GECKO && downloadInfo.conflictAction) {
  273. delete downloadInfo.conflictAction;
  274. return download(downloadInfo, replacementCharacter);
  275. } else if (errorMessage.includes(ERROR_DOWNLOAD_CANCELED_GECKO)) {
  276. return {};
  277. } else {
  278. throw error;
  279. }
  280. } else {
  281. throw error;
  282. }
  283. }
  284. return new Promise((resolve, reject) => {
  285. browser.downloads.onChanged.addListener(onChanged);
  286. function onChanged(event) {
  287. if (event.id == downloadId && event.state) {
  288. if (event.state.current == STATE_DOWNLOAD_COMPLETE) {
  289. browser.downloads.search({ id: downloadId })
  290. .then(downloadItems => resolve({ filename: downloadItems[0] && downloadItems[0].filename }))
  291. .catch(() => resolve({}));
  292. browser.downloads.onChanged.removeListener(onChanged);
  293. }
  294. if (event.state.current == STATE_DOWNLOAD_INTERRUPTED) {
  295. if (event.error && event.error.current == STATE_ERROR_CANCELED_CHROMIUM) {
  296. resolve({});
  297. } else {
  298. reject(new Error(event.state.current));
  299. }
  300. browser.downloads.onChanged.removeListener(onChanged);
  301. }
  302. }
  303. }
  304. });
  305. }
  306. function saveToClipboard(pageData) {
  307. const command = "copy";
  308. document.addEventListener(command, listener);
  309. document.execCommand(command);
  310. document.removeEventListener(command, listener);
  311. function listener(event) {
  312. event.clipboardData.setData(MIMETYPE_HTML, pageData.content);
  313. event.clipboardData.setData("text/plain", pageData.content);
  314. event.preventDefault();
  315. }
  316. }
  317. })();