authClient.request is not a function - javascript

I am trying to create events using the google calendar api however, I am having trouble with the authorization. I created a google login, a different way so I am not sure the best way to go about connecting to the google calendar, this is my hwapi file:
var Homework = require('../models/homework');
var mongoose = require('mongoose');
var google = require('googleapis');
var jwt = require('jsonwebtoken');
var secret = 'check123';
var googleAuth = require('google-auth-library');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var googleAuth = require('google-auth-library');
// function authorize(credentials, callback) {
// var clientSecret = credentials.installed.client_secret;
// var clientId = credentials.installed.client_id;
// var redirectUrl = credentials.installed.redirect_uris[0];
// var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// // Check if we have previously stored a token.
// fs.readFile(TOKEN_PATH, function(err, token) {
// if (err) {
// getNewToken(oauth2Client, callback);
// } else {
// oauth2Client.credentials = JSON.parse(token);
// callback(oauth2Client);
// }
// });
// }
//mongoose.connect('mongodb://localhost:27017/test');
var auth = new googleAuth();
var clientSecret = '4etHKG0Hhj84bKCBPr2YmaC-';
var clientId = '655984940226-dqfpncns14b1uih73i7fpmot9hd16m2l.apps.googleusercontent.com';
var redirectUrl = 'http://localhost:8000/auth/google/callback';
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
//console.log(auth);
module.exports = function(hwRouter,passport){
hwRouter.post('/homeworks', function(req, res){
var homework = new Homework();
homework.summary = req.body.summary;
homework.description = req.body.description;
homework.startDate = req.body.startDate;
homework.endDate = req.body.endDate;
if(req.body.summary == null || req.body.summary == '' || req.body.description == null || req.body.description == '' || req.body.startDate == null || req.body.startDate == '' || req.body.endDate == null || req.body.endDate == ''){
res.send("Ensure all fields were provided!");
}
else{
homework.save(function(err){
if(err){
res.send('Homework already exists!');
}
else{
res.send('Homework created successfully!');
}
});
}
})
var calendar = google.calendar('v3');
hwRouter.get('/retrieveHW/:summary', function(req,res){
Homework.find({},function(err,hwData){
console.log(hwData);
var event = {
'summary': 'Google I/O 2015',
'location': '800 Howard St., San Francisco, CA 94103',
'description': 'A chance to hear more about Google\'s developer products.',
'start': {
'dateTime': '2015-05-28T09:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'end': {
'dateTime': '2015-05-28T17:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'recurrence': [
'RRULE:FREQ=DAILY;COUNT=2'
],
'attendees': [
{'email': 'lpage#example.com'},
{'email': 'sbrin#example.com'},
],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
};
console.log(auth)
calendar.events.insert({
auth: auth,
calendarId: 'primary',
resource: event,
}, function(err, event) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log('Event created: %s', event.htmlLink);
});
res.json({success: true, message: "successfull retrieved the homework!"});
});
})
return hwRouter;
}
As you can see Ive tried using some of the code that the goog api has provided just to make sure I can connect to it. The part my code gets stuck is I believe when I pass it the auth: auth in the calendar.event.create portion. it gives me the error: authClient.request is not a function. any advice would help thanks!

Try following the JavaScript sample:
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listUpcomingEvents();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
In this code, after the initClient() runs, the gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); listens for any state changes. updateSigninStatus function handles if initClient() successfully logged in or not. If yes, it call the listUpcomingEvents() function, in your case you will call the create event function.
Here is a related SO post that can help you with a JS client library code implementation.
Hope this helps.

Related

AWS Cognito: Missing credentials in config

If a user logs in, I'm checking if the user has the required policies for IoT, if not, i'm attaching it.
This works fine, if i'm logging in for the first time.
Now when I'm logging out, and try to login with a different user, for some reason the credentials are missing, and when i'm refreshing the page, its working again....
window.login = function() {
var shadowsRegistered = false;
AWSCognito.config.region = AWSConfiguration.region;
AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: AWSConfiguration.IdPoolId
});
var authenticationData = {
Username : document.getElementById("benutzername").value,
Password : document.getElementById("passwort").value
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId : AWSConfiguration.UserPoolId,
ClientId : AWSConfiguration.ClientAppId
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : document.getElementById("benutzername").value,
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
AWS.config.region = AWSConfiguration.region;
var auth_params = {
IdentityPoolId: AWSConfiguration.IdPoolId,
Logins : {
'cognito-idp.eu-central-1.amazonaws.com/eu-central-XXXX' : result.getIdToken().getJwtToken()
}
};
AWS.config.credentials = new AWS.CognitoIdentityCredentials(auth_params);
var cognitoIdentity = new AWS.CognitoIdentity();
cognitoIdentity.getId(auth_params, function(err, data) {
if (err) {
cognitoId = AWS.config.credentials.identityId;
}
else{
cognitoId = data.IdentityId;
}
var iot = new AWS.Iot();
iot.listPrincipalPolicies({principal: cognitoId}, function(err, data) {
if (err) {
console.log(err, err.stack); //ERROR on 2nd login
}
else{
// not related, works on the first login..
The Error I'm receiving:
CredentialsError: Missing credentials in config
I fixed it by myself. You need to clear the cached credentials.
$('#logout').click(function() {
currentUser = userPool.getCurrentUser();
currentUser.signOut();
AWS.config.credentials.clearCachedId();
AWS.config.credentials = new AWS.CognitoIdentityCredentials({});
location.reload();
});

Function not running on time

I'm trying to create a metrics dashboard by running a nodejs application on a raspberry pi that will be attached to a large monitor.
The application queries a SQL server every hour on the hour. When I run it on my mac it works great, but when I run this on the raspberry, it seems to run once or twice, then stops. I have disabled screensavers on the raspberry but I'm not sure how to debug this. I'll include the full code since I'm not sure if it's the tick() function itself or something else...
"use strict";
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var pg = require('pg');
const config = {
user: '<redacted>',
database: '<redacted>',
password: '<redacted>',
host: '<redacted>',
port: 5432,
max: 10,
idleTimeoutMillis: 5000,
};
const pool = new pg.Pool(config);
const spreadsheetId = '<this my internal sheet>'; // fulfillment kpis
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
const TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
const TOKEN_PATH = TOKEN_DIR + 'olr-test.json';
// Load client secrets from a local file.
fs.readFile('secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Sheets API.
authorize(JSON.parse(content), begin); // <---- LOOK HERE...WHERE IT REALLY BEGINS...I THINK
});
/**
* 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) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function (err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = 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 to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function (code) {
rl.close();
oauth2Client.getToken(code, function (err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
// Let's get the information out of xTuple now...
function begin(auth) {
// Promise function to return results from SQL query passed as an argument
function getResults(passedQuery) {
return new Promise((resolve, reject) => {
pool.connect((err, client, done) => {
var sql = client.query(passedQuery);
sql.on('row', (row, result) => {
result.addRow(row);
});
sql.on('end', (result) => {
var rightNow = timeStamp();
// console.log('Query finished at %s', rightNow);
resolve(result.rows);
});
done(err);
if (err) {
return console.error('error running query', err);
}
});
});
pool.on('error', (err, client) => {
console.error('idle client error', err.message, err.stack);
});
}
function convertArray(sqlObj) {
return new Promise((resolve, reject) => {
var result = [];
if (sqlObj.length > 0) {
var order = Object.keys(sqlObj[0]);
var result = sqlObj.map((row) => {
return order.map((col) => {
return row[col];
});
});
}
result[0].push(timeStamp());
resolve(result);
});
}
function appendSheet (value) {
return new Promise((resolve, reject) => {
var sheets = google.sheets('v4');
var options = {
auth: auth,
spreadsheetId: spreadsheetId,
range: "Sales ABPH!A1:B",
valueInputOption: "USER_ENTERED",
resource: {
range: "Sales ABPH!A1:B",
majorDimension: "ROWS",
values: value,
}
}
// console.log(options);
sheets.spreadsheets.values.append(options, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
function fixFormats(id) {
return new Promise((resolve, reject) => {
var sheets = google.sheets('v4');
var options = {
auth: auth,
spreadsheetId: spreadsheetId,
resource: {
requests: [{
repeatCell: {
fields: "userEnteredFormat.numberFormat",
range: {
sheetId: id,
startColumnIndex: 0, // inclusive
endColumnIndex: 1, // exclusive...meaning this counts UP TO column 4 but NOT 5
},
cell: {
userEnteredFormat: {
numberFormat: {
type: "CURRENCY",
pattern: "\"$\"#,##0.00",
}
}
}
}
}],
}
}
sheets.spreadsheets.batchUpdate(options, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
function timeStamp() {
var now = new Date();
var date = [now.getMonth() + 1, now.getDate()];
var time = [now.getHours(),now.getMinutes(),now.getSeconds()];
var suffix = (time[0] < 12) ? "AM" : "PM";
time[0] = (time[0] < 12) ? time[0] : time[0] - 12;
time[0] = time[0] || 12;
for (var i = 1; i < 3; i++) {
if (time[i] < 10) {
time[i] = "0" + time[i];
}
}
return date.join("/") + " " + time.join(":") + " " + suffix;
}
function insertRow() {
return new Promise((resolve, reject) => {
var sheets = google.sheets('v4');
var options = {
auth: auth,
spreadsheetId: spreadsheetId,
resource: {
requests: [{
insertRange: {
range: {
sheetId: 1769404692,
startRowIndex: 1,
endRowIndex: 2,
startColumnIndex: 1,
endColumnIndex: 4
},
shiftDimension: "ROWS",
}
}],
}
}
sheets.spreadsheets.batchUpdate(options, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
function update() {
getResults(`
select formatMoney(sum(qry.total)) as \"Booked\"
FROM cohead c
LEFT OUTER JOIN
(SELECT coitem_cohead_id, SUM(coitem_qtyord*coitem_price) as total
FROM coitem
WHERE coitem_status NOT IN (\'X\')
GROUP BY coitem_cohead_id) as qry
ON (c.cohead_id=qry.coitem_cohead_id)
WHERE (extract(DAY FROM c.cohead_orderdate) = extract(DAY from current_date) AND extract(MONTH from c.cohead_orderdate) = extract(MONTH from current_date) AND extract(YEAR from c.cohead_orderdate) = extract(YEAR from current_date))
`)
.then((sqlObj) => {
insertRow();
return convertArray(sqlObj);
})
.then((results) => {
console.log(results);
return appendSheet(results);
})
.then((fixMe) => {
fixFormats('1769404692');
})
.catch((error) => {
console.log('Something went wrong...\n%s', error);
});
tick();
}
function tick(force) {
var d = new Date();
var min = d.getMinutes();
var sec = d.getSeconds();
var hr = d.getHours();
if (force || (min == '0' && sec == '0') && (hr >= 7 || hr <= 19))
update();
else
setTimeout(update, (60 * (60 - min) + (60 - sec)) * 1000);
}
tick(true);
}
I'm running it with nodemon to monitor for changes in the script file and restart if found.
My hunch is that somehow the raspberry is going into a sort of "sleep" mode but still outputs video.
EDIT: I thought I found a solution here: https://raspberrypi.stackexchange.com/questions/4773/raspberry-pi-sleep-mode-how-to-avoid/56046#56046
I've turned off power_save on for wlan0 (which is what I'm using for my LAN connection) and then rebooted. Same problem, but checking the power_save option again looks like it was turned back on.
I've just tested turn it off, rebooting, and immediately checking again it's re-enabled.
EDIT #2: Confirming that if I set power_save off on wlan0 and do not reboot, it still does not run the loop at the appropriate timeout. I waited 30 minutes before restarting it and it ran fine but that's because of the tick() is forced the first time it runs.

javasctipt - asynchronous issue for return value

I am working in MEAN STACK application and i want to set mail's parameters dynamic.
route.js
var Helper = require("../helper.js");
router
.route("/api/user/registration")
.POST(function (req, res) {
//after user insert send mail
Helper.sendCustomEmail(params, function (error, response) {
if (error) {
console.log("Mail : " + error);
res.json({"status": 0, "error": {"other": "Oops! something went wrong, please try again later"}});
} else {
console.log("Message sent");
res.json({status: 1, message: 'Thank you for registration. You will get verification email soon', token: res.locals.user.jwttoken});
}
});
});
Helper.js
exports.sendCustomEmail = function(params, callback) {
//Include nodejs mailer and smtp module
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
//read header email template
var headerHtml = params.fs.readFileSync(basePath + "emailHeader.html").toString();
//read footer email template
var footerHtml = params.fs.readFileSync(basePath + "emailFooter.html").toString();
//Your dynamic template html only
var dynamicMessage = params.message;
var message = headerHtml + dynamicMessage + footerHtml;
message = message.replace(/##DOMAIN_URL##/g, "http://" + params.domainUrl);
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
host: this.getSiteSetting("SMTP_HOST"),
secure: true,
auth: {
user: this.getSiteSetting("SMTP_USER"),
pass: this.getSiteSetting("SMTP_PSSSWORD")
},
tls: {
rejectUnauthorized: false
}
}));
transporter.sendMail({
from: this.getSiteSetting("SMTP_FROM"),
to: params.to, // receiver
subject: params.subject,
html: message // body
}, function(error, response) { //callback
callback(error, response);
});
};
var SiteSetting = require('../models/siteSetting');
exports.getSiteSetting = function($keyword) {
if ($keyword !== undefined && $keyword !== null && $keyword !== "") {
SiteSetting.findOne({setting_key : $keyword},function(err,siteSetting){
if(err){
return null;
}else{
if(siteSetting !== null){
console.log(siteSetting.setting_value);
return siteSetting.setting_value;
}
}
});
}else{
return null;
}
};
dependencies
"express" => "version": "4.13.4",
"mongoose" => "version": "4.4.4",
"mongodb" => "version": "2.4.9",
"OS" => "ubuntu 14.04 lts 32bit",
from the following code SiteSetting function console.log print properly but before return mail send error occur.
Please give me a proper guideline for this code.
This can be solved as bellow.
exports.sendCustomEmail = function(params, callback) {
//Include nodejs mailer and smtp module
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
//read header email template
var headerHtml = fs.readFileSync(basePath + "app/client/views/layout/emailTemplates/emailHeader.html").toString();
//read footer email template
var footerHtml = fs.readFileSync(basePath + "app/client/views/layout/emailTemplates/emailFooter.html").toString();
//Your dynamic template html only
var dynamicMessage = params.message;
var message = headerHtml + dynamicMessage + footerHtml;
message = message.replace(/##DOMAIN_URL##/g, "http://" + params.domainUrl);
var host = null;
var user = null;
var pass = null;
var from = null;
this.getSiteSetting("SMTP_HOST", function(res) {
host = res;
setParams();
});
this.getSiteSetting("SMTP_USER", function(res) {
user = res;
setParams();
});
this.getSiteSetting("SMTP_PASS", function(res) {
pass = res;
setParams();
});
this.getSiteSetting("MAIL_FROM", function(res) {
from = res;
setParams();
});
var setParams = function() {
if (host !== null && user !== null && pass !== null && from !== null) {
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
host: host,
//port: 25,
//port: 465,
secure: true,
auth: {
user: user,
pass: pass
},
tls: {
rejectUnauthorized: false
}
}));
transporter.sendMail({
from: from,
to: params.to, // receiver
subject: params.subject,
html: message // body
}, function(error, response) { //callback
callback(error, response);
});
}
};
}
var SiteSetting = require('../models/siteSetting');
exports.getSiteSetting = function(keyword, callback) {
if (keyword !== undefined && keyword !== null && keyword !== "") {
SiteSetting.findOne({ setting_key: keyword }, function(err, siteSetting) {
if (err) {
callback(null);
} else {
if (siteSetting !== null) {
//console.log(siteSetting.setting_value);
callback(siteSetting.setting_value);
}else{
callback(null);
}
}
});
} else {
callback(null);
}
};

createRecord not defined error (Firebase + Ember.js)

I was wondering if anyone could point me in the right direction and help me fix this error I'm getting when I attempt to add a user with my Ember.js model after created a user with Firebases createUser method.
To be more specific here is the error I'm getting: Uncaught TypeError: Cannot read property 'createRecord' of undefined
App.SignUpController = Ember.Controller.extend({
needs: ['sign-in'],
needs: ['application'],
userSignedIn: false,
actions: {
signMeUp: function() {
var state = false;
var controllerContext = this;
// Create firebase user
ref.createUser({
email : this.get('email'),
password : this.get('password'),
}, function(error, user) {
if (error === null) {
console.log('User created with id', user.uid);
state = true;
controllerContext.set('userSignedIn', state);
console.log("State from sign-up page: "+ state);
console.log("Testing user.uid inside: "+user.uid);
var fbid = user.id;
controllerContext.set('user id', user.uid);
var newUser = this.store.createRecord('user', {
id: fbid,
email: this.get('email'),
password: this.get('password'),
});
newUser.save();
} else {
console.log("Error creating account:", error);
}
}); // End createUser
this.transitionToRoute('letters');
}
}
});
UPDATE: Here is a (very hacky) solution I came up with after a day of JS plumbing.
App.SignUpController = Ember.Controller.extend({
needs: ['sign-in'],
needs: ['application'],
userSignedIn: false,
thisUserID: '',
actions: {
signMeUp: function() {
var state = false;
var controllerContext = this;
// Create firebase user
function authWithPassCallback(userObj, user){
console.log("authWithPassCallback user.uid is: "+user.uid);
return user.uid
}
function createUserAndLogin(userObj, callback) {
ref.createUser(userObj, function(error, user) {
if (error === null) {
console.log("User created successfully");
controllerContext.set('thisUserID', user.uid);
return callback(userObj, user);
} else {
console.log("Error creating user:", error);
}
});
}
var userAndPass = {
email: this.get('email'),
password: this.get('password')}
var fbPayload = createUserAndLogin(userAndPass, authWithPassCallback);
setTimeout(function () {
console.log("FB load: "+ controllerContext.get('thisUserID'));
var newUser = controllerContext.store.createRecord('user', {
id: controllerContext.get('thisUserID'),
email: controllerContext.get("email"),
password: controllerContext.get("password"),
});
newUser.save();
controllerContext.transitionToRoute('letters');
}, 1000);
console.log(controllerContext.get('thisUserID'));
}
}
});
I'm assuming the error is occurring at newUser = this.store.createRecord - at this point in your code this is no longer referring to the controller. You will need to use controllerContext.store.createRecord.
you probably just lost the context here. this doesn't refer to the controller, you're in the error function.
There are two ways of fixing that. First is to bind the function to the controller's this:
ref.createUser({
// ...
}, function(error, user) {
var newUser = this.store.createRecord('user', {/*...*/});
// ...
}.bind(this));
or to reuse the controllerContext variable:
ref.createUser({
// ...
}, function(error, user) {
// ...
var newUser = controllerContext.store.createRecord('user', {/*...*/});
});

How to manage User docs permission setting using Google Drive Api? (Javascript)

I am new to Google Drive SDK.
I followed
https://developers.google.com/drive/v2/reference/permissions/insert?hl=en
this examples where they show how to change permissions for file. I'm able run this code but my problem is that i want to change permission of more than one file.i tried some loop for user and inside it fileId loop but because javascript not wait for child function complete(asynchronous calling function), it wont work for me
Please Help me
Following is my Code...
i get very confused in it please help me to sort out this
This the Code Please Correct me here Please
var scopes = 'https://www.googleapis.com/auth/drive';
// Use a button to handle authentication the first time.
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
//window.setTimeout(checkAuth,1);
checkAuth();
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
var fileID = new Array();
var email = new Array();
fileID[0] = "1fEYDfB9owJAdxQ7lI0";
fileID[1] = "1YYcKn1ZsiPYWA";
email[0] = "email1#email.com";
email[1] = "email2#email.com";
email[2] = "email3#email.com";
gapi.client.load('drive', 'v2', function() {
for(var i=0;i<email.length;i++)
{
var body = {
'value': email[i],
'type': "user",
'role': "reader"
};
for(var j=0;j<fileID.length;j++)
{
var fileid = fileID[j];
excuteRequest(body, fileid, function() {
var request = gapi.client.drive.permissions.insert({
'fileId': fileid,
'resource': body
});
request.execute(function(resp) { });
});
}
}
});
}
function excuteRequest(param1, param2, callback) {
if (callback && typeof(callback) === "function") {
callback();
}
}
Use a flow control library, similar to async: https://github.com/caolan/async
var files = ["id1", "id2", "id3"];
async.each(files, function(fileId, callback){
gapi.client.drive.permissions.insert({
'fileId': fileId,
'resource': body
}).execute(function(response) {
callback(null, response);
});
}, function(err){
if (!err) { console.log('done.'); }
});

Categories