gdrive.js 12 KB

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