gdrive.js 10 KB

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