1
0

downloads.js 12 KB

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