downloads.js 12 KB

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