downloads.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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.id, tab.incognito, message);
  131. }
  132. }
  133. }
  134. return {};
  135. }
  136. async function downloadBlob(blob, tabId, 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(tabId, 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(tabId);
  156. } catch (error) {
  157. if (!error.message || error.message != "upload_cancelled") {
  158. console.error(error); // eslint-disable-line no-console
  159. ui.onError(tabId);
  160. }
  161. } finally {
  162. if (message.url) {
  163. URL.revokeObjectURL(message.url);
  164. }
  165. }
  166. }
  167. function getRegExp(string) {
  168. return string.replace(REGEXP_ESCAPE, "\\$1");
  169. }
  170. async function getAuthInfo(authOptions, force) {
  171. let authInfo = await config.getAuthInfo();
  172. const options = {
  173. interactive: true,
  174. auto: authOptions.extractAuthCode,
  175. forceWebAuthFlow: authOptions.forceWebAuthFlow,
  176. requestPermissionIdentity,
  177. launchWebAuthFlow: options => tabs.launchWebAuthFlow(options),
  178. extractAuthCode: authURL => tabs.extractAuthCode(authURL),
  179. promptAuthCode: () => tabs.promptValue("Please enter the access code for Google Drive")
  180. };
  181. gDrive.setAuthInfo(authInfo, options);
  182. if (!authInfo || !authInfo.accessToken || force) {
  183. authInfo = await gDrive.auth(options);
  184. if (authInfo) {
  185. await config.setAuthInfo(authInfo);
  186. } else {
  187. await config.removeAuthInfo();
  188. }
  189. }
  190. return authInfo;
  191. }
  192. async function uploadPage(taskId, filename, blob, authOptions, uploadOptions) {
  193. try {
  194. await getAuthInfo(authOptions);
  195. const taskInfo = business.getTaskInfo(taskId);
  196. if (taskInfo && !taskInfo.cancelled) {
  197. const uploadInfo = await gDrive.upload(filename, blob, uploadOptions);
  198. business.setCancelCallback(taskId, uploadInfo.cancelUpload);
  199. return await uploadInfo.uploadPromise;
  200. }
  201. }
  202. catch (error) {
  203. if (error.message == "invalid_token") {
  204. let authInfo;
  205. try {
  206. authInfo = await gDrive.refreshAuthToken();
  207. } catch (error) {
  208. if (error.message == "unknown_token") {
  209. authInfo = await getAuthInfo(authOptions, true);
  210. } else {
  211. throw error;
  212. }
  213. }
  214. if (authInfo) {
  215. await config.setAuthInfo(authInfo);
  216. } else {
  217. await config.removeAuthInfo();
  218. }
  219. await uploadPage(taskId, filename, blob, authOptions, uploadOptions);
  220. } else {
  221. throw error;
  222. }
  223. }
  224. }
  225. async function downloadPage(pageData, options) {
  226. const filenameConflictAction = options.filenameConflictAction;
  227. let skipped;
  228. if (filenameConflictAction == CONFLICT_ACTION_SKIP) {
  229. const downloadItems = await browser.downloads.search({
  230. filenameRegex: "(\\\\|/)" + getRegExp(pageData.filename) + "$",
  231. exists: true
  232. });
  233. if (downloadItems.length) {
  234. skipped = true;
  235. } else {
  236. options.filenameConflictAction = CONFLICT_ACTION_UNIQUIFY;
  237. }
  238. }
  239. if (!skipped) {
  240. const downloadInfo = {
  241. url: pageData.url,
  242. saveAs: options.confirmFilename,
  243. filename: pageData.filename,
  244. conflictAction: options.filenameConflictAction
  245. };
  246. if (options.incognito) {
  247. downloadInfo.incognito = true;
  248. }
  249. const downloadData = await download(downloadInfo, options.filenameReplacementCharacter);
  250. if (downloadData.filename && pageData.bookmarkId && pageData.replaceBookmarkURL) {
  251. if (!downloadData.filename.startsWith("file:")) {
  252. if (downloadData.filename.startsWith("/")) {
  253. downloadData.filename = downloadData.filename.substring(1);
  254. }
  255. downloadData.filename = "file:///" + downloadData.filename;
  256. }
  257. await bookmarks.update(pageData.bookmarkId, { url: downloadData.filename });
  258. }
  259. }
  260. }
  261. async function download(downloadInfo, replacementCharacter) {
  262. let downloadId;
  263. try {
  264. downloadId = await browser.downloads.download(downloadInfo);
  265. } catch (error) {
  266. if (error.message) {
  267. const errorMessage = error.message.toLowerCase();
  268. const invalidFilename = errorMessage.includes(ERROR_INVALID_FILENAME_GECKO) || errorMessage.includes(ERROR_INVALID_FILENAME_CHROMIUM);
  269. if (invalidFilename && downloadInfo.filename.startsWith(".")) {
  270. downloadInfo.filename = replacementCharacter + downloadInfo.filename;
  271. return download(downloadInfo, replacementCharacter);
  272. } else if (invalidFilename && downloadInfo.filename.includes(",")) {
  273. downloadInfo.filename = downloadInfo.filename.replace(/,/g, replacementCharacter);
  274. return download(downloadInfo, replacementCharacter);
  275. } else if (invalidFilename && !downloadInfo.filename.match(/^[\x00-\x7F]+$/)) { // eslint-disable-line no-control-regex
  276. downloadInfo.filename = downloadInfo.filename.replace(/[^\x00-\x7F]+/g, replacementCharacter); // eslint-disable-line no-control-regex
  277. return download(downloadInfo, replacementCharacter);
  278. } else if ((errorMessage.includes(ERROR_INCOGNITO_GECKO) || errorMessage.includes(ERROR_INCOGNITO_GECKO_ALT)) && downloadInfo.incognito) {
  279. delete downloadInfo.incognito;
  280. return download(downloadInfo, replacementCharacter);
  281. } else if (errorMessage == ERROR_CONFLICT_ACTION_GECKO && downloadInfo.conflictAction) {
  282. delete downloadInfo.conflictAction;
  283. return download(downloadInfo, replacementCharacter);
  284. } else if (errorMessage.includes(ERROR_DOWNLOAD_CANCELED_GECKO)) {
  285. return {};
  286. } else {
  287. throw error;
  288. }
  289. } else {
  290. throw error;
  291. }
  292. }
  293. return new Promise((resolve, reject) => {
  294. browser.downloads.onChanged.addListener(onChanged);
  295. function onChanged(event) {
  296. if (event.id == downloadId && event.state) {
  297. if (event.state.current == STATE_DOWNLOAD_COMPLETE) {
  298. browser.downloads.search({ id: downloadId })
  299. .then(downloadItems => resolve({ filename: downloadItems[0] && downloadItems[0].filename }))
  300. .catch(() => resolve({}));
  301. browser.downloads.onChanged.removeListener(onChanged);
  302. }
  303. if (event.state.current == STATE_DOWNLOAD_INTERRUPTED) {
  304. if (event.error && event.error.current == STATE_ERROR_CANCELED_CHROMIUM) {
  305. resolve({});
  306. } else {
  307. reject(new Error(event.state.current));
  308. }
  309. browser.downloads.onChanged.removeListener(onChanged);
  310. }
  311. }
  312. }
  313. });
  314. }
  315. function saveToClipboard(pageData) {
  316. const command = "copy";
  317. document.addEventListener(command, listener);
  318. document.execCommand(command);
  319. document.removeEventListener(command, listener);
  320. function listener(event) {
  321. event.clipboardData.setData(MIMETYPE_HTML, pageData.content);
  322. event.clipboardData.setData("text/plain", pageData.content);
  323. event.preventDefault();
  324. }
  325. }