Stackedit/js/google-helper.js

579 lines
16 KiB
JavaScript
Raw Normal View History

2013-04-10 18:14:59 +00:00
define(["jquery", "async-runner"], function($, asyncTaskRunner) {
2013-03-27 20:19:12 +00:00
2013-04-02 18:42:47 +00:00
// Dependencies
2013-04-10 18:14:59 +00:00
var core = undefined;
2013-04-02 18:42:47 +00:00
var fileManager = undefined;
2013-03-27 20:19:12 +00:00
2013-03-30 11:56:17 +00:00
var connected = false;
var authenticated = false;
2013-03-27 20:19:12 +00:00
2013-04-09 07:58:06 +00:00
var googleHelper = {};
2013-04-01 01:06:52 +00:00
2013-03-30 11:56:17 +00:00
// Try to connect Gdrive by downloading client.js
function connect(callback) {
2013-04-02 18:42:47 +00:00
callback = callback || core.doNothing;
2013-03-30 11:56:17 +00:00
var asyncTask = {};
asyncTask.run = function() {
2013-04-05 23:59:59 +00:00
if(core.isOffline === true) {
connected = false;
core.showMessage("Operation not available in offline mode.");
asyncTask.error();
return;
}
2013-04-01 01:06:52 +00:00
if (connected === true) {
2013-03-30 11:56:17 +00:00
asyncTask.success();
return;
}
2013-04-02 18:42:47 +00:00
delayedFunction = function() {
2013-03-30 11:56:17 +00:00
asyncTask.success();
};
2013-04-01 16:46:48 +00:00
$.ajax({
2013-04-02 18:42:47 +00:00
url : "https://apis.google.com/js/client.js?onload=runDelayedFunction",
2013-04-01 16:46:48 +00:00
dataType : "script", timeout : AJAX_TIMEOUT
}).fail(function() {
asyncTask.error();
});
2013-03-30 11:56:17 +00:00
};
asyncTask.onSuccess = function() {
connected = true;
callback();
2013-03-30 11:56:17 +00:00
};
asyncTask.onError = function() {
2013-04-02 18:42:47 +00:00
core.setOffline();
2013-03-30 11:56:17 +00:00
callback();
};
asyncTaskRunner.addTask(asyncTask);
}
2013-04-01 01:06:52 +00:00
2013-03-30 11:56:17 +00:00
// Try to authenticate with Oauth
function authenticate(callback, immediate) {
2013-04-02 18:42:47 +00:00
callback = callback || core.doNothing;
2013-04-01 01:06:52 +00:00
if (immediate === undefined) {
2013-03-30 11:56:17 +00:00
immediate = true;
2013-03-27 22:09:27 +00:00
}
2013-03-30 11:56:17 +00:00
connect(function() {
2013-04-01 01:06:52 +00:00
if (connected === false) {
2013-03-30 11:56:17 +00:00
callback();
return;
}
2013-04-01 01:06:52 +00:00
2013-03-30 11:56:17 +00:00
var asyncTask = {};
2013-03-31 15:33:28 +00:00
// If not immediate we add time for user to enter his credentials
2013-04-01 01:06:52 +00:00
if (immediate === false) {
asyncTask.timeout = AUTH_POPUP_TIMEOUT;
2013-03-31 15:33:28 +00:00
}
2013-03-30 11:56:17 +00:00
asyncTask.run = function() {
2013-04-01 01:06:52 +00:00
if (authenticated === true) {
2013-03-30 11:56:17 +00:00
asyncTask.success();
return;
}
2013-04-01 01:06:52 +00:00
if (immediate === false) {
2013-04-02 18:42:47 +00:00
core.showMessage("Please make sure the Google authorization popup is not blocked by your browser.");
2013-04-01 01:06:52 +00:00
}
gapi.auth.authorize({ 'client_id' : GOOGLE_CLIENT_ID,
2013-04-02 18:42:47 +00:00
'scope' : GOOGLE_SCOPES, 'immediate' : immediate }, function(
2013-04-01 01:06:52 +00:00
authResult) {
2013-03-30 11:56:17 +00:00
gapi.client.load('drive', 'v2', function() {
2013-04-05 23:59:59 +00:00
if (!authResult || authResult.error) {
asyncTask.error();
return;
}
2013-03-30 11:56:17 +00:00
authenticated = true;
asyncTask.success();
});
});
};
asyncTask.onSuccess = function() {
callback();
};
asyncTask.onError = function() {
// If immediate did not work retry without immediate flag
2013-04-01 01:06:52 +00:00
if (connected === true && immediate === true) {
2013-03-30 11:56:17 +00:00
authenticate(callback, false);
return;
}
callback();
};
asyncTaskRunner.addTask(asyncTask);
});
2013-03-27 20:19:12 +00:00
}
2013-04-09 07:58:06 +00:00
googleHelper.upload = function(fileId, parentId, title, content, callback) {
2013-04-02 18:42:47 +00:00
callback = callback || core.doNothing;
2013-03-30 11:56:17 +00:00
authenticate(function() {
2013-04-01 01:06:52 +00:00
if (connected === false) {
2013-03-30 11:56:17 +00:00
callback();
return;
}
2013-04-01 01:06:52 +00:00
var fileSyncIndex = undefined;
2013-03-30 11:56:17 +00:00
var asyncTask = {};
asyncTask.run = function() {
var boundary = '-------314159265358979323846';
var delimiter = "\r\n--" + boundary + "\r\n";
var close_delim = "\r\n--" + boundary + "--";
2013-03-27 20:19:12 +00:00
2013-03-30 11:56:17 +00:00
var contentType = 'text/x-markdown';
var metadata = { title : title, mimeType : contentType };
2013-04-01 01:06:52 +00:00
if (parentId !== undefined) {
2013-03-30 11:56:17 +00:00
// Specify the directory
2013-04-01 01:06:52 +00:00
metadata.parents = [ { kind : 'drive#fileLink',
id : parentId } ];
2013-03-30 11:56:17 +00:00
}
var path = '/upload/drive/v2/files';
var method = 'POST';
2013-04-11 22:38:41 +00:00
var etag = undefined;
2013-04-01 01:06:52 +00:00
if (fileId !== undefined) {
2013-03-30 11:56:17 +00:00
// If it's an update
path += "/" + fileId;
method = 'PUT';
2013-04-11 22:38:41 +00:00
etag = localStorage[SYNC_PROVIDER_GDRIVE
+ fileId + ".etag"];
}
var headers = { 'Content-Type' : 'multipart/mixed; boundary="'
+ boundary + '"', };
if(etag !== undefined) {
headers["If-Match"] = etag;
2013-03-30 11:56:17 +00:00
}
2013-03-27 20:19:12 +00:00
2013-04-02 18:42:47 +00:00
var base64Data = core.encodeBase64(content);
2013-03-30 11:56:17 +00:00
var multipartRequestBody = delimiter
+ 'Content-Type: application/json\r\n\r\n'
+ JSON.stringify(metadata) + delimiter + 'Content-Type: '
2013-04-01 01:06:52 +00:00
+ contentType + '\r\n'
+ 'Content-Transfer-Encoding: base64\r\n' + '\r\n'
+ base64Data + close_delim;
var request = gapi.client
.request({
'path' : path,
'method' : method,
'params' : { 'uploadType' : 'multipart', },
2013-04-11 22:38:41 +00:00
'headers' : headers,
'body' : multipartRequestBody, });
2013-04-01 01:06:52 +00:00
request.execute(function(response) {
if (response && response.id) {
2013-03-30 11:56:17 +00:00
// Upload success
fileSyncIndex = SYNC_PROVIDER_GDRIVE + response.id;
localStorage[fileSyncIndex + ".etag"] = response.etag;
2013-03-30 11:56:17 +00:00
asyncTask.success();
2013-04-01 01:06:52 +00:00
return;
2013-03-30 11:56:17 +00:00
}
2013-04-01 16:46:48 +00:00
var error = response.error;
2013-04-09 07:58:06 +00:00
// Handle error
2013-04-13 00:05:59 +00:00
if(error !== undefined && fileId !== undefined) {
2013-04-11 22:38:41 +00:00
if(error.code === 404) {
error = 'File ID "' + fileId + '" does not exist on Google Drive.';
}
else if(error.code === 412) {
2013-04-13 00:05:59 +00:00
// We may have missed a file update
localStorage.removeItem("sync.gdrive.lastChangeId");
2013-04-11 22:38:41 +00:00
error = 'Conflict on file ID "' + fileId + '". Please restart the synchronization.';
}
2013-03-30 11:56:17 +00:00
}
2013-04-01 16:46:48 +00:00
handleError(error, asyncTask, callback);
2013-03-30 11:56:17 +00:00
});
};
asyncTask.onSuccess = function() {
callback(fileSyncIndex);
2013-03-30 11:56:17 +00:00
};
2013-04-11 22:38:41 +00:00
asyncTask.onError = function() {
callback();
};
2013-04-01 01:06:52 +00:00
asyncTaskRunner.addTask(asyncTask);
});
2013-04-07 15:22:13 +00:00
};
2013-04-01 01:06:52 +00:00
2013-04-09 07:58:06 +00:00
googleHelper.checkUpdates = function(lastChangeId, callback) {
2013-04-02 18:42:47 +00:00
callback = callback || core.doNothing;
2013-04-01 01:06:52 +00:00
authenticate(function() {
if (connected === false) {
callback();
return;
}
var changes = [];
var newChangeId = lastChangeId || 0;
function retrievePageOfChanges(request) {
var nextPageToken = undefined;
var asyncTask = {};
asyncTask.run = function() {
2013-04-01 16:46:48 +00:00
request.execute(function(response) {
if (response && response.largestChangeId) {
// Retrieve success
newChangeId = response.largestChangeId;
nextPageToken = response.nextPageToken;
if (response.items !== undefined) {
for ( var i = 0; i < response.items.length; i++) {
var item = response.items[i];
var etag = localStorage[SYNC_PROVIDER_GDRIVE
+ item.fileId + ".etag"];
if (etag
&& (item.deleted === true || item.file.etag != etag)) {
changes.push(item);
2013-04-01 01:06:52 +00:00
}
}
}
2013-04-01 16:46:48 +00:00
asyncTask.success();
return;
}
// Handle error
handleError(response.error, asyncTask, callback);
});
2013-04-01 01:06:52 +00:00
};
asyncTask.onSuccess = function() {
if (nextPageToken !== undefined) {
request = gapi.client.drive.changes
.list({ 'pageToken' : nextPageToken });
retrievePageOfChanges(request);
} else {
callback(changes, newChangeId);
}
};
2013-04-11 22:38:41 +00:00
asyncTask.onError = function() {
callback();
};
2013-04-01 01:06:52 +00:00
asyncTaskRunner.addTask(asyncTask);
}
var initialRequest = gapi.client.drive.changes
.list({ 'startChangeId' : newChangeId + 1 });
retrievePageOfChanges(initialRequest);
});
};
2013-04-09 07:58:06 +00:00
googleHelper.downloadMetadata = function(ids, callback, result) {
2013-04-02 18:42:47 +00:00
callback = callback || core.doNothing;
result = result || [];
if(ids.length === 0) {
callback(result);
return;
}
authenticate(function() {
if (connected === false) {
callback();
return;
}
var id = ids.pop();
var asyncTask = {};
asyncTask.run = function() {
2013-04-07 15:22:13 +00:00
var token = gapi.auth.getToken();
var headers = {
Authorization : token ? "Bearer " + token.access_token: null
};
$.ajax({
url : "https://www.googleapis.com/drive/v2/files/" + id,
2013-04-07 15:22:13 +00:00
headers : headers,
dataType : "json",
timeout : AJAX_TIMEOUT
}).done(function(data, textStatus, jqXHR) {
result.push(data);
asyncTask.success();
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
2013-04-03 22:52:29 +00:00
if(error.code === 404) {
2013-04-07 15:22:13 +00:00
error = 'File ID "' + id + '" does not exist on Google Drive.';
2013-04-02 18:42:47 +00:00
}
handleError(error, asyncTask, callback);
});
};
asyncTask.onSuccess = function() {
2013-04-09 07:58:06 +00:00
googleHelper.downloadMetadata(ids, callback, result);
};
2013-04-11 22:38:41 +00:00
asyncTask.onError = function() {
callback();
};
asyncTaskRunner.addTask(asyncTask);
});
};
2013-04-09 07:58:06 +00:00
googleHelper.downloadContent = function(objects, callback, result) {
2013-04-02 18:42:47 +00:00
callback = callback || core.doNothing;
2013-04-01 01:06:52 +00:00
result = result || [];
if(objects.length === 0) {
callback(result);
return;
}
var object = objects.pop();
result.push(object);
var file = undefined;
// object may be a file
if(object.kind == "drive#file") {
file = object;
}
// object may be a change
else if(object.kind == "drive#change") {
file = object.file;
}
2013-04-07 15:22:13 +00:00
if(!file) {
2013-04-01 01:06:52 +00:00
this.downloadContent(objects, callback, result);
return;
}
2013-04-01 01:06:52 +00:00
authenticate(function() {
if (connected === false) {
2013-03-30 11:56:17 +00:00
callback();
2013-04-01 01:06:52 +00:00
return;
}
2013-04-01 01:06:52 +00:00
var asyncTask = {};
asyncTask.run = function() {
2013-04-07 15:22:13 +00:00
var token = gapi.auth.getToken();
var headers = {
Authorization : token ? "Bearer " + token.access_token: null
};
2013-04-01 16:46:48 +00:00
$.ajax({
url : file.downloadUrl,
2013-04-07 15:22:13 +00:00
headers : headers,
dataType : "text",
2013-04-01 16:46:48 +00:00
timeout : AJAX_TIMEOUT
}).done(function(data, textStatus, jqXHR) {
file.content = data;
asyncTask.success();
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
handleError(error, asyncTask, callback);
});
2013-04-01 01:06:52 +00:00
};
asyncTask.onSuccess = function() {
2013-04-09 07:58:06 +00:00
googleHelper.downloadContent(objects, callback, result);
2013-03-30 11:56:17 +00:00
};
2013-04-11 22:38:41 +00:00
asyncTask.onError = function() {
callback();
2013-03-30 11:56:17 +00:00
};
asyncTaskRunner.addTask(asyncTask);
2013-04-01 01:06:52 +00:00
});
};
2013-04-02 18:42:47 +00:00
function handleError(error, asyncTask, callback) {
var errorMsg = undefined;
asyncTask.onError = function() {
if (errorMsg !== undefined) {
core.showError(errorMsg);
}
callback();
};
if (error) {
// Try to analyze the error
if (typeof error === "string") {
errorMsg = error;
}
2013-04-03 22:52:29 +00:00
else if (error.code >= 500 && error.code < 600) {
2013-04-02 18:42:47 +00:00
errorMsg = "Google Drive is not accessible.";
// Retry as described in Google's best practices
asyncTask.retry();
return;
} else if (error.code === 401 || error.code === 403) {
authenticated = false;
errorMsg = "Access to Google Drive is not authorized.";
} else if (error.code <= 0) {
connected = false;
authenticated = false;
core.setOffline();
} else {
errorMsg = "Google Drive error (" + error.code + ": "
+ error.message + ").";
}
}
asyncTask.error();
}
2013-04-05 23:59:59 +00:00
var pickerLoaded = false;
function loadPicker(callback) {
2013-04-07 15:22:13 +00:00
connect(function() {
2013-04-06 00:57:52 +00:00
if (connected === false) {
2013-04-05 23:59:59 +00:00
pickerLoaded = false;
2013-04-06 00:57:52 +00:00
callback();
2013-04-05 23:59:59 +00:00
return;
}
2013-04-06 00:57:52 +00:00
var asyncTask = {};
asyncTask.run = function() {
if (pickerLoaded === true) {
asyncTask.success();
return;
}
$.ajax({
url : "//www.google.com/jsapi",
data : {key: GOOGLE_KEY},
dataType : "script", timeout : AJAX_TIMEOUT
}).done(function() {
asyncTask.success();
}).fail(function() {
asyncTask.error();
});
};
asyncTask.onSuccess = function() {
google.load('picker', '1', {callback: callback});
pickerLoaded = true;
};
asyncTask.onError = function() {
core.setOffline();
callback();
};
asyncTaskRunner.addTask(asyncTask);
});
2013-04-05 23:59:59 +00:00
}
2013-04-09 07:58:06 +00:00
googleHelper.picker = function(callback) {
2013-04-05 23:59:59 +00:00
callback = callback || core.doNothing;
loadPicker(function() {
if (pickerLoaded === false) {
callback();
return;
}
2013-04-06 01:07:45 +00:00
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes("text/x-markdown,text/plain");
var pickerBuilder = new google.picker.PickerBuilder();
pickerBuilder.enableFeature(google.picker.Feature.NAV_HIDDEN);
pickerBuilder.enableFeature(google.picker.Feature.MULTISELECT_ENABLED);
pickerBuilder.setAppId(GOOGLE_DRIVE_APP_ID);
2013-04-06 00:57:52 +00:00
var token = gapi.auth.getToken();
2013-04-06 01:07:45 +00:00
if(token) {
pickerBuilder.setOAuthToken(token.access_token);
}
pickerBuilder.addView(view);
pickerBuilder.addView(new google.picker.DocsUploadView());
pickerBuilder.setCallback(function(data) {
if (data.action == google.picker.Action.PICKED ||
data.action == google.picker.Action.CANCEL) {
var ids = [];
if(data.action == google.picker.Action.PICKED) {
for(var i=0; i<data.docs.length; i++) {
ids.push(data.docs[i].id);
2013-04-05 23:59:59 +00:00
}
2013-04-06 01:07:45 +00:00
}
$(".modal-backdrop, .picker").remove();
callback(ids);
}
});
var picker = pickerBuilder.build();
$("body").append($("<div>").addClass("modal-backdrop").click(function() {
picker.setVisible(false);
2013-04-06 00:57:52 +00:00
$(".modal-backdrop, .picker").remove();
2013-04-05 23:59:59 +00:00
callback();
2013-04-06 01:07:45 +00:00
}));
picker.setVisible(true);
2013-04-05 23:59:59 +00:00
});
};
2013-04-09 07:58:06 +00:00
googleHelper.importFiles = function(ids) {
googleHelper.downloadMetadata(ids, function(result) {
2013-04-03 18:35:25 +00:00
if(result === undefined) {
return;
}
2013-04-09 07:58:06 +00:00
googleHelper.downloadContent(result, function(result) {
2013-04-03 18:35:25 +00:00
if(result === undefined) {
return;
}
for(var i=0; i<result.length; i++) {
var file = result[i];
fileSyncIndex = SYNC_PROVIDER_GDRIVE + file.id;
localStorage[fileSyncIndex + ".etag"] = file.etag;
2013-04-09 07:58:06 +00:00
var contentCRC = core.crc32(file.content);
localStorage[fileSyncIndex + ".contentCRC"] = contentCRC;
var titleCRC = core.crc32(file.title);
localStorage[fileSyncIndex + ".titleCRC"] = titleCRC;
2013-04-03 18:35:25 +00:00
var fileIndex = fileManager.createFile(file.title, file.content, [fileSyncIndex]);
fileManager.selectFile(fileIndex);
core.showMessage('"' + file.title + '" imported successfully from Google Drive.');
}
});
});
};
2013-03-27 20:19:12 +00:00
2013-04-10 23:13:31 +00:00
googleHelper.getBlogByUrl = function(url, callback) {
authenticate(function() {
if (connected === false) {
callback();
return;
}
var result = undefined;
var asyncTask = {};
asyncTask.run = function() {
var token = gapi.auth.getToken();
var headers = {
Authorization : token ? "Bearer " + token.access_token: null
};
$.ajax({
url : "https://www.googleapis.com/blogger/v3/blogs/byurl",
data: { url: url },
headers : headers,
dataType : "json",
timeout : AJAX_TIMEOUT
}).done(function(blog, textStatus, jqXHR) {
result = blog;
asyncTask.success();
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
handleError(error, asyncTask, callback);
});
};
asyncTask.onSuccess = function() {
callback(result);
};
2013-04-11 22:38:41 +00:00
asyncTask.onError = function() {
2013-04-10 23:13:31 +00:00
callback();
};
asyncTaskRunner.addTask(asyncTask);
});
};
2013-04-11 22:38:41 +00:00
2013-04-10 18:14:59 +00:00
googleHelper.init = function(coreModule, fileManagerModule) {
core = coreModule;
2013-04-02 18:42:47 +00:00
fileManager = fileManagerModule;
var state = localStorage["sync.gdrive.state"];
if(state === undefined) {
return;
}
localStorage.removeItem("sync.gdrive.state");
state = JSON.parse(state);
if (state.action == "create") {
2013-04-09 07:58:06 +00:00
googleHelper.upload(undefined, state.folderId, GDRIVE_DEFAULT_FILE_TITLE,
"", function(fileSyncIndex) {
if(fileSyncIndex === undefined) {
return;
}
2013-04-09 07:58:06 +00:00
var contentCRC = core.crc32("");
localStorage[fileSyncIndex + ".contentCRC"] = contentCRC;
var titleCRC = core.crc32(GDRIVE_DEFAULT_FILE_TITLE);
localStorage[fileSyncIndex + ".titleCRC"] = titleCRC;
2013-04-02 18:42:47 +00:00
var fileIndex = fileManager.createFile(GDRIVE_DEFAULT_FILE_TITLE, "", [fileSyncIndex]);
fileManager.selectFile(fileIndex);
2013-04-02 18:42:47 +00:00
core.showMessage('"' + GDRIVE_DEFAULT_FILE_TITLE + '" created successfully on Google Drive.');
});
}
else if (state.action == "open") {
2013-04-03 18:35:25 +00:00
var ids = [];
for(var i=0; i<state.ids.length; i++) {
var id = state.ids[i];
var fileSyncIndex = SYNC_PROVIDER_GDRIVE + id;
var fileIndex = fileManager.getFileIndexFromSync(fileSyncIndex);
if(fileIndex !== undefined) {
fileManager.selectFile(fileIndex);
} else {
2013-04-03 18:35:25 +00:00
ids.push(id);
}
2013-03-27 20:19:12 +00:00
}
2013-04-09 07:58:06 +00:00
googleHelper.importFiles(ids);
2013-03-30 11:56:17 +00:00
}
2013-03-27 20:19:12 +00:00
};
2013-04-05 23:59:59 +00:00
2013-04-09 07:58:06 +00:00
return googleHelper;
2013-04-02 18:42:47 +00:00
});