Skip to content

Instantly share code, notes, and snippets.

@camman3d
Created June 29, 2013 04:05
Show Gist options
  • Save camman3d/5889687 to your computer and use it in GitHub Desktop.
Save camman3d/5889687 to your computer and use it in GitHub Desktop.
Google API and Google Drive JavaScript helpers. See my blog post for more information. http://joshmonson.com/blog/2013/06/27/google-drive/
var GoogleAPILoader = (function() {
"use strict";
function GoogleAPILoader(config) {
this.clientId = config.clientId;
this.apiKey = config.apiKey;
this.scopes = config.scopes;
this.clientLibraries = config.clientLibraries || [];
}
/**
* Step 1: Load the library
* @param callback {Function}
*/
function loadLibrary(callback) {
$.getScript("https://apis.google.com/js/client.js", function () {
// Keep checking until the library is loaded
(function checkIfLoaded() {
if (gapi.client)
callback();
else
window.setTimeout(checkIfLoaded, 10);
})();
});
}
/**
* Step 2: Set the API key
*/
function setApiKey() {
gapi.client.setApiKey(this.apiKey);
}
/**
* Step 3: Load the client libraries
* @param callback {Function}
*/
function loadClientLibraries(callback) {
// Asynchronously load all the libraries
var count = 0,
_this = this;
this.clientLibraries.forEach(function(library) {
gapi.client.load(library.name, library.version, function () {
if (++count === _this.clientLibraries.length) {
callback();
}
});
});
// Move on if there are no library to load
if (!this.clientLibraries || !this.clientLibraries.length) {
callback();
}
}
GoogleAPILoader.prototype.load = function (callback) {
var _this = this;
loadLibrary(function () {
setApiKey.call(_this);
loadClientLibraries.call(_this, callback);
});
};
/**
* Step 4a: Get authorization from the user.
* @param success {Function} A success callback
* @param error {Function} A error/access denied callback
*/
GoogleAPILoader.prototype.renewAuthorization = function (success, error) {
// Try to get authorization without a popup.
var params = {
client_id: this.clientId,
scope: this.scopes,
immediate: true
};
gapi.auth.authorize(params, function(authResult) {
// Check the results
if (authResult && !authResult.error) {
success && success();
} else {
error && error();
}
});
};
/**
* Step 4b: Get explicit authorization from the user.
* @param success {Function} A success callback
* @param error {Function} A error/access denied callback
*/
GoogleAPILoader.prototype.getAuthorization = function (success, error) {
// Get authorization from a popup.
var params = {
client_id: this.clientId,
scope: this.scopes,
immediate: false
};
gapi.auth.authorize(params, function(authResult) {
// Check the results
if (authResult && !authResult.error) {
success && success();
} else {
error && error();
}
});
};
return GoogleAPILoader;
})();
var GoogleDriveFileUploader = (function() {
"use strict";
function uploadMultipart(body, boundary, callback) {
var request = gapi.client.request({
'path': '/upload/drive/v2/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': body});
if (!callback) {
callback = function(file) {
console.log(file)
};
}
request.execute(callback);
}
function generateMultipartData(data, metadata) {
var boundary = '-------314159265358979323846';
var delimiter = "\r\n--" + boundary + "\r\n";
var close_delim = "\r\n--" + boundary + "--";
var base64Data = btoa(data);
var body = delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + metadata.mimeType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
return {
body: body,
boundary: boundary
};
}
return {
uploadFile: function (file, metadata, callback) {
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
// Generate the multipart data (body and boundary)
var data = generateMultipartData(reader.result, metadata);
// Upload the file
uploadMultipart(data.body, data.boundary, callback);
};
},
uploadString: function (string, metadata, callback) {
// Generate the multipart data (body and boundary)
var data = generateMultipartData(string, metadata);
// Upload the string
uploadMultipart(data.body, data.boundary, callback);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment