Firefox OS app get contacts from gmail - javascript

I'm gonna develop a firefox os app and I need to get/modify/create contacts from gmail; obviously I'd need a js script to do that but every example I've got by gmail/stack overflow/google didn't work to me... could anyone of you guide me to retrieve the contact list?
The best example I've found is this:
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<script type="text/javascript">
var clientId = 'my client id';
var apiKey = 'my api';
var scopes = 'https://www.googleapis.com/auth/plus.me';
function handleClientLoad() {
// Step 2: Reference the API key
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
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) {
// Step 3: get authorization to use private data
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() {
// Step 4: Load the Google+ API
gapi.client.load('plus', 'v1', function() {
// Step 5: Assemble the API request
var request = gapi.client.plus.people.get({
'userId': 'me'
});
// Step 6: Execute the API request
request.execute(function(resp) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = resp.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(resp.displayName));
document.getElementById('content').appendChild(heading);
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
The problem is that this code never enters the handleAuthResult(authResult) function and I get no js errors...

Related

How do I download a Google Sheet with Google Picker all in JavaScript?

I'm trying to implement Google Picker and the Google Drive API in JavaScript on my website. Currently, I use a PHP script to fetch Google Drive documents, but it's using restricted scopes and I want to remove restricted scopes from my application.
First, I got the Google Picker quickstart code working. I tried to add a Google Drive get using the access token that I fetched in the Google Picker code. Google Drive code comes over in the client.js, right? Is the access token used in api.js compatible with the access token used for client.js?
I found an old Gist from six years ago and tried to integrate and update it. Here's my code right now. The gapi.client.drive.files.get fails to get the file.
// Scope to use to access user's photos.
var scope = 'https://www.googleapis.com/auth/drive.file';
var pickerApiLoaded = false;
var driveApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth2', onAuthApiLoad);
gapi.load('picker', onPickerApiLoad);
}
function onClientLoad() {
gapi.client.setApiKey(developerKey);
gapi.client.load('drive', 'v2', onDriveApiLoad);
}
function onAuthApiLoad() {
var authBtn = document.getElementById('auth');
authBtn.disabled = false;
authBtn.addEventListener('click', function() {
gapi.auth2.init({ client_id: clientId }).then(function(googleAuth) {
googleAuth.signIn({ scope: scope }).then(function(result) {
handleAuthResult(result.getAuthResponse());
})
})
});
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function onDriveApiLoad() {
driveApiLoaded = true;
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.DocsView(google.picker.ViewId.SPREADSHEETS);
//view.setMimeTypes("text/csv");
//view.setMode(google.picker.DocsViewMode.LIST);
view.setQuery(jQuery('[updateparam="name"]').val());
var picker = new google.picker.PickerBuilder().
//addView(google.picker.ViewId.DOCS).
addView(view).
setInitialView(view).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var fileId = doc[google.picker.Document.ID];
jQuery('[updateparam="googleDriveFileId"]').val(fileId);
//if (driveApiLoaded) {
var request = gapi.client.drive.files.get({
'fileId': fileId
});
request.execute(function(file) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + oauthToken);
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.onerror = function() {
warningMessage.displayMessage('Failed to download Google Drive document ' + fileId);
};
});
//} else {
// warningMessage.displayMessage('Google Drive API has not been loaded.');
//}
}
// Triggers before Picker is shown
// else {
// warningMessage.displayMessage('No Google Drive document selected.');
//}
}
And my script tags:
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?key=KEY"></script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
The problem is when you try to retrieve the downloadUrl attribute in file.downloadUrl, which is a field that doesn’t exist anymore in the Drive API version 3 (It was in the version 2), check v2 [1] and v3 [2].
Instead, you should use the webContentLink attribute to download the file, which is available for files with binary content as images, pdf, etc, but not for google docs and sheets (it’s only available the webViewLink attribute which is the url to the file) [2]. For these cases (docs and sheets), you can implement the import method which works for convert google documents and returns the file object [3]. The import request would be like this:
var request = gapi.client.drive.files.import({ 'fileId': fileId, 'mimeType': mimeType });
With mimeType for the target document you want (pdf, txt, etc). Then, inside the callback, access the attribute using file.webContentLink as with the other cases.
[1] https://developers.google.com/drive/api/v2/reference/files
[2] https://developers.google.com/drive/api/v3/reference/files
[3] https://developers.google.com/drive/api/v3/reference/files/export
Through trial and error, I discovered that in order to load both the Google Picker (client:auth2) and the Google Drive API (gapi.client), the Google Picker must be initialized with a callback, and then the Google Drive API is initialized with a Promise that must be chained. If the Promise is not chained, then it will be unresolved and will not work.
// Use the Google API Loader script to load the google.picker script.
function loadPicker() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
driveApiLoaded = true;
}
function onPickerApiLoad() {
pickerApiLoaded = true;
}
function askForClientAuthorization() {
gapi.load('client:auth2', function(_) {
window.gapi.client.init({
apiKey: developerKey,
clientId: clientId,
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"],
scope: 'https://www.googleapis.com/auth/drive.file'
})
.then(function(__) {
return gapi.client.drive.files.export({
'fileId': window.googleDriveFileId,
'mimeType': 'text/csv'
})
.then(function(file) {
// Client is authorized to access this file, do something with the file
})
.catch(function(e) {
gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
});
})
})
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
return true;
} else {
return false;
}
}
// Create and render a Picker object for searching images.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.DocsView(google.picker.ViewId.SPREADSHEETS);
view.setMode(google.picker.DocsViewMode.LIST);
view.setQuery(window.dataFeedName);
var picker = new google.picker.PickerBuilder()
.setAppId(appId)
.setOAuthToken(oauthToken)
.addView(view)
.setDeveloperKey(developerKey)
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
return picker;
}
}
// A simple callback implementation.
function pickerCallback(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
// Do work
}
}
With this code, it must check if the user is authorized for every execution.

gapi auth2 fails with cb=gapi.loaded_0:43 Uncaught [object Object] exception if user denies permission to access google account data

I am trying to make google plus login working for my website using gapi auth2 api.
The flow is like this:
User clicks on google+ button -> pop up to choose google account appears -> permission window (user allows/denies the permission to access account) -> I call my custom auth service using access_token provided by google -> login happens.
Everything else is working fine except for when user chooses the google account and then instead of allowing he clicks on 'Deny' button on permission window. In this case, I get the below exception:
I was expecting that when user denies the permission I will get a callback to my code from gapi but instead it fails.
Here is the code I wrote to do google+ login
gapi.client.setApiKey(config.apiKey);
var auth2 = gapi.auth2.getAuthInstance();
if (auth2 == undefined) {
auth2 = gapi.auth2.init({
client_id: config.clientId,
scope: config.scopes,
immediate: false
});
}
auth2.then(function() {
var options = new gapi.auth2.SigninOptionsBuilder();
options.setScope(config.scopes); // Set scopes
options.setPrompt('select_account consent'); // Get authorization from the user to access profile info
var signIn = gapi.auth2.getAuthInstance().signIn(options);
signIn.then(function() {
gapi.client.load('plus', 'v1', function() {
console.log("google plus api loaded.");
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
console.log(resp.displayName);
});
});
var authResult = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse();
if (authResult && !authResult.error) {
console.log("google auth success");
console.log(authResult.access_token);
var authService = new authServiceModel.authServiceResp({});
var formvalues = {};
formvalues.Method = 3;
formvalues.Source = 5;
formvalues.GoogleToken = authResult.access_token;
authService.fetch(formvalues);
} else {
if (authResult && authResult.error) {
console.error('Unable to sign in:', authResult.error);
}
console.log("google auth failed");
}
});
});
Here are the screenshots:
2.
3.
Click Deny.
Please look into the code and suggest what should I do to get a proper callback when 'Deny' button is clicked.
Thanks.

Access Multiple Google Calendars using Java Script - Google Calendar API

I have this code where I can get the event from my calendar.
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<button id="insert-button" style="visibility: hidden">Insert</button>
<script type="text/javascript">
// Enter a client ID for a web application from the Google Developer Console.
// The provided clientId will only work if the sample is run directly from
// https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
// In your Developer Console project, add a JavaScript origin that corresponds to the domain
// where you will be running the script.
var clientId = '823958590548-s5b4d4ngoj6tj2misdvrcdm3rt27jolr.apps.googleusercontent.com';
// Enter the API key from the Google Developer Console - to handle any unauthenticated
// requests in the code.
// The provided key works for this sample only when run from
// https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
// To use in your own application, replace this API key with your own.
var apiKey = 'AIzaSyDTqOkVPgBv5kCIqp5NXp7UwE0MKTjLmrU';
// To enter one or more authentication scopes, refer to the documentation for the API.
var scopes = 'https://www.googleapis.com/auth/calendar';
// Use a button to handle authentication the first time.
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
var insertButton = document.getElementById('insert-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
insertButton.style.visibility = '';
insertButton.onclick = handleInsertClick;
} else {
authorizeButton.style.visibility = '';
insertButton.style.visibility = 'hidden';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function handleInsertClick(event) {
makeInsertApiCall();
}
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'ashishpandit2312#gmail.com'
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
function makeInsertApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.insert({
"calendarId": "primary",
resource:{
"summary": "Meeting",
"location": "Somewhere",
"start": {
"dateTime": "2015-02-21T01:00:00.000-07:00"
},
"end": {
"dateTime": "2015-02-21T04:25:00.000-08:00"
}
}
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
console.dir(resp);
}
});
});
}
</script>
<script
src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<div id='content'>
<h1>Events</h1>
<ul id='events'></ul>
</div>
<p>Connecting to Google Calendar with the Javascript Library.</p>
</body>
</html>
I want to get the events from multiple Google Calendars. What changes should I make to make it work and access multiple calendars of different people?
If you want to access multiple calendars of different people, the best way is to create a service account (which will do all requests to API's on behalf of users). So, users are not prompted with consent screen for authentication for accessing their calendar. Here are the steps:
Create a service account and you as the admin for the domain.
Share all the calendars to this service account.
For the service account to access users data, follow this link for domain wide delegation.
Check this link for service account sample code in java.

Get all messages by label from gmail account

i want to create a reporting tool based on export from google gmail api.
so the main thing i want to do is to retrieve , get all inbox messages by labels from my account in gmail, and display it in custom structure in my custom ehtml document.
i want to do it with php or javascript.
I have made some researches in Google API, but couldn't understand how to start working, from where?
i think it would be nice if could get the JSON data from this urls
Labels
Messages
how can i do it with javascript, what js libs i need to include, how to work with google Api? I have never worked with it before, so can anybody show me some simple full example?
Here is a full example showing how to load the Google APIs Javascript client, load the gmail API, and call the two API methods to list labels and inbox messages. There are a lot of javascript code snippets in the Gmai lAPI docs for each API call, so you can combine the structure of the code below with whatever specific code snippet to achieve what you want.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<div id="content"></div>
<p>Test gmail API.</p>
<script type="text/javascript">
// Enter a client ID for a web application from the Google Developer Console.
// In your Developer Console project, add a JavaScript origin that corresponds to the domain
// where you will be running the script.
var clientId = 'YOUR_CLIENT_ID_HERE';
// To enter one or more authentication scopes, refer to the documentation for the API.
var scopes = 'https://www.googleapis.com/auth/gmail.readonly';
// Use a button to handle authentication the first time.
function handleClientLoad() {
window.setTimeout(checkAuth,1);
}
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() {
gapi.client.load('gmail', 'v1', function() {
listLabels();
listMessages();
});
}
/**
* Get all the Labels in the authenticated user's mailbox.
*/
function listLabels() {
var userId = "me";
var request = gapi.client.gmail.users.labels.list({
'userId': userId
});
request.execute(function(resp) {
var labels = resp.labels;
var output = ("<br>Query returned " + labels.length + " labels:<br>");
for(var i = 0; i < labels.length; i++) {
output += labels[i].name + "<br>";
}
document.getElementById("content").innerHTML += output;
});
}
/**
* Get all the message IDs in the authenticated user's inbox.
*/
function listMessages() {
var userId = "me";
var request = gapi.client.gmail.users.messages.list({
'userId': userId
});
request.execute(function(resp) {
var messages = resp.messages;
var output = "<br>Query returned " + messages.length + " messages:<br>";
for(var i = 0; i < messages.length; i++) {
output += messages[i].id + "<br>";
}
document.getElementById("content").innerHTML += output;
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</body>
</html>

Error: origin_mismatch when using Google calendar API with port 444

I am getting an error origin_mismatch message when I try to use the Google Calendar API through another site that uses a different port.
The code doesn't return an error when the API request is sent from http://original.domain.edu.
However, the code returns the above title error when the API request is sent from https://original.domain.edu:444 (which is the secure login port that the app uses).
I've added both https://original.domain.edu:444 and https://original.domain.edu to my OAuth client in my API console but the same error is still occurring. Can someone offer some help on this?
var exportCalendarToGoogle = function() {
var clientId = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
var scope = 'https://www.googleapis.com/auth/calendar';
var apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
var withGApi = function() {
console.log("gapi loaded");
setTimeout(function() {
gapi.client.setApiKey(apiKey);
gapi.auth.init(checkAuth);
}, 500);
}
var checkAuth = function() {
gapi.auth.authorize({client_id: clientId, scope: scope, immediate: false}, handleAuthResult);
}
var handleAuthResult = function(authResult) {
if(authResult) {
gapi.client.load("calendar", "v3", exportCalendar);
} else {
alert("Authentication failed: please enter correct login information.");
}
}
...
You need a server side file to act as a proxy/bridge to get around JS Origin issues.
eg: var scope = "https://original.domain.edu:444/proxy.php";
<?php
//proxy.php file
echo file_get_contents('https://www.googleapis.com/auth/calendar?' . http_build_query($_GET) );
?>

Categories