Reputation: 1263
I am trying to list my files on Google Drive.
I've been attempting to get this done for weeks without success. I've been trying PHP and now I've moved into Javascript to see if I can get any example to work.
This is the example I'm working off of
http://runnable.com/UTlPMF-f2W1TAAAj/list-files-on-google-drive
So I've uploaded my files, enabled the Drive API on my Google console, have the correct scope, have a client secret, client id
I am testing on localhost with my own account.
So far the main html page loads, I click on the login button, then there is a blank popup, and nothing else, no errors.
Here are my files
oauth.js
var request = require('request')
, qs = require('qs')
, callbackURL = 'http://'+process.env.OPENSHIFT_APP_DNS+'/callback';
var state = ''
, access_token = ''
, token_type = ''
, expires = '';
function login(req, res) {
state = Math.floor(Math.random() * 1e19);
exports.state = state;
var params = {
response_type: 'code',
client_id: 'myclientid',
redirect_uri: callbackURL,
state: state,
display: 'popup',
scope: 'https://www.googleapis.com/auth/drive' // specify the "Google Drive" scope
};
params = qs.stringify(params);
res.writeHead(200, {'Content-type': 'text/plain'});
res.end('https://accounts.google.com/o/oauth2/auth?'+params);
}
function callback(req, res) {
var code = req.query.code
, cb_state = req.query.state
, error = req.query.error;
if (state == cb_state) {
if (code !== undefined) {
var params = {
code: code,
client_id: 'myclientid',
client_secret: 'myclientsecret',
redirect_uri: callbackURL,
grant_type: 'authorization_code'
};
request.post('https://accounts.google.com/o/oauth2/token', {form:params}, function(err, resp, body) {
var results = JSON.parse(body);
exports.access_token = access_token = results.access_token;
exports.token_type = token_type = results.token_type;
exports.expires = expires = results.expires_in;
console.log("Connected to Google");
// close the popup
var output = '<html><head></head><body onload="window.close();">Close this window</body></html>';
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(output);
});
} else {
console.error('Code is undefined: '+code);
console.error('Error: '+ error);
}
} else {
console.log('Mismatch with variable "state". Redirecting to /');
res.redirect('/');
}
}
exports.login = login;
exports.callback = callback;
server.js
var express = require('express')
, request = require('request')
, oauth = require('./oauth')
, app = express();
// Setup middleware
app.use(express.static(__dirname));
// List out file that are in your Google Drive
app.get('/list', function(req, res) {
// Check to see if user has an access_token first
if (oauth.access_token) {
// URL endpoint and params needed to make the API call
var url = 'https://www.googleapis.com/drive/v2/files';
var params = {
access_token: oauth.access_token
};
// Send the API request
request.get({url:url, qs:params}, function(err, resp, body) {
// Handle any errors that may occur
if (err) return console.error("Error occured: ", err);
var list = JSON.parse(body);
if (list.error) return console.error("Error returned from Google: ", list.error);
// Generate output
if (list.items && list.items.length > 0) {
var file = ''
, iconLink = ''
, link = ''
, output = '<h1>Your Google Drive</h1><ul>';
for(var i=0; i<list.items.length; i++) {
file = list.items[i].title;
iconLink = list.items[i].iconLink;
link = list.items[i].alternateLink;
output += '<li style="list-style- image:url('+iconLink+');"><a href="'+link+'" target="_blank">'+file+'</a></li>';
}
output += '</ul>';
//Send output as response
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(output);
} else { // Alternate output if no files exist on Drive
console.log('Could not retrieve any items.');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<p>Your drive appears to be empty.</p>')
}
});
// If no access_token was found, start the OAuth flow
} else {
console.log("Could not determine if user was authed. Redirecting to /");
res.redirect('/');
}
});
// Handle OAuth Routes
app.get('/login', oauth.login);
app.get('/callback', oauth.callback);
app.listen(80);
index.html
<html>
<head>
<title>Google server-side OAuth v2 Example</title>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var url = '';
var b = '';
$(document).ready(function() {
$.get('/login', function(data) {
url = data;
});
var interval = window.setInterval((function() {
if (b.closed) {
window.clearInterval(interval);
window.location = './list';
}
}),1000);
});
</script>
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<h1 id="header">Google Drive: Retrieve list of files</h1>
<p>Get started by logging into your Google account using the button below</p>
<button id="login" onclick="b = window.open(url, 'window', 'status=0,menubar=0,resizable=1,width=500,height=800;')">Login to Google</button>
</body>
</html>
package.json
{
"name": "facebook-oauthv2-js-sdk-example",
"version": "0.0.1",
"description": "A sample code project using Google to perform server-side OAuth v2",
"dependencies": {
"express": "*",
"qs": "*",
"request": "*"
},
"engine": "node 0.6.x"
}
style.css
body{
margin: 0;
padding: 10px;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}
h1{
padding: 10px 0;
font-size: 18px;
font-weight: normal;
color: #444;
border-bottom: 1px solid #ccc;
margin: 0 0 20px;
text-transform:capitalize;
}
Any thoughts on how to list my files?
Upvotes: 1
Views: 663
Reputation: 922
First, I see you are using openshift env variable that might be dynamic or not same as you registered on api console.
Second, you are not saving the refresh_token that you get first time you allow access on consent screen, maybe the access_token expired so you have refresh it using that refresh_token
However, I recommend using google-api-nodejs-client for accessing google api, its official google apis client library.
If you use this library then you don't need to worry about refreshing expired access token and you get nice clean syntex through library apis and caching.
I blogged about it at http://manan-vaghasiya.in/post/integrating-your-node.js-app-with-google-apis
Upvotes: 1