gdrive.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import {join} from 'path';
  2. import {promises as fs} from 'fs';
  3. import {promisify} from 'util';
  4. import {google} from 'googleapis';
  5. // If modifying these scopes, delete token.json.
  6. const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
  7. // The file token.json stores the user's access and refresh tokens, and is
  8. // created automatically when the authorization flow completes for the first
  9. // time.
  10. const TOKEN_PATH = join(__dirname, '..', 'token.json');
  11. class GoogleAuth extends EventEmitter {
  12. constructor() {
  13. super();
  14. }
  15. async authorize(credentials) {
  16. let token;
  17. const {client_secret, client_id} = credentials;
  18. const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, `http://localhost:${port}`);
  19. try {
  20. token = JSON.parse(await fs.readFile(TOKEN_PATH));
  21. } catch (e) {
  22. const authUrl = oAuth2Client.generateAuthUrl({
  23. access_type: 'offline',
  24. scope: SCOPES,
  25. });
  26. this.emit('auth', authUrl);
  27. const code = await promisify(this.once).bind(this)('token');
  28. token = await oAuth2Client.getToken(code);
  29. await fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  30. } finally {
  31. await oAuth2Client.setCredentials(token);
  32. }
  33. }
  34. token(code) {
  35. this.emit('token', code);
  36. }
  37. }
  38. class GoogleDrive extends GoogleAuth {
  39. constructor() {
  40. super();
  41. this.path = '/drive/api';
  42. }
  43. async getFolderID(path) {
  44. }
  45. async infoFile(path) {
  46. }
  47. async folderList(path) {
  48. }
  49. async downloadFile(path) {
  50. }
  51. async uploadFile(path) {
  52. }
  53. }
  54. export {
  55. GoogleAuth,
  56. GoogleDrive,
  57. };