gdrive.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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, 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. });
  132. try {
  133. return await uploader.upload();
  134. }
  135. catch (error) {
  136. if (error.message == "path_not_found" && retry) {
  137. this.folderIds.clear();
  138. return this.upload(fullFilename, blob, false);
  139. } else {
  140. throw error;
  141. }
  142. }
  143. }
  144. }
  145. class MediaUploader {
  146. constructor(options) {
  147. this.file = options.file;
  148. this.contentType = this.file.type || "application/octet-stream";
  149. this.metadata = {
  150. name: options.filename,
  151. mimeType: this.contentType,
  152. parents: options.parents || ["root"]
  153. };
  154. this.token = options.token;
  155. this.offset = 0;
  156. this.chunkSize = options.chunkSize || 5 * 1024 * 1024;
  157. }
  158. async upload() {
  159. const httpResponse = getResponse(await fetch(GDRIVE_UPLOAD_URL + "?uploadType=resumable", {
  160. method: "POST",
  161. headers: {
  162. "Authorization": "Bearer " + this.token,
  163. "Content-Type": "application/json",
  164. "X-Upload-Content-Length": this.file.size,
  165. "X-Upload-Content-Type": this.contentType
  166. },
  167. body: JSON.stringify(this.metadata)
  168. }));
  169. const location = httpResponse.headers.get("Location");
  170. this.url = location;
  171. return sendFile(this);
  172. }
  173. }
  174. return GDrive;
  175. async function authFromCode(gdrive, options) {
  176. const httpResponse = await fetch(TOKEN_URL, {
  177. method: "POST",
  178. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  179. body: "client_id=" + gdrive.clientId +
  180. "&grant_type=authorization_code" +
  181. "&code=" + options.code +
  182. "&redirect_uri=" + gdrive.redirectURI
  183. });
  184. const response = await getJSON(httpResponse);
  185. gdrive.accessToken = response.access_token;
  186. gdrive.refreshToken = response.refresh_token;
  187. gdrive.expirationDate = Date.now() + (response.expires_in * 1000);
  188. return { accessToken: gdrive.accessToken, refreshToken: gdrive.refreshToken, expirationDate: gdrive.expirationDate };
  189. }
  190. async function initAuth(gdrive, options) {
  191. let code;
  192. if (options.extractAuthCode) {
  193. options.extractAuthCode(getAuthURL(gdrive, options))
  194. .then(authCode => code = authCode)
  195. .catch(() => { /* ignored */ });
  196. }
  197. try {
  198. if (browser.identity && browser.identity.launchWebAuthFlow && !options.forceWebAuthFlow) {
  199. return await browser.identity.launchWebAuthFlow({
  200. interactive: options.interactive,
  201. url: gdrive.authURL
  202. });
  203. } else if (options.launchWebAuthFlow) {
  204. return await options.launchWebAuthFlow({ url: gdrive.authURL });
  205. } else {
  206. throw new Error("auth_not_supported");
  207. }
  208. }
  209. catch (error) {
  210. if (error.message && (error.message == "code_required" || error.message.includes("access"))) {
  211. if (!options.auto && !code && options.promptAuthCode) {
  212. code = await options.promptAuthCode();
  213. }
  214. if (code) {
  215. options.code = code;
  216. return await authFromCode(gdrive, options);
  217. } else {
  218. throw new Error("code_required");
  219. }
  220. } else {
  221. throw error;
  222. }
  223. }
  224. }
  225. function getAuthURL(gdrive, options = {}) {
  226. gdrive.redirectURI = encodeURIComponent("urn:ietf:wg:oauth:2.0:oob" + (options.auto ? ":auto" : ""));
  227. gdrive.authURL = AUTH_URL +
  228. "?client_id=" + gdrive.clientId +
  229. "&response_type=code" +
  230. "&access_type=offline" +
  231. "&redirect_uri=" + gdrive.redirectURI +
  232. "&scope=" + gdrive.scopes.join(" ");
  233. return gdrive.authURL;
  234. }
  235. function nativeAuth(options = {}) {
  236. return Boolean(browser.identity && browser.identity.getAuthToken) && !options.forceWebAuthFlow;
  237. }
  238. async function getParentFolderId(gdrive, filename, retry = true) {
  239. const fileParts = filename.split("/");
  240. fileParts.pop();
  241. const folderId = gdrive.folderIds.get(fileParts.join("/"));
  242. if (folderId) {
  243. return folderId;
  244. }
  245. let parentFolderId = "root";
  246. if (fileParts.length) {
  247. let fullFolderName = "";
  248. for (const folderName of fileParts) {
  249. if (fullFolderName) {
  250. fullFolderName += "/";
  251. }
  252. fullFolderName += folderName;
  253. const folderId = gdrive.folderIds.get(fullFolderName);
  254. if (folderId) {
  255. parentFolderId = folderId;
  256. } else {
  257. try {
  258. parentFolderId = await getOrCreateFolder(gdrive, folderName, parentFolderId);
  259. gdrive.folderIds.set(fullFolderName, parentFolderId);
  260. } catch (error) {
  261. if (error.message == "path_not_found" && retry) {
  262. gdrive.folderIds.clear();
  263. return getParentFolderId(gdrive, filename, false);
  264. } else {
  265. throw error;
  266. }
  267. }
  268. }
  269. }
  270. }
  271. return parentFolderId;
  272. }
  273. async function getOrCreateFolder(gdrive, folderName, parentFolderId) {
  274. const response = await getFolder(gdrive, folderName, parentFolderId);
  275. if (response.files.length) {
  276. return response.files[0].id;
  277. } else {
  278. const response = await createFolder(gdrive, folderName, parentFolderId);
  279. return response.id;
  280. }
  281. }
  282. async function getFolder(gdrive, folderName, parentFolderId) {
  283. const httpResponse = await fetch(GDRIVE_URL + "?q=mimeType = 'application/vnd.google-apps.folder' and name = '" + folderName + "' and trashed != true and '" + parentFolderId + "' in parents", {
  284. headers: {
  285. "Authorization": "Bearer " + gdrive.accessToken
  286. }
  287. });
  288. return getJSON(httpResponse);
  289. }
  290. async function createFolder(gdrive, folderName, parentFolderId) {
  291. const httpResponse = await fetch(GDRIVE_URL, {
  292. method: "POST",
  293. headers: {
  294. "Authorization": "Bearer " + gdrive.accessToken,
  295. "Content-Type": "application/json"
  296. },
  297. body: JSON.stringify({
  298. name: folderName,
  299. parents: [parentFolderId],
  300. mimeType: "application/vnd.google-apps.folder"
  301. })
  302. });
  303. return getJSON(httpResponse);
  304. }
  305. async function sendFile(mediaUploader) {
  306. let content = mediaUploader.file, end = mediaUploader.file.size;
  307. if (mediaUploader.offset || mediaUploader.chunkSize) {
  308. if (mediaUploader.chunkSize) {
  309. end = Math.min(mediaUploader.offset + mediaUploader.chunkSize, mediaUploader.file.size);
  310. }
  311. content = content.slice(mediaUploader.offset, end);
  312. }
  313. const httpResponse = await fetch(mediaUploader.url, {
  314. method: "PUT",
  315. headers: {
  316. "Authorization": "Bearer " + mediaUploader.token,
  317. "Content-Type": mediaUploader.contentType,
  318. "Content-Range": "bytes " + mediaUploader.offset + "-" + (end - 1) + "/" + mediaUploader.file.size,
  319. "X-Upload-Content-Type": mediaUploader.contentType
  320. },
  321. body: content
  322. });
  323. if (httpResponse.status == 200 || httpResponse.status == 201) {
  324. return httpResponse.json();
  325. } else if (httpResponse.status == 308) {
  326. const range = httpResponse.headers.get("Range");
  327. if (range) {
  328. mediaUploader.offset = parseInt(range.match(/\d+/g).pop(), 10) + 1;
  329. }
  330. sendFile(mediaUploader);
  331. } else {
  332. getResponse(httpResponse);
  333. }
  334. }
  335. async function getJSON(httpResponse) {
  336. httpResponse = getResponse(httpResponse);
  337. const response = await httpResponse.json();
  338. if (response.error) {
  339. throw new Error(response.error);
  340. } else {
  341. return response;
  342. }
  343. }
  344. function getResponse(httpResponse) {
  345. if (httpResponse.status == 200) {
  346. return httpResponse;
  347. } else if (httpResponse.status == 404) {
  348. throw new Error("path_not_found");
  349. } else if (httpResponse.status == 401) {
  350. throw new Error("invalid_token");
  351. } else {
  352. throw new Error("unknown_error (" + httpResponse.status + ")");
  353. }
  354. }
  355. })();