Advertisement
philipd83

Express google drive

Mar 26th, 2023
1,216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs').promises;
  2. const path = require('path');
  3. const process = require('process');
  4. const {authenticate} = require('@google-cloud/local-auth');
  5. const {google} = require('googleapis');
  6.  
  7. // If modifying these scopes, delete token.json.
  8. const SCOPES = ['https://www.googleapis.com/auth/drive.file'];
  9. // The file token.json stores the user's access and refresh tokens, and is
  10. // created automatically when the authorization flow completes for the first
  11. // time.
  12. const TOKEN_PATH = path.join(process.cwd(), 'token.json');
  13. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');
  14.  
  15. const DriveAPI = {
  16.     /**
  17.      * Reads previously authorized credentials from the save file.
  18.      *
  19.      * @return {Promise<OAuth2Client|null>}
  20.      */
  21.     loadSavedCredentialsIfExist: async function () {
  22.         try {
  23.             const content = await fs.readFile(TOKEN_PATH);
  24.             const credentials = JSON.parse(content);
  25.             return google.auth.fromJSON(credentials);
  26.         } catch (err) {
  27.             return null;
  28.         }
  29.     },
  30.  
  31.     /**
  32.      * Serializes credentials to a file comptible with GoogleAUth.fromJSON.
  33.      *
  34.      * @param {OAuth2Client} client
  35.      * @return {Promise<void>}
  36.      */
  37.     saveCredentials: async function(client) {
  38.         const content = await fs.readFile(CREDENTIALS_PATH);
  39.         const keys = JSON.parse(content);
  40.         const key = keys.installed || keys.web;
  41.         const payload = JSON.stringify({
  42.             type: 'authorized_user',
  43.             client_id: key.client_id,
  44.             client_secret: key.client_secret,
  45.             refresh_token: client.credentials.refresh_token,
  46.         });
  47.         await fs.writeFile(TOKEN_PATH, payload);
  48.     },
  49.  
  50.     /**
  51.      * Load or request or authorization to call APIs.
  52.      *
  53.      */
  54.     authorize:async function() {
  55.         let client = await this.loadSavedCredentialsIfExist();
  56.         if (client) {
  57.             return client;
  58.         }
  59.         client = await authenticate({
  60.             scopes: SCOPES,
  61.             keyfilePath: CREDENTIALS_PATH,
  62.         });
  63.         if (client.credentials) {
  64.             await this.saveCredentials(client);
  65.         }
  66.         return client;
  67.     },
  68.  
  69.     /**
  70.      * Lists the names and IDs of up to 10 files.
  71.      * @param {OAuth2Client} authClient An authorized OAuth2 client.
  72.      */
  73.     listFiles:async function (authClient) {
  74.         const drive = google.drive({version: 'v3', auth: authClient});
  75.         const res = await drive.files.list({
  76.             pageSize: 10,
  77.             fields: 'nextPageToken, files(id, name)',
  78.         });
  79.         const files = res.data.files;
  80.         if (files.length === 0) {
  81.             console.log('No files found.');
  82.             return;
  83.         }
  84.  
  85.         console.log('Files:');
  86.         console.log(files);
  87.         files.map((file) => {
  88.             console.log(`${file.name} (${file.id})`);
  89.         });
  90.     },
  91.     getParent:async function(authClient, name){
  92.         let parent = await this.findParent(authClient);
  93.         if(parent.length >0){
  94.             return parent[0];
  95.         }
  96.  
  97.  
  98.         const drive = google.drive({version: 'v3', auth: authClient});
  99.  
  100.         const fileMetadata = {
  101.             name: 'Client Information',
  102.             mimeType: 'application/vnd.google-apps.folder',
  103.           };
  104.  
  105.         try {
  106.             const file = await drive.files.create({
  107.               resource: fileMetadata,
  108.               fields: 'id',
  109.             });
  110.             console.log('Folder Id:', file.data.id);
  111.             return file.data.id;
  112.           } catch (err) {
  113.             // TODO(developer) - Handle error
  114.             throw err;
  115.           }
  116.     },
  117.     findParent:async function(authClient){
  118.         const drive = google.drive({version: 'v3', auth: authClient});
  119.  
  120.         try{
  121.             const res = await drive.files.list({
  122.                 q:"name = 'Client Information' and trashed = false"
  123.             });
  124.             const files = res.data.files;
  125.  
  126.             return files;
  127.  
  128.         }catch(err){
  129.             console.log(err);
  130.         }
  131.  
  132.     }
  133. }
  134.  
  135. //authorize().then(listFiles).catch(console.error);
  136. //DriveAPI.authorize().then(auth => DriveAPI.getParent(auth).then(console.log)).catch(console.error);
  137. async function thing(){
  138.     let client = await DriveAPI.authorize();
  139.     console.log(await DriveAPI.getParent(client));
  140.  
  141. }
  142. thing();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement