Secondary Google account (part6)

This commit is contained in:
benweet 2013-12-27 01:01:11 +01:00
parent 5f6c4b5450
commit 02640f1f89
2 changed files with 135 additions and 110 deletions

View File

@ -113,6 +113,8 @@ define([
authorizationMgrMap[accountId] = authorizationMgr; authorizationMgrMap[accountId] = authorizationMgr;
} }
task.onRun(function() { task.onRun(function() {
var currentToken = gapi.auth.getToken();
var newToken;
function loadGdriveClient() { function loadGdriveClient() {
if(gapi.client.drive) { if(gapi.client.drive) {
task.chain(); task.chain();
@ -126,7 +128,7 @@ define([
$.ajax({ $.ajax({
url: 'https://www.googleapis.com/oauth2/v1/tokeninfo', url: 'https://www.googleapis.com/oauth2/v1/tokeninfo',
data: { data: {
access_token: gapi.auth.getToken().access_token access_token: newToken.access_token
}, },
timeout: constants.AJAX_TIMEOUT, timeout: constants.AJAX_TIMEOUT,
type: "GET" type: "GET"
@ -138,7 +140,7 @@ define([
else { else {
authorizationMgr.setUserId(data.user_id); authorizationMgr.setUserId(data.user_id);
authorizationMgr.add(permission); authorizationMgr.add(permission);
authorizationMgr.token = gapi.auth.getToken(); authorizationMgr.token = newToken;
task.chain(loadGdriveClient); task.chain(loadGdriveClient);
} }
}).fail(function(jqXHR) { }).fail(function(jqXHR) {
@ -166,6 +168,8 @@ define([
immediate: immediate, immediate: immediate,
authuser: immediate === false ? '' : authuser authuser: immediate === false ? '' : authuser
}, function(authResult) { }, function(authResult) {
newToken = gapi.auth.getToken();
gapi.auth.setToken(currentToken);
if(!authResult || authResult.error) { if(!authResult || authResult.error) {
if(connected === true && immediate === true) { if(connected === true && immediate === true) {
// If immediate did not work retry without immediate // If immediate did not work retry without immediate
@ -199,7 +203,6 @@ define([
function startAuthenticate() { function startAuthenticate() {
immediate = true; immediate = true;
if(authorizationMgr.token && authorizationMgr.isAuthorized(permission)) { if(authorizationMgr.token && authorizationMgr.isAuthorized(permission)) {
gapi.auth.setToken(authorizationMgr.token);
task.chain(); task.chain();
return; return;
} }
@ -219,6 +222,14 @@ define([
authenticate(task, 'gdrive', accountId); authenticate(task, 'gdrive', accountId);
task.enqueue(); task.enqueue();
}; };
function runWithToken(accountId, functionToRun) {
var currentToken = gapi.auth.getToken();
var authorizationMgr = authorizationMgrMap[accountId];
gapi.auth.setToken(authorizationMgr.token);
functionToRun();
gapi.auth.setToken(currentToken);
}
googleHelper.upload = function(fileId, parentId, title, content, contentType, etag, accountId, callback) { googleHelper.upload = function(fileId, parentId, title, content, contentType, etag, accountId, callback) {
var result; var result;
@ -274,36 +285,38 @@ define([
close_delim close_delim
].join(""); ].join("");
var request = gapi.client.request({ runWithToken(accountId, function() {
'path': path, var request = gapi.client.request({
'method': method, 'path': path,
'params': { 'method': method,
'uploadType': 'multipart', 'params': {
}, 'uploadType': 'multipart',
'headers': headers, },
'body': multipartRequestBody, 'headers': headers,
}); 'body': multipartRequestBody,
request.execute(function(response) { });
if(response && response.id) { request.execute(function(response) {
// Upload success if(response && response.id) {
result = response; // Upload success
result.content = content; result = response;
task.chain(); result.content = content;
return; task.chain();
} return;
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) { var error = response.error;
// We may have missed a file update // Handle error
storage.removeItem(accountId + ".gdrive.lastChangeId"); if(error !== undefined && fileId !== undefined) {
error = 'Conflict on file ID "' + fileId + '". Please restart the synchronization.'; 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.';
}
} }
} handleError(error, task);
handleError(error, task); });
}); });
}); });
task.onSuccess(function() { task.onSuccess(function() {
@ -322,25 +335,27 @@ define([
authenticate(task, 'gdrive', accountId); authenticate(task, 'gdrive', accountId);
task.onRun(function() { task.onRun(function() {
var body = {'title': title}; var body = {'title': title};
var request = gapi.client.drive.files.patch({ runWithToken(accountId, function() {
'fileId': fileId, var request = gapi.client.drive.files.patch({
'resource': body 'fileId': fileId,
}); 'resource': body
request.execute(function(response) { });
if(response && response.id) { request.execute(function(response) {
// Rename success if(response && response.id) {
result = response; // Rename success
task.chain(); result = response;
return; task.chain();
} return;
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';
} }
} var error = response.error;
handleError(error, task); // 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() { task.onSuccess(function() {
@ -371,17 +386,19 @@ define([
} }
]; ];
} }
var request = gapi.client.drive.files.insert({ runWithToken(accountId, function() {
'resource': metadata var request = gapi.client.drive.files.insert({
}); 'resource': metadata
request.execute(function(response) { });
if(response && response.id) { request.execute(function(response) {
// Upload success if(response && response.id) {
result = response; // Upload success
task.chain(); result = response;
return; task.chain();
} return;
handleError(response.error, task); }
handleError(response.error, task);
});
}); });
}); });
task.onSuccess(function() { task.onSuccess(function() {
@ -402,36 +419,38 @@ define([
task.onRun(function() { task.onRun(function() {
var nextPageToken; var nextPageToken;
function retrievePageOfChanges() { function retrievePageOfChanges() {
var request; runWithToken(accountId, function() {
if(nextPageToken === undefined) { var request;
request = gapi.client.drive.changes.list({ if(nextPageToken === undefined) {
'startChangeId': newChangeId + 1 request = gapi.client.drive.changes.list({
}); 'startChangeId': newChangeId + 1
} });
else {
request = gapi.client.drive.changes.list({
'pageToken': nextPageToken
});
}
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 { else {
task.chain(); request = gapi.client.drive.changes.list({
'pageToken': nextPageToken
});
} }
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();
}
});
}); });
} }
task.chain(retrievePageOfChanges); task.chain(retrievePageOfChanges);
@ -460,9 +479,9 @@ define([
} }
var id = ids[0]; var id = ids[0];
var headers = {}; var headers = {};
var token = gapi.auth.getToken(); var authorizationMgr = authorizationMgrMap[accountId];
if(token) { if(authorizationMgr && authorizationMgr.token) {
headers.Authorization = "Bearer " + token.access_token; headers.Authorization = "Bearer " + authorizationMgr.token.access_token;
} }
$.ajax({ $.ajax({
url: "https://www.googleapis.com/drive/v2/files/" + id, url: "https://www.googleapis.com/drive/v2/files/" + id,
@ -539,9 +558,9 @@ define([
return; return;
} }
var headers = {}; var headers = {};
var token = gapi.auth.getToken(); var authorizationMgr = authorizationMgrMap[accountId];
if(token) { if(authorizationMgr && authorizationMgr.token) {
headers.Authorization = "Bearer " + token.access_token; headers.Authorization = "Bearer " + authorizationMgr.token.access_token;
} }
$.ajax({ $.ajax({
url: file.downloadUrl, url: file.downloadUrl,
@ -581,6 +600,8 @@ define([
connect(task); connect(task);
authenticate(task, 'gdrive', accountId); authenticate(task, 'gdrive', accountId);
task.onRun(function() { task.onRun(function() {
var authorizationMgr = authorizationMgrMap[accountId];
gapi.auth.setToken(authorizationMgr.token);
gapi.drive.realtime.load(fileId, function(result) { gapi.drive.realtime.load(fileId, function(result) {
// onFileLoaded // onFileLoaded
doc = result; doc = result;
@ -604,10 +625,11 @@ define([
}; };
googleHelper.uploadImg = function(name, content, albumId, callback) { googleHelper.uploadImg = function(name, content, albumId, callback) {
var accountId = 'google.picasa0';
var result; var result;
var task = new AsyncTask(); var task = new AsyncTask();
connect(task); connect(task);
authenticate(task, 'picasa', 'google.picasa0'); authenticate(task, 'picasa', accountId);
task.onRun(function() { task.onRun(function() {
var headers = { var headers = {
"Slug": name "Slug": name
@ -621,9 +643,9 @@ define([
else if(name.match(/.gif$/i)) { else if(name.match(/.gif$/i)) {
headers["Content-Type"] = "image/gif"; headers["Content-Type"] = "image/gif";
} }
var token = gapi.auth.getToken(); var authorizationMgr = authorizationMgrMap[accountId];
if(token) { if(authorizationMgr && authorizationMgr.token) {
headers.Authorization = "Bearer " + token.access_token; headers.Authorization = "Bearer " + authorizationMgr.token.access_token;
} }
$.ajax({ $.ajax({
@ -742,6 +764,7 @@ define([
} }
loadPicker(task); loadPicker(task);
task.onRun(function() { task.onRun(function() {
var authorizationMgr = authorizationMgrMap[accountId];
var pickerBuilder = new google.picker.PickerBuilder(); var pickerBuilder = new google.picker.PickerBuilder();
pickerBuilder.setAppId(constants.GOOGLE_DRIVE_APP_ID); pickerBuilder.setAppId(constants.GOOGLE_DRIVE_APP_ID);
var view; var view;
@ -758,7 +781,7 @@ define([
pickerBuilder.enableFeature(google.picker.Feature.NAV_HIDDEN); pickerBuilder.enableFeature(google.picker.Feature.NAV_HIDDEN);
pickerBuilder.enableFeature(google.picker.Feature.MULTISELECT_ENABLED); pickerBuilder.enableFeature(google.picker.Feature.MULTISELECT_ENABLED);
pickerBuilder.addView(view); pickerBuilder.addView(view);
pickerBuilder.setOAuthToken(gapi.auth.getToken().access_token); authorizationMgr && authorizationMgr.token && pickerBuilder.setOAuthToken(authorizationMgr.token.access_token);
} }
else if(pickerType == 'folder') { else if(pickerType == 'folder') {
view = new google.picker.DocsView(google.picker.ViewId.FOLDERS); view = new google.picker.DocsView(google.picker.ViewId.FOLDERS);
@ -768,7 +791,7 @@ define([
view.setMimeTypes('application/vnd.google-apps.folder'); view.setMimeTypes('application/vnd.google-apps.folder');
pickerBuilder.enableFeature(google.picker.Feature.NAV_HIDDEN); pickerBuilder.enableFeature(google.picker.Feature.NAV_HIDDEN);
pickerBuilder.addView(view); pickerBuilder.addView(view);
pickerBuilder.setOAuthToken(gapi.auth.getToken().access_token); authorizationMgr && authorizationMgr.token && pickerBuilder.setOAuthToken(authorizationMgr.token.access_token);
} }
else if(pickerType == 'img') { else if(pickerType == 'img') {
view = new google.picker.PhotosView(); view = new google.picker.PhotosView();
@ -806,14 +829,15 @@ define([
}; };
googleHelper.uploadBlogger = function(blogUrl, blogId, postId, labelList, isDraft, publishDate, title, content, callback) { googleHelper.uploadBlogger = function(blogUrl, blogId, postId, labelList, isDraft, publishDate, title, content, callback) {
var accountId = 'google.blogger0';
var task = new AsyncTask(); var task = new AsyncTask();
connect(task); connect(task);
authenticate(task, 'blogger', 'google.blogger0'); authenticate(task, 'blogger', accountId);
task.onRun(function() { task.onRun(function() {
var headers = {}; var headers = {};
var token = gapi.auth.getToken(); var authorizationMgr = authorizationMgrMap[accountId];
if(token) { if(authorizationMgr && authorizationMgr.token) {
headers.Authorization = "Bearer " + token.access_token; headers.Authorization = "Bearer " + authorizationMgr.token.access_token;
} }
function uploadPost() { function uploadPost() {
var url = "https://www.googleapis.com/blogger/v3/blogs/" + blogId + "/posts/"; var url = "https://www.googleapis.com/blogger/v3/blogs/" + blogId + "/posts/";

View File

@ -199,7 +199,7 @@ define([
var localTitle = fileDesc.title; var localTitle = fileDesc.title;
// File deleted // File deleted
if(change.deleted === true) { if(change.deleted === true) {
eventMgr.onError('"' + localTitle + '" has been removed from Google Drive.'); eventMgr.onError('"' + localTitle + '" has been removed from ' + providerName + '.');
fileDesc.removeSyncLocation(syncAttributes); fileDesc.removeSyncLocation(syncAttributes);
eventMgr.onSyncRemoved(fileDesc, syncAttributes); eventMgr.onSyncRemoved(fileDesc, syncAttributes);
if(syncAttributes.isRealtime === true && fileMgr.currentFile === fileDesc) { if(syncAttributes.isRealtime === true && fileMgr.currentFile === fileDesc) {
@ -226,13 +226,13 @@ define([
if(fileTitleChanged && remoteTitleChanged === true) { if(fileTitleChanged && remoteTitleChanged === true) {
fileDesc.title = file.title; fileDesc.title = file.title;
eventMgr.onTitleChanged(fileDesc); eventMgr.onTitleChanged(fileDesc);
eventMgr.onMessage('"' + localTitle + '" has been renamed to "' + file.title + '" on Google Drive.'); eventMgr.onMessage('"' + localTitle + '" has been renamed to "' + file.title + '" on ' + providerName + '.');
} }
// If file content changed // If file content changed
if(!syncAttributes.isRealtime && fileContentChanged && remoteContentChanged === true) { if(!syncAttributes.isRealtime && fileContentChanged && remoteContentChanged === true) {
fileDesc.content = file.content; fileDesc.content = file.content;
eventMgr.onContentChanged(fileDesc); eventMgr.onContentChanged(fileDesc);
eventMgr.onMessage('"' + file.title + '" has been updated from Google Drive.'); eventMgr.onMessage('"' + file.title + '" has been updated from ' + providerName + '.');
if(fileMgr.currentFile === fileDesc) { if(fileMgr.currentFile === fileDesc) {
fileMgr.selectFile(); // Refresh editor fileMgr.selectFile(); // Refresh editor
} }
@ -443,7 +443,7 @@ define([
googleHelper.refreshGdriveToken(accountId); googleHelper.refreshGdriveToken(accountId);
} }
else if(err.type == "not_found") { else if(err.type == "not_found") {
eventMgr.onError('"' + fileDesc.title + '" has been removed from Google Drive.'); eventMgr.onError('"' + fileDesc.title + '" has been removed from ' + providerName + '.');
fileDesc.removeSyncLocation(syncAttributes); fileDesc.removeSyncLocation(syncAttributes);
eventMgr.onSyncRemoved(fileDesc, syncAttributes); eventMgr.onSyncRemoved(fileDesc, syncAttributes);
gdriveProvider.stopRealtimeSync(); gdriveProvider.stopRealtimeSync();
@ -482,10 +482,11 @@ define([
$('.submenu-sync-' + providerId).toggle(settings.gdriveMultiAccount > accountIndex); $('.submenu-sync-' + providerId).toggle(settings.gdriveMultiAccount > accountIndex);
// Create export dialog // Create export dialog
document.querySelector('.modal-upload-' + providerId).innerHTML = _.template(dialogExportGdriveHTML, { var modalUploadElt = document.querySelector('.modal-upload-' + providerId);
modalUploadElt && (modalUploadElt.innerHTML = _.template(dialogExportGdriveHTML, {
providerId: providerId, providerId: providerId,
providerName: providerName providerName: providerName
}); }));
// Choose folder button in export modal // Choose folder button in export modal
$('.export-' + providerId + '-choose-folder').click(function() { $('.export-' + providerId + '-choose-folder').click(function() {
@ -522,7 +523,7 @@ define([
syncLocations[syncAttributes.syncIndex] = syncAttributes; syncLocations[syncAttributes.syncIndex] = syncAttributes;
var fileDesc = fileMgr.createFile(file.title, file.content, syncLocations); var fileDesc = fileMgr.createFile(file.title, file.content, syncLocations);
fileMgr.selectFile(fileDesc); fileMgr.selectFile(fileDesc);
eventMgr.onMessage('"' + file.title + '" created successfully on Google Drive.'); eventMgr.onMessage('"' + file.title + '" created successfully on ' + providerName + '.');
}); });
} }
else if(state.action == "open") { else if(state.action == "open") {