Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs').promises;
- const path = require('path');
- const process = require('process');
- const {authenticate} = require('@google-cloud/local-auth');
- const {google} = require('googleapis');
- // If modifying these scopes, delete token.json.
- const SCOPES = ['https://www.googleapis.com/auth/drive.file'];
- // The file token.json stores the user's access and refresh tokens, and is
- // created automatically when the authorization flow completes for the first
- // time.
- const TOKEN_PATH = path.join(process.cwd(), 'token.json');
- const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');
- const DriveAPI = {
- /**
- * Reads previously authorized credentials from the save file.
- *
- * @return {Promise<OAuth2Client|null>}
- */
- loadSavedCredentialsIfExist: async function () {
- try {
- const content = await fs.readFile(TOKEN_PATH);
- const credentials = JSON.parse(content);
- return google.auth.fromJSON(credentials);
- } catch (err) {
- return null;
- }
- },
- /**
- * Serializes credentials to a file comptible with GoogleAUth.fromJSON.
- *
- * @param {OAuth2Client} client
- * @return {Promise<void>}
- */
- saveCredentials: async function(client) {
- const content = await fs.readFile(CREDENTIALS_PATH);
- const keys = JSON.parse(content);
- const key = keys.installed || keys.web;
- const payload = JSON.stringify({
- type: 'authorized_user',
- client_id: key.client_id,
- client_secret: key.client_secret,
- refresh_token: client.credentials.refresh_token,
- });
- await fs.writeFile(TOKEN_PATH, payload);
- },
- /**
- * Load or request or authorization to call APIs.
- *
- */
- authorize:async function() {
- let client = await this.loadSavedCredentialsIfExist();
- if (client) {
- return client;
- }
- client = await authenticate({
- scopes: SCOPES,
- keyfilePath: CREDENTIALS_PATH,
- });
- if (client.credentials) {
- await this.saveCredentials(client);
- }
- return client;
- },
- /**
- * Lists the names and IDs of up to 10 files.
- * @param {OAuth2Client} authClient An authorized OAuth2 client.
- */
- listFiles:async function (authClient) {
- const drive = google.drive({version: 'v3', auth: authClient});
- const res = await drive.files.list({
- pageSize: 10,
- fields: 'nextPageToken, files(id, name)',
- });
- const files = res.data.files;
- if (files.length === 0) {
- console.log('No files found.');
- return;
- }
- console.log('Files:');
- console.log(files);
- files.map((file) => {
- console.log(`${file.name} (${file.id})`);
- });
- },
- getParent:async function(authClient, name){
- let parent = await this.findParent(authClient);
- if(parent.length >0){
- return parent[0];
- }
- const drive = google.drive({version: 'v3', auth: authClient});
- const fileMetadata = {
- name: 'Client Information',
- mimeType: 'application/vnd.google-apps.folder',
- };
- try {
- const file = await drive.files.create({
- resource: fileMetadata,
- fields: 'id',
- });
- console.log('Folder Id:', file.data.id);
- return file.data.id;
- } catch (err) {
- // TODO(developer) - Handle error
- throw err;
- }
- },
- findParent:async function(authClient){
- const drive = google.drive({version: 'v3', auth: authClient});
- try{
- const res = await drive.files.list({
- q:"name = 'Client Information' and trashed = false"
- });
- const files = res.data.files;
- return files;
- }catch(err){
- console.log(err);
- }
- }
- }
- //authorize().then(listFiles).catch(console.error);
- //DriveAPI.authorize().then(auth => DriveAPI.getParent(auth).then(console.log)).catch(console.error);
- async function thing(){
- let client = await DriveAPI.authorize();
- console.log(await DriveAPI.getParent(client));
- }
- thing();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement