I am trying to set up an application to upload files to google drive using their api. I got it functioning basically, uploading files, but not to the particular folder I would like them in. I was starting to and set up the process of identifying the parent folder by searching for title and getting the id from the response, when I received the error:
{
domain: 'usageLimits',
reason: 'dailyLimitExceededUnreg',
message: 'Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.',
extendedHelp: 'https://code.google.com/apis/console'
}
Clearly this error means I have to sign up, so I did. However I cannot figure out where to post the credentials I received from signing up in the application. Below is the full body of my Nodejs file. I tried replacing the json generated from the Quickstart application with those from the signup process but they don’t have the same fields and it did not work. The signup contained the following keys:
{
"type":
"project_id":
"private_key_id":
"private_key":
"client_email":
"client_id":
"auth_uri":
"token_uri":
"auth_provider_x509_cert_url":
"client_x509_cert_url":
}
let fs = require('fs-extra')
const readline = require('readline');
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 = 'certificates/token.json';
fs.readFile('certificates/credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.
authorize(JSON.parse(content), execute);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
function execute(auth) {
const drive = google.drive({ version: 'v3', auth });
return drive.files.list({
"includeItemsFromAllDrives": false,
"includeTeamDriveItems": true,
"q": "name contains 'certificates' and name contains '2019'",
"supportsAllDrives": true,
"supportsTeamDrives": true
})
.then(function (response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function (err) { console.error("Execute error", err); });
}
execute();
const newCertificates = JSON.parse(fs.readFileSync('certificates/newCertificates.json', 'utf8'))
let certificates = [...newCertificates.lastYear, ...newCertificates.thisYear]
/**
* Lists the names and IDs of up to 10 files.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
const drive = google.drive({ version: 'v3', auth });
drive.files.list({
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const files = res.data.files;
if (files.length) {
console.log('Files:');
files.map((file) => {
console.log(`${file.name} (${file.id})`);
});
} else {
console.log('No files found.');
}
});
}
// For each Certificate object
function uploadFiles(auth) {
const drive = google.drive({ version: 'v3', auth });
for (let certificate of certificates) {
let courseTitleArr = certificate.course.split(' ');
let courseDate = courseTitleArr[courseTitleArr.length - 1].replace(/[()]/g, '');
let year = String(new Date(courseDate).getFullYear());
const cleanCourse = certificate.course.split(' ').splice(0, courseTitleArr.length - 1).join(' ').trim();
var fileMetadata = {
'name': `${certificate.student}.pdf`,
parents: 'certificates/'
};
var media = {
mimeType: 'application/pdf',
body: fs.createReadStream(`certificates/${year} Certificates/${cleanCourse}/${certificate.student}.pdf`)
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id: ', file.id);
}
});
}
}
// Upload to google drive in the corresponding folder