Async sync

This commit is contained in:
Mo Bitar
2018-06-29 10:57:56 -05:00
parent d6c26bd344
commit 7849c00f7d
14 changed files with 52 additions and 378 deletions

View File

@@ -207,7 +207,7 @@ angular.module('app')
}
// Lots of dirtying can happen above, so we'll sync
syncManager.sync("editorMenuOnSelect");
syncManager.sync();
}.bind(this)
this.hasAvailableExtensions = function() {

View File

@@ -94,16 +94,16 @@ angular.module('app')
this.refreshData = function() {
this.isRefreshing = true;
syncManager.sync((response) => {
syncManager.sync({force: true}).then((response) => {
$timeout(function(){
this.isRefreshing = false;
}.bind(this), 200)
if(response && response.error) {
alert("There was an error syncing. Please try again. If all else fails, log out and log back in.");
alert("There was an error syncing. Please try again. If all else fails, try signing out and signing back in.");
} else {
this.syncUpdated();
}
}, {force: true}, "refreshData");
});
}
this.syncUpdated = function() {

View File

@@ -26,7 +26,7 @@ angular.module('app')
/* Used to avoid circular dependencies where syncManager cannot be imported but rootScope can */
$rootScope.sync = function(source) {
syncManager.sync("$rootScope.sync - " + source);
syncManager.sync();
}
$rootScope.lockApplication = function() {
@@ -34,7 +34,7 @@ angular.module('app')
window.location.reload();
}
function async load() {
function load() {
// pass keys to storageManager to decrypt storage
// Update: Wait, why? passcodeManager already handles this.
// storageManager.setKeys(passcodeManager.keys());
@@ -66,7 +66,7 @@ angular.module('app')
dbManager.openDatabase(null, function() {
// new database, delete syncToken so that items can be refetched entirely from server
syncManager.clearSyncToken();
syncManager.sync("openDatabase");
syncManager.sync();
})
}
@@ -94,10 +94,10 @@ angular.module('app')
$rootScope.$broadcast("initial-data-loaded");
syncManager.sync("initiateSync");
syncManager.sync();
// refresh every 30s
setInterval(function () {
syncManager.sync("timer");
syncManager.sync();
}, 30000);
});
}
@@ -148,7 +148,7 @@ angular.module('app')
}
note.setDirty(true);
syncManager.sync("updateTagsForNote");
syncManager.sync();
}
/*
@@ -178,7 +178,7 @@ angular.module('app')
return;
}
tag.setDirty(true);
syncManager.sync(callback, null, "tagsSave");
syncManager.sync().then(callback);
$rootScope.$broadcast("tag-changed");
modelManager.resortTag(tag);
}
@@ -191,10 +191,10 @@ angular.module('app')
if(confirm("Are you sure you want to delete this tag? Note: deleting a tag will not delete its notes.")) {
modelManager.setItemToBeDeleted(tag);
// if no more notes, delete tag
syncManager.sync(function(){
syncManager.sync().then(() => {
// force scope tags to update on sub directives
$scope.safeApply();
}, null, "removeTag");
});
}
}
@@ -218,7 +218,7 @@ angular.module('app')
$scope.saveNote = function(note, callback) {
note.setDirty(true);
syncManager.sync(function(response){
syncManager.sync().then((response) => {
if(response && response.error) {
if(!$scope.didShowErrorAlert) {
$scope.didShowErrorAlert = true;
@@ -233,7 +233,7 @@ angular.module('app')
callback(true);
}
}
}, null, "saveNote")
})
}
$scope.safeApply = function(fn) {
@@ -264,7 +264,7 @@ angular.module('app')
return;
}
syncManager.sync(function(){
syncManager.sync().then(() => {
if(authManager.offline()) {
// when deleting items while ofline, we need to explictly tell angular to refresh UI
setTimeout(function () {
@@ -274,7 +274,7 @@ angular.module('app')
} else {
$rootScope.notifyDelete();
}
}, null, "deleteNote");
});
}

View File

@@ -89,7 +89,7 @@ class AccountMenu {
else {
$scope.onAuthSuccess(() => {
syncManager.unlockSyncing();
syncManager.sync("onLogin");
syncManager.sync();
});
}
});
@@ -114,7 +114,7 @@ class AccountMenu {
alert(error.message);
} else {
$scope.onAuthSuccess(() => {
syncManager.sync("onRegister");
syncManager.sync();
});
}
});
@@ -163,9 +163,9 @@ class AccountMenu {
// See: https://github.com/standardnotes/desktop/issues/131
$scope.clearDatabaseAndRewriteAllItems = function(alternateUuids, callback) {
storageManager.clearAllModels(() => {
syncManager.markAllItemsDirtyAndSaveOffline(function(){
syncManager.markAllItemsDirtyAndSaveOffline(alternateUuids).then(() => {
callback && callback();
}, alternateUuids)
})
});
}
@@ -242,7 +242,7 @@ class AccountMenu {
}
$scope.importJSONData = function(data, password, callback) {
var onDataReady = function(errorCount) {
var onDataReady = (errorCount) => {
var items = modelManager.mapResponseItemsToLocalModels(data.items, SFModelManager.MappingSourceFileImport);
items.forEach(function(item){
item.setDirty(true, true);
@@ -256,10 +256,10 @@ class AccountMenu {
}
})
syncManager.sync((response) => {
syncManager.sync({additionalFields: ["created_at", "updated_at"]}).then((response) => {
callback(response, errorCount);
}, {additionalFields: ["created_at", "updated_at"]}, "importJSONData");
}.bind(this)
});
}
if(data.auth_params) {
SFJS.crypto.computeEncryptionKeysForUser(password, data.auth_params).then((keys) => {

View File

@@ -53,7 +53,7 @@ class EditorMenu {
component.setAppDataItem("defaultEditor", true);
component.setDirty(true);
syncManager.sync("makeEditorDefault");
syncManager.sync();
$scope.defaultEditor = component;
}
@@ -61,7 +61,7 @@ class EditorMenu {
$scope.removeEditorDefault = function(component) {
component.setAppDataItem("defaultEditor", false);
component.setDirty(true);
syncManager.sync("removeEditorDefault");
syncManager.sync();
$scope.defaultEditor = null;
}

View File

@@ -188,7 +188,7 @@ class PasswordWizard {
$scope.resyncData = function(callback) {
modelManager.setAllItemsDirty();
syncManager.sync((response) => {
syncManager.sync().then((response) => {
if(response.error) {
alert(FailedSyncMessage)
$timeout(() => callback(false));
@@ -208,7 +208,7 @@ class PasswordWizard {
let newAuthParams = results.authParams;
// perform a sync beforehand to pull in any last minutes changes before we change the encryption key (and thus cant decrypt new changes)
syncManager.sync((response) => {
syncManager.sync().then((response) => {
authManager.changePassword(authManager.user.email, currentServerPw, newKeys, newAuthParams).then((response) => {
if(response.error) {
alert(response.error.message ? response.error.message : "There was an error changing your password. Please try again.");
@@ -217,7 +217,7 @@ class PasswordWizard {
$timeout(() => callback(true));
}
})
}, null, "submitPasswordChange")
})
});
}
}

View File

@@ -78,7 +78,7 @@ class ActionsManager {
for(var mappedItem of items) {
mappedItem.setDirty(true);
}
this.syncManager.sync(null);
this.syncManager.sync();
customCallback({item: item});
} else {
item = this.modelManager.createItem(item, true /* Dont notify observers */);
@@ -122,7 +122,7 @@ class ActionsManager {
switch (action.verb) {
case "get": {
this.httpManager.getAbsolute(action.url, {}, (response) => {
this.httpManager.getAbsolute(action.url, {}, async (response) => {
action.error = false;
handleResponseDecryption(response, await this.authManager.keys(), true);
}, (response) => {
@@ -134,7 +134,7 @@ class ActionsManager {
case "render": {
this.httpManager.getAbsolute(action.url, {}, (response) => {
this.httpManager.getAbsolute(action.url, {}, async (response) => {
action.error = false;
handleResponseDecryption(response, await this.authManager.keys(), false);
}, (response) => {

View File

@@ -166,7 +166,7 @@ class AuthManager extends SFAuthManager {
var prefs = new SFItem({content_type: prefsContentType});
this.modelManager.addItem(prefs);
prefs.setDirty(true);
this.$rootScope.sync("authManager singletonCreate");
this.$rootScope.sync();
valueCallback(prefs);
});
}
@@ -177,7 +177,7 @@ class AuthManager extends SFAuthManager {
syncUserPreferences() {
this.userPreferences.setDirty(true);
this.$rootScope.sync("syncUserPreferences");
this.$rootScope.sync();
}
getUserPrefValue(key, defaultValue) {
@@ -193,6 +193,6 @@ class AuthManager extends SFAuthManager {
this.syncUserPreferences();
}
}
});
}
angular.module('app').service('authManager', AuthManager);

View File

@@ -479,13 +479,13 @@ class ComponentManager {
item.setDirty(true);
}
this.syncManager.sync((response) => {
this.syncManager.sync().then((response) => {
// Allow handlers to be notified when a save begins and ends, to update the UI
var saveMessage = Object.assign({}, message);
saveMessage.action = response && response.error ? "save-error" : "save-success";
this.replyToMessage(component, message, {error: response.error})
this.handleMessage(component, saveMessage);
}, null, "handleSaveItemsMessage");
});
});
}
@@ -513,7 +513,7 @@ class ComponentManager {
processedItems.push(item);
}
this.syncManager.sync("handleCreateItemMessage");
this.syncManager.sync();
// "create-item" or "create-items" are possible messages handled here
let reply =
@@ -548,7 +548,7 @@ class ComponentManager {
this.modelManager.setItemToBeDeleted(model);
}
this.syncManager.sync("handleDeleteItemsMessage");
this.syncManager.sync();
}
});
}
@@ -564,7 +564,7 @@ class ComponentManager {
this.runWithPermissions(component, [], () => {
component.componentData = message.data.componentData;
component.setDirty(true);
this.syncManager.sync("handleSetComponentDataMessage");
this.syncManager.sync();
});
}
@@ -657,7 +657,7 @@ class ComponentManager {
}
}
component.setDirty(true);
this.syncManager.sync("promptForPermissions");
this.syncManager.sync();
}
this.permissionDialogs = this.permissionDialogs.filter((pendingDialog) => {
@@ -760,7 +760,7 @@ class ComponentManager {
if(didChange && !dontSync) {
component.setDirty(true);
this.syncManager.sync("activateComponent");
this.syncManager.sync();
}
if(!this.activeComponents.includes(component)) {
@@ -785,7 +785,7 @@ class ComponentManager {
if(didChange && !dontSync) {
component.setDirty(true);
this.syncManager.sync("deactivateComponent");
this.syncManager.sync();
}
_.pull(this.activeComponents, component);
@@ -851,7 +851,7 @@ class ComponentManager {
deleteComponent(component) {
this.modelManager.setItemToBeDeleted(component);
this.syncManager.sync("deleteComponent");
this.syncManager.sync();
}
isComponentActive(component) {

View File

@@ -100,7 +100,7 @@ class DesktopManager {
component.setAppDataItem("installError", null);
}
component.setDirty(true);
this.syncManager.sync("onComponentInstallationComplete");
this.syncManager.sync();
this.timeout(() => {
for(var observer of this.updateObservers) {

View File

@@ -52,7 +52,7 @@ class MigrationManager {
this.modelManager.setItemToBeDeleted(editor);
}
this.syncManager.sync("addEditorToComponentMigrator");
this.syncManager.sync();
}
})
}

View File

@@ -40,7 +40,7 @@ class NativeExtManager {
if(needsSync) {
resolvedSingleton.setDirty(true);
this.syncManager.sync("resolveExtensionsManager");
this.syncManager.sync();
}
}, (valueCallback) => {
// Safe to create. Create and return object.
@@ -81,7 +81,7 @@ class NativeExtManager {
this.modelManager.addItem(component);
component.setDirty(true);
this.syncManager.sync("resolveExtensionsManager createNew");
this.syncManager.sync();
this.systemExtensions.push(component.uuid);
@@ -110,7 +110,7 @@ class NativeExtManager {
if(needsSync) {
resolvedSingleton.setDirty(true);
this.syncManager.sync("resolveExtensionsManager");
this.syncManager.sync();
}
}, (valueCallback) => {
// Safe to create. Create and return object.
@@ -151,7 +151,7 @@ class NativeExtManager {
this.modelManager.addItem(component);
component.setDirty(true);
this.syncManager.sync("resolveBatchManager createNew");
this.syncManager.sync();
this.systemExtensions.push(component.uuid);

View File

@@ -1,326 +0,0 @@
// angular.module('app')
// .provider('authManager', function () {
//
// function domainName() {
// var domain_comps = location.hostname.split(".");
// var domain = domain_comps[domain_comps.length - 2] + "." + domain_comps[domain_comps.length - 1];
// return domain;
// }
//
// this.$get = function($rootScope, $timeout, httpManager, modelManager, dbManager, storageManager, singletonManager, $compile) {
// return new AuthManager($rootScope, $timeout, httpManager, modelManager, dbManager, storageManager, singletonManager, $compile);
// }
//
// function AuthManager($rootScope, $timeout, httpManager, modelManager, dbManager, storageManager, singletonManager, $compile) {
//
// this.loadInitialData = function() {
// var userData = storageManager.getItem("user");
// if(userData) {
// this.user = JSON.parse(userData);
// } else {
// // legacy, check for uuid
// var idData = storageManager.getItem("uuid");
// if(idData) {
// this.user = {uuid: idData};
// }
// }
//
// this.checkForSecurityUpdate();
// }
//
// this.offline = function() {
// return !this.user;
// }
//
// this.isEphemeralSession = function() {
// if(this.ephemeral == null || this.ephemeral == undefined) {
// this.ephemeral = JSON.parse(storageManager.getItem("ephemeral", StorageManager.Fixed));
// }
// return this.ephemeral;
// }
//
// this.setEphemeral = function(ephemeral) {
// this.ephemeral = ephemeral;
// if(ephemeral) {
// storageManager.setModelStorageMode(StorageManager.Ephemeral);
// storageManager.setItemsMode(StorageManager.Ephemeral);
// } else {
// storageManager.setModelStorageMode(StorageManager.Fixed);
// storageManager.setItemsMode(storageManager.hasPasscode() ? StorageManager.FixedEncrypted : StorageManager.Fixed);
// storageManager.setItem("ephemeral", JSON.stringify(false), StorageManager.Fixed);
// }
// }
//
// this.getAuthParams = function() {
// if(!this._authParams) {
// this._authParams = JSON.parse(storageManager.getItem("auth_params"));
// }
// return this._authParams;
// }
//
// this.keys = function() {
// if(!this._keys) {
// var mk = storageManager.getItem("mk");
// if(!mk) {
// return null;
// }
// this._keys = {mk: mk, ak: storageManager.getItem("ak")};
// }
// return this._keys;
// }
//
// this.protocolVersion = function() {
// var authParams = this.getAuthParams();
// if(authParams && authParams.version) {
// return authParams.version;
// }
//
// var keys = this.keys();
// if(keys && keys.ak) {
// // If there's no version stored, and there's an ak, it has to be 002. Newer versions would have thier version stored in authParams.
// return "002";
// } else {
// return "001";
// }
// }
//
// this.getAuthParamsForEmail = function(url, email, extraParams, callback) {
// var requestUrl = url + "/auth/params";
// httpManager.getAbsolute(requestUrl, _.merge({email: email}, extraParams), function(response){
// callback(response);
// }, function(response){
// console.error("Error getting auth params", response);
// if(typeof response !== 'object') {
// response = {error: {message: "A server error occurred while trying to sign in. Please try again."}};
// }
// callback(response);
// })
// }
//
// this.login = function(url, email, password, ephemeral, strictSignin, extraParams, callback) {
// this.getAuthParamsForEmail(url, email, extraParams, (authParams) => {
//
// // SF3 requires a unique identifier in the auth params
// authParams.identifier = email;
//
// if(authParams.error) {
// callback(authParams);
// return;
// }
//
// if(!authParams || !authParams.pw_cost) {
// callback({error : {message: "Invalid email or password."}});
// return;
// }
//
// if(!SFJS.supportedVersions().includes(authParams.version)) {
// var message;
// if(SFJS.isVersionNewerThanLibraryVersion(authParams.version)) {
// // The user has a new account type, but is signing in to an older client.
// message = "This version of the application does not support your newer account type. Please upgrade to the latest version of Standard Notes to sign in.";
// } else {
// // The user has a very old account type, which is no longer supported by this client
// message = "The protocol version associated with your account is outdated and no longer supported by this application. Please visit standardnotes.org/help/security for more information.";
// }
// callback({error: {message: message}});
// return;
// }
//
// if(SFJS.isProtocolVersionOutdated(authParams.version)) {
// let message = `The encryption version for your account, ${authParams.version}, is outdated and requires upgrade. You may proceed with login, but are advised to follow prompts for Security Updates once inside. Please visit standardnotes.org/help/security for more information.\n\nClick 'OK' to proceed with login.`
// if(!confirm(message)) {
// callback({error: {}});
// return;
// }
// }
//
// if(!SFJS.supportsPasswordDerivationCost(authParams.pw_cost)) {
// let message = "Your account was created on a platform with higher security capabilities than this browser supports. " +
// "If we attempted to generate your login keys here, it would take hours. " +
// "Please use a browser with more up to date security capabilities, like Google Chrome or Firefox, to log in."
// callback({error: {message: message}});
// return;
// }
//
// var minimum = SFJS.costMinimumForVersion(authParams.version);
// if(authParams.pw_cost < minimum) {
// let message = "Unable to login due to insecure password parameters. Please visit standardnotes.org/help/security for more information.";
// callback({error: {message: message}});
// return;
// }
//
// if(strictSignin) {
// // Refuse sign in if authParams.version is anything but the latest version
// var latestVersion = SFJS.version();
// if(authParams.version !== latestVersion) {
// let message = `Strict sign in refused server sign in parameters. The latest security version is ${latestVersion}, but your account is reported to have version ${authParams.version}. If you'd like to proceed with sign in anyway, please disable strict sign in and try again.`;
// callback({error: {message: message}});
// return;
// }
// }
//
// SFJS.crypto.computeEncryptionKeysForUser(password, authParams).then((keys) => {
// var requestUrl = url + "/auth/sign_in";
// var params = _.merge({password: keys.pw, email: email}, extraParams);
//
// httpManager.postAbsolute(requestUrl, params, (response) => {
// this.setEphemeral(ephemeral);
// this.handleAuthResponse(response, email, url, authParams, keys);
// this.checkForSecurityUpdate();
// $timeout(() => callback(response));
// }, (response) => {
// console.error("Error logging in", response);
// if(typeof response !== 'object') {
// response = {error: {message: "A server error occurred while trying to sign in. Please try again."}};
// }
// $timeout(() => callback(response));
// });
//
// });
// })
// }
//
// this.handleAuthResponse = function(response, email, url, authParams, keys) {
// try {
// if(url) {
// storageManager.setItem("server", url);
// }
//
// this.user = response.user;
// storageManager.setItem("user", JSON.stringify(response.user));
//
// this._authParams = authParams;
// storageManager.setItem("auth_params", JSON.stringify(authParams));
//
// storageManager.setItem("jwt", response.token);
// this.saveKeys(keys);
// } catch(e) {
// dbManager.displayOfflineAlert();
// }
// }
//
// this.saveKeys = function(keys) {
// this._keys = keys;
// // pw doesn't need to be saved.
// // storageManager.setItem("pw", keys.pw);
// storageManager.setItem("mk", keys.mk);
// storageManager.setItem("ak", keys.ak);
// }
//
// this.register = function(url, email, password, ephemeral, callback) {
// SFJS.crypto.generateInitialKeysAndAuthParamsForUser(email, password).then((results) => {
// let keys = results.keys;
// let authParams = results.authParams;
//
// var requestUrl = url + "/auth";
// var params = _.merge({password: keys.pw, email: email}, authParams);
//
// httpManager.postAbsolute(requestUrl, params, (response) => {
// this.setEphemeral(ephemeral);
// this.handleAuthResponse(response, email, url, authParams, keys);
// callback(response);
// }, (response) => {
// console.error("Registration error", response);
// if(typeof response !== 'object') {
// response = {error: {message: "A server error occurred while trying to register. Please try again."}};
// }
// callback(response);
// })
// });
// }
//
// this.changePassword = function(current_server_pw, newKeys, newAuthParams, callback) {
// let email = this.user.email;
// let newServerPw = newKeys.pw;
//
// var requestUrl = storageManager.getItem("server") + "/auth/change_pw";
// var params = _.merge({new_password: newServerPw, current_password: current_server_pw}, newAuthParams);
//
// httpManager.postAbsolute(requestUrl, params, (response) => {
// this.handleAuthResponse(response, email, null, newAuthParams, newKeys);
// callback(response);
//
// // Allows security update status to be changed if neccessary
// this.checkForSecurityUpdate();
// }, (response) => {
// if(typeof response !== 'object') {
// response = {error: {message: "Something went wrong while changing your password. Your password was not changed. Please try again."}}
// }
// callback(response);
// })
// }
//
// this.checkForSecurityUpdate = function() {
// if(this.offline()) {
// return false;
// }
//
// let latest = SFJS.version();
// let updateAvailable = this.protocolVersion() !== latest;
// if(updateAvailable !== this.securityUpdateAvailable) {
// this.securityUpdateAvailable = updateAvailable;
// $rootScope.$broadcast("security-update-status-changed");
// }
//
// return this.securityUpdateAvailable;
// }
//
// this.presentPasswordWizard = function(type) {
// var scope = $rootScope.$new(true);
// scope.type = type;
// var el = $compile( "<password-wizard type='type'></password-wizard>" )(scope);
// angular.element(document.body).append(el);
// }
//
// this.staticifyObject = function(object) {
// return JSON.parse(JSON.stringify(object));
// }
//
// this.signOut = function() {
// this._keys = null;
// this.user = null;
// this._authParams = null;
// }
//
//
// /* User Preferences */
//
// let prefsContentType = "SN|UserPreferences";
//
// singletonManager.registerSingleton({content_type: prefsContentType}, (resolvedSingleton) => {
// this.userPreferences = resolvedSingleton;
// this.userPreferencesDidChange();
// }, (valueCallback) => {
// // Safe to create. Create and return object.
// var prefs = new SFItem({content_type: prefsContentType});
// modelManager.addItem(prefs);
// prefs.setDirty(true);
// $rootScope.sync("authManager singletonCreate");
// valueCallback(prefs);
// });
//
// this.userPreferencesDidChange = function() {
// $rootScope.$broadcast("user-preferences-changed");
// }
//
// this.syncUserPreferences = function() {
// this.userPreferences.setDirty(true);
// $rootScope.sync("syncUserPreferences");
// }
//
// this.getUserPrefValue = function(key, defaultValue) {
// if(!this.userPreferences) { return defaultValue; }
// var value = this.userPreferences.getAppDataItem(key);
// return (value !== undefined && value != null) ? value : defaultValue;
// }
//
// this.setUserPrefValue = function(key, value, sync) {
// if(!this.userPreferences) { console.log("Prefs are null, not setting value", key); return; }
// this.userPreferences.setAppDataItem(key, value);
// if(sync) {
// this.syncUserPreferences();
// }
// }
//
// }
// });

View File

@@ -92,7 +92,7 @@ class SingletonManager {
this.modelManager.setItemToBeDeleted(d);
}
this.$rootScope.sync("resolveSingletons");
this.$rootScope.sync();
// Send remaining item to callback
singletonHandler.singleton = winningItem;