define(["jquery", "async-runner"], function($, asyncRunner) { // Dependencies var core = undefined; var client = undefined; var authenticated = false; var dropboxHelper = {}; // Try to connect dropbox by downloading client.js function connect(task) { task.onRun(function() { if(core.isOffline === true) { client = undefined; core.showMessage("Operation not available in offline mode."); task.error(); return; } if (client !== undefined) { task.chain(); return; } $.ajax({ url : "lib/dropbox.min.js", dataType : "script", timeout : AJAX_TIMEOUT }).done(function() { client = new Dropbox.Client({ key: DROPBOX_APP_KEY, secret: DROPBOX_APP_SECRET }); client.authDriver(new Dropbox.Drivers.Popup({ receiverUrl: BASE_URL + "dropbox-oauth-receiver.html", rememberUser: true })); task.chain(); }).fail(function() { core.setOffline(); task.error(new Error("Network timeout")); }); }); } // Try to authenticate with Oauth function authenticate(task) { task.onRun(function() { if (authenticated === true) { task.chain(); return; } var immediate = true; function localAuthenticate() { if (immediate === false) { core.showMessage("Please make sure the Dropbox authorization popup is not blocked by your browser."); // If not immediate we add time for user to enter his credentials task.timeout = ASYNC_TASK_LONG_TIMEOUT; } client.reset(); client.authenticate({interactive: !immediate}, function(error, client) { // Success if (client.authState === Dropbox.Client.DONE) { authenticated = true; task.chain(); return; } // If immediate did not work retry without immediate flag if (immediate === true) { immediate = false; task.chain(localAuthenticate); return; } // Error var errorMsg = "Access to Dropbox account is not authorized."; core.showError(errorMsg); task.error(new Error(errorMsg)); }); } task.chain(localAuthenticate); }); } dropboxHelper.upload = function(path, content, callback) { callback = callback || core.doNothing; var result = undefined; var task = asyncRunner.createTask(); connect(task); authenticate(task); task.onRun(function() { client.writeFile(path, content, function(error, stat) { if (!error) { result = stat; task.chain(); return; } // Handle error if(error.status === Dropbox.ApiError.INVALID_PARAM) { error = 'Could not upload document into path "' + path + '".'; } handleError(error, task, callback); }); }); task.onSuccess(function() { callback(undefined, result); }); task.onError(function(error) { callback(error); }); asyncRunner.addTask(task); }; dropboxHelper.checkUpdates = function(lastChangeId, callback) { callback = callback || core.doNothing; var changes = []; var newChangeId = lastChangeId || 0; var task = asyncRunner.createTask(); connect(task); authenticate(task); task.onRun(function() { function retrievePageOfChanges() { client.pullChanges(newChangeId, function(error, pullChanges) { if (error) { handleError(error, task, callback); return; } // Retrieve success newChangeId = pullChanges.cursor(); if(pullChanges.changes !== undefined) { for(var i=0; i