Skip to content

Instantly share code, notes, and snippets.

@error404as
Last active May 15, 2016 20:36
Show Gist options
  • Save error404as/c633f73bb99f31863369 to your computer and use it in GitHub Desktop.
Save error404as/c633f73bb99f31863369 to your computer and use it in GitHub Desktop.
Save JSON to Google Drive. Check if file exists (by filename). Update existing file. Get JSON from Google Drive file having file ID.
<!--
Example shows functionality of:
- saving JSON (appState) to Google Drive
- updating Google Drive file if file with such filename exists
- retrieving saved data from file with ID saved in localStogare (picker may be used instead: https://developers.google.com/picker/docs/ )
Used google tutorial examples:
https://developers.google.com/drive/web/quickstart/quickstart-js
https://developers.google.com/drive/v2/reference/files/get
https://developers.google.com/drive/v2/reference/files/update
-->
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<script type="text/javascript">
var CLIENT_ID = '1027793413486-vhgujkanqqk216p7pfp083dvkmb7l6e5.apps.googleusercontent.com';
var SCOPES = 'https://www.googleapis.com/auth/drive';
var appState = { number: 12, text: 'hello' }; // sample app data to be saved
var appStateFileName = '-app-state.txt'; // file name append
var stName = 'agd_file'; // localStorage field for default source file id and title
var contentType = 'application/json';
var metadata = {}; // file metadata for creating/updating
var fileDefault = {}; // default source file with data
function handleClientLoad() {
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authButton = document.getElementById('authorizeButton');
var actionBlock = document.getElementById('actions');
authButton.style.display = 'none';
actionBlock.style.display = 'none';
if (authResult && !authResult.error) {
gapi.client.load('drive', 'v2', function(){
getStogareData();
actionBlock.style.display = 'block';
});
} else {
authButton.style.display = 'block';
}
}
function saveData() {
metadata = getFileMetadata();
checkFileExists(metadata.title, saveDataHandle);
}
function saveDataHandle(fileExists) {
if(fileExists){
console.log('File already exists...');
updateFile(fileExists);
} else {
console.log('Will create a new file...');
createFile();
}
}
function getFileMetadata() {
return {
'title': document.getElementById('fname').value+appStateFileName,
'mimeType': contentType
}
}
function createFile() {
console.log('Creating a new file ('+metadata.title+') with data:');
console.log(appState);
const boundary = '-------314159265358979323846264';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var base64Data = btoa(JSON.stringify(appState));
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
request.execute(function(res) {
console.log('New file created! Fileinfo:');
console.log(res);
fileDefault.id = res.id;
fileDefault.title = res.title;
setStogareData();
});
}
function updateFile(fileId) {
if(!fileId){ return; }
console.log('Updating file ('+metadata.title+') with data:');
console.log(appState);
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var base64Data = btoa(JSON.stringify(appState));
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files/' + fileId,
'method': 'PUT',
'params': {'uploadType': 'multipart', 'alt': 'json'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
request.execute(function(res){
console.log('File successfully updated!');
});
}
function getStogareData(){
var elemDef = localStorage.getItem(stName);
if(elemDef){
fileDefault = JSON.parse(elemDef);
}
}
function setStogareData(){
if(fileDefault.id){
localStorage.setItem(stName, JSON.stringify(fileDefault));
} else {
localStorage.removeItem(stName);
}
}
function getFile() {
if(!fileDefault.id){ return false; }
console.log('We are loading data...')
var fileId = fileDefault.id;
var request = gapi.client.drive.files.get({
'fileId': fileId
});
request.execute(function(resp) {
downloadFile(resp);
});
}
function downloadFile(file) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
console.log('Data downloaded:')
appState = JSON.parse(xhr.responseText);
console.log(appState);
};
xhr.onerror = function() {
console.log('XHR error!');
};
xhr.send();
} else {
console.log('Can\'t download...');
}
}
function checkFileExists(fname, callback){
console.log('Looking for: '+fname)
var req = gapi.client.drive.files.list({q: "title='"+fname+"'"});
req.execute(function(r){
console.log(r);
var len = r.items ? r.items.length : 0;
if(r.items && r.items.length && r.items[0].id){
callback(r.items[0].id);
} else {
callback();
}
});
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body>
<input type="button" id="authorizeButton" onclick="checkAuth()" value="Authorize" style="display:none;" />
<div id="actions" style="display:none;">
<input type="button" onclick="saveData()" value="Save Data" /> to file:
<input type="text" id="fname" value="appState-filename-example">
<script type="text/javascript">document.write(appStateFileName)</script> <br> <br>
<input type="button" onclick="getFile()" value="Get Data From Drive" />
<input type="button" onclick="console.log(appState)" value="console.log(appState)" />
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment