downloads.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 { launchWebAuthFlow, extractAuthCode, promptValue } from "./tabs-util.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. import { download } from "./download-util.js";
  35. const partialContents = new Map();
  36. const MIMETYPE_HTML = "text/html";
  37. const CLIENT_ID = "207618107333-3pj2pmelhnl4sf3rpctghs9cean3q8nj.apps.googleusercontent.com";
  38. const SCOPES = ["https://www.googleapis.com/auth/drive.file"];
  39. const CONFLICT_ACTION_SKIP = "skip";
  40. const CONFLICT_ACTION_UNIQUIFY = "uniquify";
  41. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  42. const manifest = browser.runtime.getManifest();
  43. const requestPermissionIdentity = manifest.optional_permissions && manifest.optional_permissions.includes("identity");
  44. const gDrive = new GDrive(CLIENT_ID, SCOPES);
  45. export {
  46. onMessage,
  47. downloadPage,
  48. saveToGDrive,
  49. saveToGitHub
  50. };
  51. async function onMessage(message, sender) {
  52. if (message.method.endsWith(".download")) {
  53. return downloadTabPage(message, sender.tab);
  54. }
  55. if (message.method.endsWith(".disableGDrive")) {
  56. const authInfo = await config.getAuthInfo();
  57. config.removeAuthInfo();
  58. await gDrive.revokeAuthToken(authInfo && (authInfo.accessToken || authInfo.revokableAccessToken));
  59. return {};
  60. }
  61. if (message.method.endsWith(".end")) {
  62. if (message.hash) {
  63. try {
  64. await woleet.anchor(message.hash, message.woleetKey);
  65. } catch (error) {
  66. ui.onError(sender.tab.id, error.message, error.link);
  67. }
  68. }
  69. business.onSaveEnd(message.taskId);
  70. return {};
  71. }
  72. if (message.method.endsWith(".getInfo")) {
  73. return business.getTasksInfo();
  74. }
  75. if (message.method.endsWith(".cancel")) {
  76. business.cancelTask(message.taskId);
  77. return {};
  78. }
  79. if (message.method.endsWith(".cancelAll")) {
  80. business.cancelAllTasks();
  81. return {};
  82. }
  83. if (message.method.endsWith(".saveUrls")) {
  84. business.saveUrls(message.urls);
  85. return {};
  86. }
  87. }
  88. async function downloadTabPage(message, tab) {
  89. let contents;
  90. if (message.truncated) {
  91. contents = partialContents.get(tab.id);
  92. if (!contents) {
  93. contents = [];
  94. partialContents.set(tab.id, contents);
  95. }
  96. contents.push(message.content);
  97. if (message.finished) {
  98. partialContents.delete(tab.id);
  99. }
  100. } else if (message.content) {
  101. contents = [message.content];
  102. }
  103. if (!message.truncated || message.finished) {
  104. if (message.openEditor) {
  105. ui.onEdit(tab.id);
  106. await editor.open({ tabIndex: tab.index + 1, filename: message.filename, content: contents.join("") });
  107. } else {
  108. if (message.saveToClipboard) {
  109. message.content = contents.join("");
  110. saveToClipboard(message);
  111. ui.onEnd(tab.id);
  112. } else {
  113. await downloadContent(contents, tab, tab.incognito, message);
  114. }
  115. }
  116. }
  117. return {};
  118. }
  119. async function downloadContent(contents, tab, incognito, message) {
  120. try {
  121. if (message.saveToGDrive) {
  122. await (await saveToGDrive(message.taskId, message.filename, new Blob([contents], { type: MIMETYPE_HTML }), {
  123. forceWebAuthFlow: message.forceWebAuthFlow,
  124. extractAuthCode: message.extractAuthCode
  125. }, {
  126. onProgress: (offset, size) => ui.onUploadProgress(tab.id, offset, size)
  127. })).uploadPromise;
  128. } else if (message.saveToGitHub) {
  129. await (await saveToGitHub(message.taskId, message.filename, contents.join(""), message.githubToken, message.githubUser, message.githubRepository, message.githubBranch)).pushPromise;
  130. } else if (message.saveWithCompanion) {
  131. await companion.save({
  132. filename: message.filename,
  133. content: message.content,
  134. filenameConflictAction: message.filenameConflictAction
  135. });
  136. } else {
  137. message.url = URL.createObjectURL(new Blob([contents], { type: MIMETYPE_HTML }));
  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. ui.onEnd(tab.id);
  147. if (message.openSavedPage) {
  148. const createTabProperties = { active: true, url: URL.createObjectURL(new Blob([contents], { type: MIMETYPE_HTML })) };
  149. if (tab.index != null) {
  150. createTabProperties.index = tab.index + 1;
  151. }
  152. browser.tabs.create(createTabProperties);
  153. }
  154. } catch (error) {
  155. if (!error.message || error.message != "upload_cancelled") {
  156. console.error(error); // eslint-disable-line no-console
  157. ui.onError(tab.id, error.message, error.link);
  158. }
  159. } finally {
  160. if (message.url) {
  161. URL.revokeObjectURL(message.url);
  162. }
  163. }
  164. }
  165. function getRegExp(string) {
  166. return string.replace(REGEXP_ESCAPE, "\\$1");
  167. }
  168. async function getAuthInfo(authOptions, force) {
  169. let authInfo = await config.getAuthInfo();
  170. const options = {
  171. interactive: true,
  172. auto: authOptions.extractAuthCode,
  173. forceWebAuthFlow: authOptions.forceWebAuthFlow,
  174. requestPermissionIdentity,
  175. launchWebAuthFlow: options => launchWebAuthFlow(options),
  176. extractAuthCode: authURL => extractAuthCode(authURL),
  177. promptAuthCode: () => promptValue("Please enter the access code for Google Drive")
  178. };
  179. gDrive.setAuthInfo(authInfo, options);
  180. if (!authInfo || !authInfo.accessToken || force) {
  181. authInfo = await gDrive.auth(options);
  182. if (authInfo) {
  183. await config.setAuthInfo(authInfo);
  184. } else {
  185. await config.removeAuthInfo();
  186. }
  187. }
  188. return authInfo;
  189. }
  190. async function saveToGitHub(taskId, filename, content, githubToken, githubUser, githubRepository, githubBranch) {
  191. const taskInfo = business.getTaskInfo(taskId);
  192. if (!taskInfo || !taskInfo.cancelled) {
  193. const pushInfo = pushGitHub(githubToken, githubUser, githubRepository, githubBranch, filename, content);
  194. business.setCancelCallback(taskId, pushInfo.cancelPush);
  195. try {
  196. await (await pushInfo).pushPromise;
  197. return pushInfo;
  198. } catch (error) {
  199. throw new Error(error.message + " (GitHub)");
  200. }
  201. }
  202. }
  203. async function saveToGDrive(taskId, filename, blob, authOptions, uploadOptions) {
  204. try {
  205. await getAuthInfo(authOptions);
  206. const taskInfo = business.getTaskInfo(taskId);
  207. if (!taskInfo || !taskInfo.cancelled) {
  208. const uploadInfo = await gDrive.upload(filename, blob, uploadOptions);
  209. business.setCancelCallback(taskId, uploadInfo.cancelUpload);
  210. return uploadInfo;
  211. }
  212. }
  213. catch (error) {
  214. if (error.message == "invalid_token") {
  215. let authInfo;
  216. try {
  217. authInfo = await gDrive.refreshAuthToken();
  218. } catch (error) {
  219. if (error.message == "unknown_token") {
  220. authInfo = await getAuthInfo(authOptions, true);
  221. } else {
  222. throw new Error(error.message + " (Google Drive)");
  223. }
  224. }
  225. if (authInfo) {
  226. await config.setAuthInfo(authInfo);
  227. } else {
  228. await config.removeAuthInfo();
  229. }
  230. await saveToGDrive(taskId, filename, blob, authOptions, uploadOptions);
  231. } else {
  232. throw new Error(error.message + " (Google Drive)");
  233. }
  234. }
  235. }
  236. async function downloadPage(pageData, options) {
  237. const filenameConflictAction = options.filenameConflictAction;
  238. let skipped;
  239. if (filenameConflictAction == CONFLICT_ACTION_SKIP) {
  240. const downloadItems = await browser.downloads.search({
  241. filenameRegex: "(\\\\|/)" + getRegExp(pageData.filename) + "$",
  242. exists: true
  243. });
  244. if (downloadItems.length) {
  245. skipped = true;
  246. } else {
  247. options.filenameConflictAction = CONFLICT_ACTION_UNIQUIFY;
  248. }
  249. }
  250. if (!skipped) {
  251. const downloadInfo = {
  252. url: pageData.url,
  253. saveAs: options.confirmFilename,
  254. filename: pageData.filename,
  255. conflictAction: options.filenameConflictAction
  256. };
  257. if (options.incognito) {
  258. downloadInfo.incognito = true;
  259. }
  260. const downloadData = await download(downloadInfo, options.filenameReplacementCharacter);
  261. if (downloadData.filename && pageData.bookmarkId && pageData.replaceBookmarkURL) {
  262. if (!downloadData.filename.startsWith("file:")) {
  263. if (downloadData.filename.startsWith("/")) {
  264. downloadData.filename = downloadData.filename.substring(1);
  265. }
  266. downloadData.filename = "file:///" + downloadData.filename.replace(/#/g, "%23");
  267. }
  268. await bookmarks.update(pageData.bookmarkId, { url: downloadData.filename });
  269. }
  270. }
  271. }
  272. function saveToClipboard(pageData) {
  273. const command = "copy";
  274. document.addEventListener(command, listener);
  275. document.execCommand(command);
  276. document.removeEventListener(command, listener);
  277. function listener(event) {
  278. event.clipboardData.setData(MIMETYPE_HTML, pageData.content);
  279. event.clipboardData.setData("text/plain", pageData.content);
  280. event.preventDefault();
  281. }
  282. }