Stackedit/public/res/helpers/googleHelper.js

1045 lines
39 KiB
JavaScript
Raw Normal View History

2013-11-05 23:03:38 +00:00
/*global gapi, google */
2013-05-27 19:45:33 +00:00
define([
2013-10-06 14:34:40 +00:00
"underscore",
2013-05-27 19:45:33 +00:00
"jquery",
2013-11-05 23:03:38 +00:00
"constants",
2013-05-27 19:45:33 +00:00
"core",
"utils",
2013-11-05 23:03:38 +00:00
"storage",
"logger",
2013-10-06 14:34:40 +00:00
"settings",
2013-07-30 08:46:36 +00:00
"eventMgr",
2013-10-06 14:34:40 +00:00
"classes/AsyncTask",
2013-11-05 23:03:38 +00:00
], function(_, $, constants, core, utils, storage, logger, settings, eventMgr, AsyncTask) {
2013-03-27 20:19:12 +00:00
2013-05-29 19:55:23 +00:00
var connected = false;
2013-12-15 17:26:17 +00:00
var authorizationMgrMap = {};
function AuthorizationMgr(accountId) {
2013-12-17 00:15:13 +00:00
var permissionList = {
profile: true
};
2013-12-16 00:31:40 +00:00
var refreshFlag = true;
2013-12-15 17:26:17 +00:00
_.each((storage[accountId + '.permissions'] || '').split(';'), function(permission) {
permission && (permissionList[permission] = true);
});
2013-12-16 00:31:40 +00:00
this.setRefreshFlag = function() {
refreshFlag = true;
};
2013-12-15 17:26:17 +00:00
this.isAuthorized = function(permission) {
2013-12-16 00:31:40 +00:00
return refreshFlag === false && _.has(permissionList, permission);
};
2013-12-15 17:26:17 +00:00
this.add = function(permission) {
permissionList[permission] = true;
2013-12-15 17:26:17 +00:00
storage[accountId + '.permissions'] = _.keys(permissionList).join(';');
2013-12-16 00:31:40 +00:00
refreshFlag = false;
};
2013-12-15 17:26:17 +00:00
this.getListWithNew = function(permission) {
var result = _.keys(permissionList);
if(!_.has(permissionList, permission)) {
result.push(permission);
}
return result;
};
2013-12-17 00:15:13 +00:00
var userId = storage[accountId + '.userId'];
this.setUserId = function(value) {
userId = value;
storage[accountId + '.userId'] = userId;
2013-12-15 17:26:17 +00:00
};
2013-12-17 00:15:13 +00:00
this.getUserId = function() {
return userId;
2013-12-15 17:26:17 +00:00
};
}
2013-03-27 20:19:12 +00:00
2013-05-29 19:55:23 +00:00
var googleHelper = {};
2013-04-01 01:06:52 +00:00
2013-08-04 00:53:46 +00:00
// Listen to offline status changes
var isOffline = false;
eventMgr.addListener("onOfflineChanged", function(isOfflineParam) {
isOffline = isOfflineParam;
});
2013-12-23 22:33:33 +00:00
// Try to connect by downloading client.js
2013-05-29 19:55:23 +00:00
function connect(task) {
task.onRun(function() {
2013-08-04 00:53:46 +00:00
if(isOffline === true) {
2013-05-29 19:55:23 +00:00
connected = false;
task.error(new Error("Operation not available in offline mode.|stopPublish"));
return;
}
if(connected === true) {
task.chain();
return;
}
2013-11-05 23:03:38 +00:00
window.delayedFunction = function() {
2013-07-16 23:54:56 +00:00
gapi.load("client,drive-realtime", function() {
gapi.client.load('drive', 'v2', function() {
connected = true;
task.chain();
});
2013-07-16 23:54:56 +00:00
});
2013-05-29 19:55:23 +00:00
};
$.ajax({
2013-07-16 23:54:56 +00:00
url: "https://apis.google.com/js/api.js?onload=runDelayedFunction",
2013-05-29 19:55:23 +00:00
dataType: "script",
2013-11-05 23:03:38 +00:00
timeout: constants.AJAX_TIMEOUT
2013-05-29 19:55:23 +00:00
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
handleError(error, task);
});
});
}
2013-04-01 01:06:52 +00:00
2013-05-29 19:55:23 +00:00
// Try to authenticate with Oauth
var scopeMap = {
2013-12-17 00:15:13 +00:00
profile: [
'https://www.googleapis.com/auth/userinfo.profile'
],
gdrive: [
'https://www.googleapis.com/auth/drive.install',
settings.gdriveFullAccess === true ? 'https://www.googleapis.com/auth/drive' : 'https://www.googleapis.com/auth/drive.file'
],
blogger: [
'https://www.googleapis.com/auth/blogger'
],
picasa: [
'https://picasaweb.google.com/data/'
]
};
2013-12-16 00:31:40 +00:00
function authenticate(task, permission, accountId) {
2013-12-15 17:26:17 +00:00
var authorizationMgr = authorizationMgrMap[accountId];
if(!authorizationMgr) {
authorizationMgr = new AuthorizationMgr(accountId);
authorizationMgrMap[accountId] = authorizationMgr;
}
2013-05-29 19:55:23 +00:00
task.onRun(function() {
2013-12-27 00:01:11 +00:00
var currentToken = gapi.auth.getToken();
var newToken;
2013-12-17 00:15:13 +00:00
function getTokenInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/tokeninfo',
data: {
2013-12-27 00:01:11 +00:00
access_token: newToken.access_token
2013-12-17 00:15:13 +00:00
},
timeout: constants.AJAX_TIMEOUT,
type: "GET"
}).done(function(data) {
2013-12-23 22:33:33 +00:00
if(authorizationMgr.getUserId() && authorizationMgr.getUserId() != data.user_id) {
// Wrong user id, try again
startAuthenticate();
2013-12-17 00:15:13 +00:00
}
else {
authorizationMgr.setUserId(data.user_id);
2013-12-23 22:33:33 +00:00
authorizationMgr.add(permission);
2013-12-27 00:01:11 +00:00
authorizationMgr.token = newToken;
task.chain();
2013-12-17 00:15:13 +00:00
}
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
handleError(error, task);
2013-10-06 14:34:40 +00:00
});
}
2013-12-17 00:15:13 +00:00
var authuser = 0;
var immediate;
2013-05-29 19:55:23 +00:00
function localAuthenticate() {
2013-12-23 22:33:33 +00:00
if(authuser > 5) {
2013-12-25 21:14:22 +00:00
task.error(new Error('Unable to authenticate user ' + authorizationMgr.getUserId() + ', please sign in with Google.'));
return;
2013-12-23 22:33:33 +00:00
}
2013-05-29 19:55:23 +00:00
if(immediate === false) {
2013-11-05 23:03:38 +00:00
task.timeout = constants.ASYNC_TASK_LONG_TIMEOUT;
2013-05-29 19:55:23 +00:00
}
var scopeList = _.chain(scopeMap).pick(authorizationMgr.getListWithNew(permission)).flatten().value();
2013-05-29 19:55:23 +00:00
gapi.auth.authorize({
2013-12-16 00:31:40 +00:00
client_id: constants.GOOGLE_CLIENT_ID,
scope: scopeList,
immediate: immediate,
2013-12-17 00:15:13 +00:00
authuser: immediate === false ? '' : authuser
2013-05-29 19:55:23 +00:00
}, function(authResult) {
2013-12-27 00:01:11 +00:00
newToken = gapi.auth.getToken();
gapi.auth.setToken(currentToken);
2013-12-17 00:15:13 +00:00
if(!authResult || authResult.error) {
if(connected === true && immediate === true) {
2013-05-29 19:55:23 +00:00
// If immediate did not work retry without immediate
// flag
2013-12-17 00:15:13 +00:00
immediate = false;
task.chain(oauthRedirect);
}
else {
2013-05-29 19:55:23 +00:00
// Error
task.error(new Error("Access to Google account is not authorized."));
}
2013-12-17 00:15:13 +00:00
}
else {
2013-12-23 22:33:33 +00:00
// Success but we need to check the user id
immediate === true && authuser++;
2013-12-17 00:15:13 +00:00
task.chain(getTokenInfo);
}
2013-05-29 19:55:23 +00:00
});
}
2013-12-17 00:15:13 +00:00
function oauthRedirect() {
if(immediate === true) {
task.chain(localAuthenticate);
return;
}
2014-01-13 18:57:59 +00:00
utils.redirectConfirm('You are being redirected to <strong>Google</strong> authorization page.', function() {
2013-12-17 00:15:13 +00:00
task.chain(localAuthenticate);
}, function() {
task.error(new Error('Operation canceled.'));
});
}
2013-12-23 22:33:33 +00:00
function startAuthenticate() {
2013-12-17 00:15:13 +00:00
immediate = true;
if(authorizationMgr.token && authorizationMgr.isAuthorized(permission)) {
task.chain();
return;
}
if(!authorizationMgr.getUserId()) {
immediate = false;
}
task.chain(oauthRedirect);
}
2013-12-23 22:33:33 +00:00
startAuthenticate();
2013-05-29 19:55:23 +00:00
});
}
2013-12-15 17:26:17 +00:00
googleHelper.refreshGdriveToken = function(accountId) {
2013-07-21 22:18:35 +00:00
var task = new AsyncTask();
connect(task);
2013-12-16 00:31:40 +00:00
var authorizationMgr = authorizationMgrMap[accountId];
authorizationMgr && authorizationMgr.setRefreshFlag();
authenticate(task, 'gdrive', accountId);
2013-07-21 22:18:35 +00:00
task.enqueue();
};
2014-03-19 22:10:59 +00:00
2013-12-27 00:01:11 +00:00
function runWithToken(accountId, functionToRun) {
var currentToken = gapi.auth.getToken();
var authorizationMgr = authorizationMgrMap[accountId];
gapi.auth.setToken(authorizationMgr.token);
functionToRun();
gapi.auth.setToken(currentToken);
}
2013-03-27 20:19:12 +00:00
2013-12-15 17:26:17 +00:00
googleHelper.upload = function(fileId, parentId, title, content, contentType, etag, accountId, callback) {
2013-11-05 23:03:38 +00:00
var result;
2013-06-16 10:47:35 +00:00
var task = new AsyncTask();
2013-05-29 19:55:23 +00:00
connect(task);
2013-12-15 17:26:17 +00:00
authenticate(task, 'gdrive', accountId);
2013-05-29 19:55:23 +00:00
task.onRun(function() {
var boundary = '-------314159265358979323846';
var delimiter = "\r\n--" + boundary + "\r\n";
var close_delim = "\r\n--" + boundary + "--";
contentType = contentType || 'text/x-markdown';
2013-05-29 19:55:23 +00:00
var metadata = {
title: title,
mimeType: contentType
};
2013-08-14 23:44:51 +00:00
if(parentId) {
2013-05-29 19:55:23 +00:00
// Specify the directory
metadata.parents = [
2013-11-05 23:03:38 +00:00
{
kind: 'drive#fileLink',
id: parentId
}
];
2013-05-29 19:55:23 +00:00
}
var path = '/upload/drive/v2/files';
var method = 'POST';
2013-08-14 23:44:51 +00:00
if(fileId) {
2013-05-29 19:55:23 +00:00
// If it's an update
path += "/" + fileId;
method = 'PUT';
}
var headers = {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"',
};
2013-06-02 00:38:23 +00:00
// Sometimes we have error 412 from Google even with the correct
// etag
// if(etag !== undefined) {
// headers["If-Match"] = etag;
// }
2014-03-19 22:10:59 +00:00
2013-05-29 19:55:23 +00:00
var base64Data = utils.encodeBase64(content);
2013-07-16 23:54:56 +00:00
var multipartRequestBody = [
2013-11-05 23:03:38 +00:00
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
].join("");
2014-03-19 22:10:59 +00:00
2013-12-27 00:01:11 +00:00
runWithToken(accountId, function() {
var request = gapi.client.request({
'path': path,
'method': method,
'params': {
'uploadType': 'multipart',
},
'headers': headers,
'body': multipartRequestBody,
});
request.execute(function(response) {
if(response && response.id) {
// Upload success
result = response;
result.content = content;
task.chain();
return;
2013-05-29 19:55:23 +00:00
}
2013-12-27 00:01:11 +00:00
var error = response.error;
// Handle error
if(error !== undefined && fileId !== undefined) {
if(error.code === 404) {
error = 'File ID "' + fileId + '" not found on Google Drive.|removePublish';
}
else if(error.code === 412) {
// We may have missed a file update
storage.removeItem(accountId + ".gdrive.lastChangeId");
error = 'Conflict on file ID "' + fileId + '". Please restart the synchronization.';
}
2013-05-29 19:55:23 +00:00
}
2013-12-27 00:01:11 +00:00
handleError(error, task);
});
2013-07-16 23:54:56 +00:00
});
});
task.onSuccess(function() {
callback(undefined, result);
});
task.onError(function(error) {
callback(error);
});
task.enqueue();
};
2014-03-19 22:10:59 +00:00
2013-12-15 17:26:17 +00:00
googleHelper.rename = function(fileId, title, accountId, callback) {
2013-11-05 23:03:38 +00:00
var result;
var task = new AsyncTask();
connect(task);
2013-12-15 17:26:17 +00:00
authenticate(task, 'gdrive', accountId);
task.onRun(function() {
var body = {'title': title};
2013-12-27 00:01:11 +00:00
runWithToken(accountId, function() {
var request = gapi.client.drive.files.patch({
'fileId': fileId,
'resource': body
});
request.execute(function(response) {
if(response && response.id) {
// Rename success
result = response;
task.chain();
return;
}
2013-12-27 00:01:11 +00:00
var error = response.error;
// Handle error
if(error !== undefined && fileId !== undefined) {
if(error.code === 404) {
error = 'File ID "' + fileId + '" not found on Google Drive.|removePublish';
}
}
handleError(error, task);
});
});
});
task.onSuccess(function() {
callback(undefined, result);
});
2013-07-16 23:54:56 +00:00
task.onError(function(error) {
callback(error);
});
task.enqueue();
};
2013-07-20 01:08:17 +00:00
2013-12-15 17:26:17 +00:00
googleHelper.createRealtimeFile = function(parentId, title, accountId, callback) {
2013-11-05 23:03:38 +00:00
var result;
2013-07-18 23:30:28 +00:00
var task = new AsyncTask();
connect(task);
2013-12-15 17:26:17 +00:00
authenticate(task, 'gdrive', accountId);
2013-07-18 23:30:28 +00:00
task.onRun(function() {
var metadata = {
title: title,
2013-07-20 01:08:17 +00:00
mimeType: 'application/vnd.google-apps.drive-sdk',
2013-07-18 23:30:28 +00:00
};
if(parentId !== undefined) {
// Specify the directory
metadata.parents = [
{
kind: 'drive#fileLink',
id: parentId
}
];
}
2013-12-27 00:01:11 +00:00
runWithToken(accountId, function() {
var request = gapi.client.drive.files.insert({
'resource': metadata
});
request.execute(function(response) {
if(response && response.id) {
// Upload success
result = response;
task.chain();
return;
}
handleError(response.error, task);
});
2013-07-18 23:30:28 +00:00
});
});
task.onSuccess(function() {
callback(undefined, result);
});
task.onError(function(error) {
callback(error);
});
task.enqueue();
};
2013-07-16 23:54:56 +00:00
2013-12-15 17:26:17 +00:00
googleHelper.checkChanges = function(lastChangeId, accountId, callback) {
2013-05-29 19:55:23 +00:00
var changes = [];
var newChangeId = lastChangeId || 0;
2013-06-16 10:47:35 +00:00
var task = new AsyncTask();
2013-05-29 19:55:23 +00:00
connect(task);
2013-12-15 17:26:17 +00:00
authenticate(task, 'gdrive', accountId);
2013-05-29 19:55:23 +00:00
task.onRun(function() {
2013-11-05 23:03:38 +00:00
var nextPageToken;
2013-05-29 19:55:23 +00:00
function retrievePageOfChanges() {
2013-12-27 00:01:11 +00:00
runWithToken(accountId, function() {
var request;
if(nextPageToken === undefined) {
request = gapi.client.drive.changes.list({
'startChangeId': newChangeId + 1
});
2013-05-29 19:55:23 +00:00
}
else {
2013-12-27 00:01:11 +00:00
request = gapi.client.drive.changes.list({
'pageToken': nextPageToken
});
2013-05-29 19:55:23 +00:00
}
2014-03-19 22:10:59 +00:00
2013-12-27 00:01:11 +00:00
request.execute(function(response) {
if(!response || !response.largestChangeId) {
// Handle error
handleError(response.error, task);
return;
}
// Retrieve success
newChangeId = response.largestChangeId;
nextPageToken = response.nextPageToken;
if(response.items !== undefined) {
changes = changes.concat(response.items);
}
if(nextPageToken !== undefined) {
task.chain(retrievePageOfChanges);
}
else {
task.chain();
}
});
2013-05-29 19:55:23 +00:00
});
}
task.chain(retrievePageOfChanges);
});
task.onSuccess(function() {
callback(undefined, changes, newChangeId);
});
task.onError(function(error) {
callback(error);
});
2013-06-16 10:47:35 +00:00
task.enqueue();
2013-05-29 19:55:23 +00:00
};
2013-04-01 01:06:52 +00:00
2013-12-15 17:26:17 +00:00
googleHelper.downloadMetadata = function(ids, accountId, callback, skipAuth) {
2013-05-29 19:55:23 +00:00
var result = [];
2013-06-16 10:47:35 +00:00
var task = new AsyncTask();
2013-05-29 19:55:23 +00:00
connect(task);
if(!skipAuth) {
2013-12-15 17:26:17 +00:00
authenticate(task, 'gdrive', accountId);
2013-05-29 19:55:23 +00:00
}
task.onRun(function() {
function recursiveDownloadMetadata() {
if(ids.length === 0) {
task.chain();
return;
}
var id = ids[0];
var headers = {};
2013-12-27 00:01:11 +00:00
var authorizationMgr = authorizationMgrMap[accountId];
if(authorizationMgr && authorizationMgr.token) {
headers.Authorization = "Bearer " + authorizationMgr.token.access_token;
2013-05-29 19:55:23 +00:00
}
$.ajax({
url: "https://www.googleapis.com/drive/v2/files/" + id,
headers: headers,
data: {
2013-11-05 23:03:38 +00:00
key: constants.GOOGLE_API_KEY
2013-05-29 19:55:23 +00:00
},
dataType: "json",
2013-11-05 23:03:38 +00:00
timeout: constants.AJAX_TIMEOUT
}).done(function(data) {
2013-05-29 19:55:23 +00:00
result.push(data);
ids.shift();
task.chain(recursiveDownloadMetadata);
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
if(error.code === 404) {
error = 'File ID "' + id + '" not found on Google Drive.';
}
handleError(error, task);
});
}
task.chain(recursiveDownloadMetadata);
});
task.onSuccess(function() {
callback(undefined, result);
});
task.onError(function(error) {
callback(error);
});
2013-06-16 10:47:35 +00:00
task.enqueue();
2013-05-29 19:55:23 +00:00
};
2013-12-15 17:26:17 +00:00
googleHelper.downloadContent = function(objects, accountId, callback, skipAuth) {
2013-05-29 19:55:23 +00:00
var result = [];
2013-06-16 10:47:35 +00:00
var task = new AsyncTask();
2013-05-29 19:55:23 +00:00
// Add some time for user to choose his files
2013-11-05 23:03:38 +00:00
task.timeout = constants.ASYNC_TASK_LONG_TIMEOUT;
2013-05-29 19:55:23 +00:00
connect(task);
if(!skipAuth) {
2013-12-15 17:26:17 +00:00
authenticate(task, 'gdrive', accountId);
2013-05-29 19:55:23 +00:00
}
task.onRun(function() {
function recursiveDownloadContent() {
if(objects.length === 0) {
task.chain();
return;
}
var object = objects[0];
result.push(object);
2013-11-05 23:03:38 +00:00
var file;
2013-05-29 19:55:23 +00:00
// 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;
}
if(!file) {
objects.shift();
task.chain(recursiveDownloadContent);
return;
}
var url = file.downloadUrl;
2013-07-20 01:08:17 +00:00
// if file is a real time document
if(file.mimeType.indexOf("application/vnd.google-apps.drive-sdk") === 0) {
file.isRealtime = true;
url = 'https://www.googleapis.com/drive/v2/files/' + file.id + '/realtime';
2013-07-20 01:08:17 +00:00
}
2013-05-29 19:55:23 +00:00
var headers = {};
2013-12-27 00:01:11 +00:00
var authorizationMgr = authorizationMgrMap[accountId];
if(authorizationMgr && authorizationMgr.token) {
headers.Authorization = "Bearer " + authorizationMgr.token.access_token;
2013-05-29 19:55:23 +00:00
}
$.ajax({
url: url,
2013-05-29 19:55:23 +00:00
headers: headers,
data: {
2013-11-05 23:03:38 +00:00
key: constants.GOOGLE_API_KEY
2013-05-29 19:55:23 +00:00
},
dataType: file.isRealtime ? 'json' : 'text',
2013-11-05 23:03:38 +00:00
timeout: constants.AJAX_TIMEOUT
}).done(function(data) {
2013-05-29 19:55:23 +00:00
file.content = data;
objects.shift();
task.chain(recursiveDownloadContent);
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
handleError(error, task);
});
}
task.chain(recursiveDownloadContent);
});
task.onSuccess(function() {
callback(undefined, result);
});
task.onError(function(error) {
callback(error);
});
2013-06-16 10:47:35 +00:00
task.enqueue();
2013-05-29 19:55:23 +00:00
};
2013-07-20 01:08:17 +00:00
2014-04-07 23:19:47 +00:00
googleHelper.loadRealtime = function(fileId, accountId, callback, errorCallback) {
2013-11-05 23:03:38 +00:00
var doc;
var task = new AsyncTask();
connect(task);
2013-12-15 17:26:17 +00:00
authenticate(task, 'gdrive', accountId);
task.onRun(function() {
2013-12-27 00:01:11 +00:00
var authorizationMgr = authorizationMgrMap[accountId];
gapi.auth.setToken(authorizationMgr.token);
gapi.drive.realtime.load(fileId, function(result) {
// onFileLoaded
doc = result;
task.chain();
2014-04-07 23:19:47 +00:00
}, undefined, function(err) {
2013-07-21 22:18:35 +00:00
errorCallback(err);
task.error(new Error(err.message));
2013-07-20 01:08:17 +00:00
});
2013-07-21 14:38:53 +00:00
});
task.onSuccess(function() {
callback(undefined, doc);
});
task.onError(function(error) {
callback(error);
});
task.enqueue();
};
2013-04-02 18:42:47 +00:00
2013-12-23 22:33:33 +00:00
googleHelper.uploadImg = function(name, content, albumId, callback) {
2013-12-27 00:01:11 +00:00
var accountId = 'google.picasa0';
2013-12-23 22:33:33 +00:00
var result;
var task = new AsyncTask();
connect(task);
2013-12-27 00:01:11 +00:00
authenticate(task, 'picasa', accountId);
2013-12-23 22:33:33 +00:00
task.onRun(function() {
var headers = {
"Slug": name
};
if(name.match(/.jpe?g$/i)) {
headers["Content-Type"] = "image/jpeg";
}
else if(name.match(/.png$/i)) {
headers["Content-Type"] = "image/png";
}
else if(name.match(/.gif$/i)) {
headers["Content-Type"] = "image/gif";
}
2013-12-27 00:01:11 +00:00
var authorizationMgr = authorizationMgrMap[accountId];
if(authorizationMgr && authorizationMgr.token) {
headers.Authorization = "Bearer " + authorizationMgr.token.access_token;
2013-12-23 22:33:33 +00:00
}
$.ajax({
url: constants.PICASA_PROXY_URL + "upload/" + albumId,
headers: headers,
data: content,
processData: false,
dataType: "xml",
timeout: constants.AJAX_TIMEOUT,
type: "POST"
}).done(function(data) {
result = data;
task.chain();
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
if(error.code == 200) {
error.message = jqXHR.responseText;
}
handleError(error, task);
});
});
task.onSuccess(function() {
callback(undefined, result);
});
task.onError(function(error) {
callback(error);
});
task.enqueue();
};
2013-05-29 19:55:23 +00:00
function handleError(error, task) {
2013-11-05 23:03:38 +00:00
var errorMsg;
2013-05-29 19:55:23 +00:00
if(error) {
logger.error(error);
// Try to analyze the error
if(typeof error === "string") {
errorMsg = error;
}
else {
errorMsg = "Google error (" + error.code + ": " + error.message + ").";
if(error.code >= 500 && error.code < 600) {
// Retry as described in Google's best practices
task.retry(new Error(errorMsg));
return;
}
2013-07-21 22:18:35 +00:00
else if(error.code === 401 || error.code === 403 || error.code == "token_refresh_required") {
2013-12-15 17:26:17 +00:00
_.each(authorizationMgrMap, function(authorizationMgr) {
2013-12-16 00:31:40 +00:00
authorizationMgr.setRefreshFlag();
2013-12-15 17:26:17 +00:00
});
2013-05-29 19:55:23 +00:00
errorMsg = "Access to Google account is not authorized.";
task.retry(new Error(errorMsg), 1);
return;
}
2013-06-03 22:19:52 +00:00
else if(error.code === 0 || error.code === -1) {
2013-05-29 19:55:23 +00:00
connected = false;
2013-12-15 17:26:17 +00:00
_.each(authorizationMgrMap, function(authorizationMgr) {
2013-12-16 00:31:40 +00:00
authorizationMgr.setRefreshFlag();
2013-12-15 17:26:17 +00:00
});
2013-05-29 19:55:23 +00:00
core.setOffline();
errorMsg = "|stopPublish";
}
}
}
task.error(new Error(errorMsg));
}
2013-03-27 20:19:12 +00:00
2013-05-29 19:55:23 +00:00
var pickerLoaded = false;
function loadPicker(task) {
task.onRun(function() {
if(pickerLoaded === true) {
task.chain();
return;
}
$.ajax({
url: "//www.google.com/jsapi",
data: {
2013-11-05 23:03:38 +00:00
key: constants.GOOGLE_API_KEY
2013-05-29 19:55:23 +00:00
},
dataType: "script",
2013-11-05 23:03:38 +00:00
timeout: constants.AJAX_TIMEOUT
2013-05-29 19:55:23 +00:00
}).done(function() {
google.load('picker', '1', {
2013-06-16 10:47:35 +00:00
callback: function() {
task.chain();
}
2013-05-29 19:55:23 +00:00
});
pickerLoaded = true;
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
handleError(error, task);
});
});
}
2013-04-11 22:38:41 +00:00
2013-12-15 17:26:17 +00:00
googleHelper.picker = function(callback, pickerType, accountId) {
2013-06-02 00:38:23 +00:00
var docs = [];
2013-11-05 23:03:38 +00:00
var picker;
2013-05-29 19:55:23 +00:00
function hidePicker() {
if(picker !== undefined) {
picker.setVisible(false);
$(".modal-backdrop, .picker").remove();
}
}
2013-06-16 10:47:35 +00:00
var task = new AsyncTask();
2013-08-23 23:50:14 +00:00
// Add some time for user to choose his files
2013-11-05 23:03:38 +00:00
task.timeout = constants.ASYNC_TASK_LONG_TIMEOUT;
2013-05-29 19:55:23 +00:00
connect(task);
2013-12-15 17:26:17 +00:00
if(pickerType == 'doc' || pickerType == 'folder') {
authenticate(task, 'gdrive', accountId);
}
2014-03-18 01:10:22 +00:00
else {
accountId = 'google.picasa0';
authenticate(task, 'picasa', accountId);
}
2013-05-29 19:55:23 +00:00
loadPicker(task);
task.onRun(function() {
2013-12-27 00:01:11 +00:00
var authorizationMgr = authorizationMgrMap[accountId];
2013-05-29 19:55:23 +00:00
var pickerBuilder = new google.picker.PickerBuilder();
2013-11-05 23:03:38 +00:00
pickerBuilder.setAppId(constants.GOOGLE_DRIVE_APP_ID);
var view;
2013-08-23 23:50:14 +00:00
if(pickerType == 'doc') {
2013-11-05 23:03:38 +00:00
view = new google.picker.DocsView(google.picker.ViewId.DOCS);
2013-12-25 21:14:22 +00:00
view.setParent('root');
2013-08-23 23:50:14 +00:00
view.setIncludeFolders(true);
2013-07-20 01:08:17 +00:00
view.setMimeTypes([
"text/x-markdown",
"text/plain",
"application/octet-stream",
2013-11-05 23:03:38 +00:00
"application/vnd.google-apps.drive-sdk." + constants.GOOGLE_DRIVE_APP_ID
2013-07-20 01:08:17 +00:00
].join(","));
2013-06-02 00:38:23 +00:00
pickerBuilder.enableFeature(google.picker.Feature.NAV_HIDDEN);
pickerBuilder.enableFeature(google.picker.Feature.MULTISELECT_ENABLED);
pickerBuilder.addView(view);
2013-12-27 00:01:11 +00:00
authorizationMgr && authorizationMgr.token && pickerBuilder.setOAuthToken(authorizationMgr.token.access_token);
2013-06-02 00:38:23 +00:00
}
2013-08-23 23:50:14 +00:00
else if(pickerType == 'folder') {
2013-11-05 23:03:38 +00:00
view = new google.picker.DocsView(google.picker.ViewId.FOLDERS);
2013-12-25 21:14:22 +00:00
view.setParent('root');
2013-08-23 23:50:14 +00:00
view.setIncludeFolders(true);
view.setSelectFolderEnabled(true);
view.setMimeTypes('application/vnd.google-apps.folder');
pickerBuilder.enableFeature(google.picker.Feature.NAV_HIDDEN);
pickerBuilder.addView(view);
2013-12-27 00:01:11 +00:00
authorizationMgr && authorizationMgr.token && pickerBuilder.setOAuthToken(authorizationMgr.token.access_token);
2013-08-23 23:50:14 +00:00
}
else if(pickerType == 'img') {
view = new google.picker.PhotosView();
view.setType('flat');
pickerBuilder.addView(view);
view = new google.picker.PhotosView();
view.setType('ofuser');
pickerBuilder.addView(view);
2013-06-02 00:38:23 +00:00
pickerBuilder.addView(google.picker.ViewId.PHOTO_UPLOAD);
2014-03-18 01:10:22 +00:00
authorizationMgr && authorizationMgr.token && pickerBuilder.setOAuthToken(authorizationMgr.token.access_token);
2013-05-29 19:55:23 +00:00
}
pickerBuilder.setCallback(function(data) {
if(data.action == google.picker.Action.PICKED || data.action == google.picker.Action.CANCEL) {
if(data.action == google.picker.Action.PICKED) {
2013-06-02 00:38:23 +00:00
docs = data.docs;
2013-05-29 19:55:23 +00:00
}
hidePicker();
task.chain();
}
});
picker = pickerBuilder.build();
2013-08-12 22:08:22 +00:00
$(utils.createBackdrop()).click(function() {
2013-05-29 19:55:23 +00:00
hidePicker();
task.chain();
2013-08-12 22:08:22 +00:00
});
2013-05-29 19:55:23 +00:00
picker.setVisible(true);
});
task.onSuccess(function() {
2013-06-02 00:38:23 +00:00
callback(undefined, docs);
2013-05-29 19:55:23 +00:00
});
task.onError(function(error) {
hidePicker();
callback(error);
});
2013-06-16 10:47:35 +00:00
task.enqueue();
2013-05-29 19:55:23 +00:00
};
googleHelper.uploadBlogger = function(blogUrl, blogId, postId, labelList, isDraft, publishDate, title, content, callback) {
2013-12-27 00:01:11 +00:00
var accountId = 'google.blogger0';
2013-06-16 10:47:35 +00:00
var task = new AsyncTask();
2013-05-29 19:55:23 +00:00
connect(task);
2013-12-27 00:01:11 +00:00
authenticate(task, 'blogger', accountId);
2013-05-29 19:55:23 +00:00
task.onRun(function() {
var headers = {};
2013-12-27 00:01:11 +00:00
var authorizationMgr = authorizationMgrMap[accountId];
if(authorizationMgr && authorizationMgr.token) {
headers.Authorization = "Bearer " + authorizationMgr.token.access_token;
2013-05-29 19:55:23 +00:00
}
function uploadPost() {
2013-05-29 19:55:23 +00:00
var url = "https://www.googleapis.com/blogger/v3/blogs/" + blogId + "/posts/";
var data = {
kind: "blogger#post",
blog: {
id: blogId
},
labels: labelList,
title: title,
content: content
};
var type = "POST";
// If it's an update
if(postId !== undefined) {
url += postId;
data.id = postId;
type = "PUT";
}
$.ajax({
url: url,
data: JSON.stringify(data),
headers: headers,
type: type,
contentType: "application/json",
dataType: "json",
2013-11-05 23:03:38 +00:00
timeout: constants.AJAX_TIMEOUT
}).done(function(post) {
2013-05-29 19:55:23 +00:00
postId = post.id;
task.chain(publish);
2013-05-29 19:55:23 +00:00
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
if(error.code === 404 && postId !== undefined) {
error = 'Post ' + postId + ' not found on Blogger.|removePublish';
}
handleError(error, task);
});
}
function publish() {
var url = "https://www.googleapis.com/blogger/v3/blogs/" + blogId + "/posts/" + postId;
if(isDraft) {
url += "/revert";
}
else {
url += "/publish";
if(publishDate) {
url += '?publishDate=' + publishDate.toISOString();
}
}
$.ajax({
url: url,
headers: headers,
type: 'POST',
dataType: "json",
timeout: constants.AJAX_TIMEOUT
2013-12-08 18:13:58 +00:00
}).done(function() {
task.chain();
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
if(error.code === 404) {
error = 'Post ' + postId + ' not found on Blogger.|removePublish';
}
handleError(error, task);
});
}
2013-05-29 19:55:23 +00:00
function getBlogId() {
if(blogId !== undefined) {
task.chain(uploadPost);
2013-05-29 19:55:23 +00:00
return;
}
$.ajax({
url: "https://www.googleapis.com/blogger/v3/blogs/byurl",
data: {
url: blogUrl
},
headers: headers,
dataType: "json",
2013-11-05 23:03:38 +00:00
timeout: constants.AJAX_TIMEOUT
}).done(function(blog) {
2013-05-29 19:55:23 +00:00
blogId = blog.id;
task.chain(uploadPost);
2013-05-29 19:55:23 +00:00
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
if(error.code === 404) {
error = 'Blog "' + blogUrl + '" not found on Blogger.|removePublish';
}
handleError(error, task);
});
}
task.chain(getBlogId);
});
task.onSuccess(function() {
callback(undefined, blogId, postId);
});
task.onError(function(error) {
callback(error);
});
2013-06-16 10:47:35 +00:00
task.enqueue();
2013-05-29 19:55:23 +00:00
};
2014-01-19 13:31:36 +00:00
googleHelper.uploadBloggerPage = function(blogUrl, blogId, pageId, isDraft, publishDate, title, content, callback) {
var accountId = 'google.blogger0';
var task = new AsyncTask();
connect(task);
authenticate(task, 'blogger', accountId);
task.onRun(function() {
var headers = {};
var authorizationMgr = authorizationMgrMap[accountId];
if(authorizationMgr && authorizationMgr.token) {
headers.Authorization = "Bearer " + authorizationMgr.token.access_token;
}
function uploadPage() {
var url = "https://www.googleapis.com/blogger/v3/blogs/" + blogId + "/pages/";
var data = {
kind: "blogger#page",
blog: {
id: blogId
},
title: title,
content: content
};
var type = "POST";
// If it's an update
if(pageId !== undefined) {
url += pageId;
data.id = pageId;
type = "PUT";
}
$.ajax({
url: url,
data: JSON.stringify(data),
headers: headers,
type: type,
contentType: "application/json",
dataType: "json",
timeout: constants.AJAX_TIMEOUT
}).done(function(page) {
pageId = page.id;
task.chain();
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
if(error.code === 404 && pageId !== undefined) {
error = 'Page ' + pageId + ' not found on Blogger.|removePublish';
}
handleError(error, task);
});
}
function getBlogId() {
if(blogId !== undefined) {
task.chain(uploadPage);
return;
}
$.ajax({
url: "https://www.googleapis.com/blogger/v3/blogs/byurl",
data: {
url: blogUrl
},
headers: headers,
dataType: "json",
timeout: constants.AJAX_TIMEOUT
}).done(function(blog) {
blogId = blog.id;
task.chain(uploadPage);
}).fail(function(jqXHR) {
var error = {
code: jqXHR.status,
message: jqXHR.statusText
};
// Handle error
if(error.code === 404) {
error = 'Blog "' + blogUrl + '" not found on Blogger.|removePublish';
}
handleError(error, task);
});
}
task.chain(getBlogId);
});
task.onSuccess(function() {
callback(undefined, blogId, pageId);
});
task.onError(function(error) {
callback(error);
});
task.enqueue();
};
2014-03-19 22:10:59 +00:00
2013-12-14 22:44:59 +00:00
// Use by Google's client.js
window.delayedFunction = undefined;
window.runDelayedFunction = function() {
if(window.delayedFunction !== undefined) {
window.delayedFunction();
}
};
2014-03-19 22:10:59 +00:00
2013-05-29 19:55:23 +00:00
return googleHelper;
2013-04-02 18:42:47 +00:00
});