gdrive.js 10 KB

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