gdrive.js 12 KB

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