downloads.js 12 KB

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