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