gdrive.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /*
  2. * Copyright 2010-2019 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, fetch, setInterval */
  24. this.GDrive = this.GDrive || (() => {
  25. "use strict";
  26. const TOKEN_URL = "https://oauth2.googleapis.com/token";
  27. const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
  28. const REVOKE_ACCESS_URL = "https://accounts.google.com/o/oauth2/revoke";
  29. const GDRIVE_URL = "https://www.googleapis.com/drive/v3/files";
  30. const GDRIVE_UPLOAD_URL = "https://www.googleapis.com/upload/drive/v3/files";
  31. let requestPermissionIdentityNeeded;
  32. class GDrive {
  33. constructor(clientId, scopes) {
  34. this.clientId = clientId;
  35. this.scopes = scopes;
  36. this.folderIds = new Map();
  37. setInterval(() => this.folderIds.clear(), 60 * 1000);
  38. }
  39. async requestPermissionIdentity(options) {
  40. if (options.requestPermissionIdentity) {
  41. await requestPermissionIdentity();
  42. }
  43. }
  44. async auth(options = { interactive: true, auto: true }) {
  45. if (this.managedToken(options)) {
  46. await this.requestPermissionIdentity(options);
  47. const token = await browser.identity.getAuthToken({ interactive: options.interactive });
  48. if (token) {
  49. this.accessToken = token;
  50. return { accessToken: this.accessToken };
  51. }
  52. } else {
  53. this.getAuthURL(options);
  54. return options.code ? authFromCode(this, options) : initAuth(this, options);
  55. }
  56. }
  57. managedToken(options) {
  58. return Boolean(browser.identity && browser.identity.getAuthToken) && !options.forceWebAuthFlow;
  59. }
  60. setAuthInfo(authInfo, options) {
  61. if (!this.managedToken(options)) {
  62. if (authInfo) {
  63. this.accessToken = authInfo.accessToken;
  64. this.refreshToken = authInfo.refreshToken;
  65. this.expirationDate = authInfo.expirationDate;
  66. } else {
  67. delete this.accessToken;
  68. delete this.refreshToken;
  69. delete this.expirationDate;
  70. }
  71. }
  72. }
  73. getAuthURL(options = {}) {
  74. this.redirectURI = encodeURIComponent("urn:ietf:wg:oauth:2.0:oob" + (options.auto ? ":auto" : ""));
  75. this.authURL = AUTH_URL +
  76. "?client_id=" + this.clientId +
  77. "&response_type=code" +
  78. "&access_type=offline" +
  79. "&redirect_uri=" + this.redirectURI +
  80. "&scope=" + this.scopes.join(" ");
  81. return this.authURL;
  82. }
  83. async refreshAuthToken() {
  84. if (this.clientId && this.refreshToken) {
  85. const httpResponse = await fetch(TOKEN_URL, {
  86. method: "POST",
  87. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  88. body: "client_id=" + this.clientId +
  89. "&refresh_token=" + this.refreshToken +
  90. "&grant_type=refresh_token"
  91. });
  92. if (httpResponse.status == 400) {
  93. throw new Error("unknown_token");
  94. }
  95. const response = await getJSON(httpResponse);
  96. this.accessToken = response.access_token;
  97. if (response.refresh_token) {
  98. this.refreshToken = response.refresh_token;
  99. }
  100. if (response.expires_in) {
  101. this.expirationDate = Date.now() + (response.expires_in * 1000);
  102. }
  103. return { accessToken: this.accessToken, refreshToken: this.refreshToken, expirationDate: this.expirationDate };
  104. }
  105. }
  106. async revokeAuthToken(accessToken) {
  107. if (accessToken) {
  108. if (browser.identity && browser.identity.removeCachedAuthToken) {
  109. try {
  110. await browser.identity.removeCachedAuthToken({ token: accessToken });
  111. } catch (error) {
  112. // ignored
  113. }
  114. }
  115. const httpResponse = await fetch(REVOKE_ACCESS_URL, {
  116. method: "POST",
  117. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  118. body: "token=" + accessToken
  119. });
  120. try {
  121. await getJSON(httpResponse);
  122. }
  123. catch (error) {
  124. if (error.message != "invalid_token") {
  125. throw error;
  126. }
  127. }
  128. finally {
  129. delete this.accessToken;
  130. delete this.refreshToken;
  131. delete this.expirationDate;
  132. }
  133. }
  134. }
  135. async upload(fullFilename, blob, retry = true) {
  136. const parentFolderId = await getParentFolderId(this, fullFilename);
  137. const fileParts = fullFilename.split("/");
  138. const filename = fileParts.pop();
  139. const uploader = new MediaUploader({
  140. token: this.accessToken,
  141. file: blob,
  142. parents: [parentFolderId],
  143. filename
  144. });
  145. try {
  146. return await uploader.upload();
  147. }
  148. catch (error) {
  149. if (error.message == "path_not_found" && retry) {
  150. this.folderIds.clear();
  151. return this.upload(fullFilename, blob, false);
  152. } else {
  153. throw error;
  154. }
  155. }
  156. }
  157. }
  158. class MediaUploader {
  159. constructor(options) {
  160. this.file = options.file;
  161. this.contentType = this.file.type || "application/octet-stream";
  162. this.metadata = {
  163. name: options.filename,
  164. mimeType: this.contentType,
  165. parents: options.parents || ["root"]
  166. };
  167. this.token = options.token;
  168. this.offset = 0;
  169. this.chunkSize = options.chunkSize || 5 * 1024 * 1024;
  170. }
  171. async upload() {
  172. const httpResponse = getResponse(await fetch(GDRIVE_UPLOAD_URL + "?uploadType=resumable", {
  173. method: "POST",
  174. headers: {
  175. "Authorization": "Bearer " + this.token,
  176. "Content-Type": "application/json",
  177. "X-Upload-Content-Length": this.file.size,
  178. "X-Upload-Content-Type": this.contentType
  179. },
  180. body: JSON.stringify(this.metadata)
  181. }));
  182. const location = httpResponse.headers.get("Location");
  183. this.url = location;
  184. return sendFile(this);
  185. }
  186. }
  187. return GDrive;
  188. async function requestPermissionIdentity() {
  189. if (requestPermissionIdentityNeeded) {
  190. try {
  191. await browser.permissions.request({ permissions: ["identity"] });
  192. requestPermissionIdentityNeeded = false;
  193. }
  194. catch (error) {
  195. // ignored;
  196. }
  197. }
  198. }
  199. async function authFromCode(gdrive, options) {
  200. const httpResponse = await fetch(TOKEN_URL, {
  201. method: "POST",
  202. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  203. body: "client_id=" + gdrive.clientId +
  204. "&grant_type=authorization_code" +
  205. "&code=" + options.code +
  206. "&redirect_uri=" + gdrive.redirectURI
  207. });
  208. const response = await getJSON(httpResponse);
  209. gdrive.accessToken = response.access_token;
  210. gdrive.refreshToken = response.refresh_token;
  211. gdrive.expirationDate = Date.now() + (response.expires_in * 1000);
  212. return { accessToken: gdrive.accessToken, refreshToken: gdrive.refreshToken, expirationDate: gdrive.expirationDate };
  213. }
  214. async function initAuth(gdrive, options) {
  215. try {
  216. if (gdrive.managedToken(options)) {
  217. return await browser.identity.launchWebAuthFlow({
  218. interactive: options.interactive,
  219. url: gdrive.authURL
  220. });
  221. } else if (gdrive.launchWebAuthFlow) {
  222. return await gdrive.launchWebAuthFlow({ url: gdrive.authURL });
  223. } else {
  224. throw new Error("auth_not_supported");
  225. }
  226. }
  227. catch (error) {
  228. if (error.message && error.message.includes("access")) {
  229. throw new Error("code_required");
  230. } else {
  231. throw error;
  232. }
  233. }
  234. }
  235. async function getParentFolderId(gdrive, filename, retry = true) {
  236. const fileParts = filename.split("/");
  237. fileParts.pop();
  238. const folderId = gdrive.folderIds.get(fileParts.join("/"));
  239. if (folderId) {
  240. return folderId;
  241. }
  242. let parentFolderId = "root";
  243. if (fileParts.length) {
  244. let fullFolderName = "";
  245. for (const folderName of fileParts) {
  246. if (fullFolderName) {
  247. fullFolderName += "/";
  248. }
  249. fullFolderName += folderName;
  250. const folderId = gdrive.folderIds.get(fullFolderName);
  251. if (folderId) {
  252. parentFolderId = folderId;
  253. } else {
  254. try {
  255. parentFolderId = await getOrCreateFolder(gdrive, folderName, parentFolderId);
  256. gdrive.folderIds.set(fullFolderName, parentFolderId);
  257. } catch (error) {
  258. if (error.message == "path_not_found" && retry) {
  259. gdrive.folderIds.clear();
  260. return getParentFolderId(gdrive, filename, false);
  261. } else {
  262. throw error;
  263. }
  264. }
  265. }
  266. }
  267. }
  268. return parentFolderId;
  269. }
  270. async function getOrCreateFolder(gdrive, folderName, parentFolderId) {
  271. const response = await getFolder(gdrive, folderName, parentFolderId);
  272. if (response.files.length) {
  273. return response.files[0].id;
  274. } else {
  275. const response = await createFolder(gdrive, folderName, parentFolderId);
  276. return response.id;
  277. }
  278. }
  279. async function getFolder(gdrive, folderName, parentFolderId) {
  280. const httpResponse = await fetch(GDRIVE_URL + "?q=mimeType = 'application/vnd.google-apps.folder' and name = '" + folderName + "' and trashed != true and '" + parentFolderId + "' in parents", {
  281. headers: {
  282. "Authorization": "Bearer " + gdrive.accessToken
  283. }
  284. });
  285. return getJSON(httpResponse);
  286. }
  287. async function createFolder(gdrive, folderName, parentFolderId) {
  288. const httpResponse = await fetch(GDRIVE_URL, {
  289. method: "POST",
  290. headers: {
  291. "Authorization": "Bearer " + gdrive.accessToken,
  292. "Content-Type": "application/json"
  293. },
  294. body: JSON.stringify({
  295. name: folderName,
  296. parents: [parentFolderId],
  297. mimeType: "application/vnd.google-apps.folder"
  298. })
  299. });
  300. return getJSON(httpResponse);
  301. }
  302. async function sendFile(mediaUploader) {
  303. let content = mediaUploader.file, end = mediaUploader.file.size;
  304. if (mediaUploader.offset || mediaUploader.chunkSize) {
  305. if (mediaUploader.chunkSize) {
  306. end = Math.min(mediaUploader.offset + mediaUploader.chunkSize, mediaUploader.file.size);
  307. }
  308. content = content.slice(mediaUploader.offset, end);
  309. }
  310. const httpResponse = await fetch(mediaUploader.url, {
  311. method: "PUT",
  312. headers: {
  313. "Authorization": "Bearer " + mediaUploader.token,
  314. "Content-Type": mediaUploader.contentType,
  315. "Content-Range": "bytes " + mediaUploader.offset + "-" + (end - 1) + "/" + mediaUploader.file.size,
  316. "X-Upload-Content-Type": mediaUploader.contentType
  317. },
  318. body: content
  319. });
  320. if (httpResponse.status == 200 || httpResponse.status == 201) {
  321. return httpResponse.json();
  322. } else if (httpResponse.status == 308) {
  323. const range = httpResponse.headers.get("Range");
  324. if (range) {
  325. mediaUploader.offset = parseInt(range.match(/\d+/g).pop(), 10) + 1;
  326. }
  327. sendFile(mediaUploader);
  328. } else {
  329. getResponse(httpResponse);
  330. }
  331. }
  332. async function getJSON(httpResponse) {
  333. httpResponse = getResponse(httpResponse);
  334. const response = await httpResponse.json();
  335. if (response.error) {
  336. throw new Error(response.error);
  337. } else {
  338. return response;
  339. }
  340. }
  341. function getResponse(httpResponse) {
  342. if (httpResponse.status == 200) {
  343. return httpResponse;
  344. } else if (httpResponse.status == 404) {
  345. throw new Error("path_not_found");
  346. } else if (httpResponse.status == 401) {
  347. throw new Error("invalid_token");
  348. } else {
  349. throw new Error("unknown_error (" + httpResponse.status + ")");
  350. }
  351. }
  352. })();