szurubooru/public_html/js/BrowsingSettings.js

97 lines
1.7 KiB
JavaScript
Raw Normal View History

2014-09-07 14:50:16 +02:00
var App = App || {};
App.BrowsingSettings = function(
promise,
auth,
api) {
var settings = getDefaultSettings();
auth.startObservingLoginChanges('browsing-settings', loginStateChanged);
2014-09-07 14:50:16 +02:00
readFromLocalStorage();
2014-09-08 22:02:28 +02:00
if (auth.isLoggedIn()) {
2014-09-07 14:50:16 +02:00
loginStateChanged();
2014-09-08 22:02:28 +02:00
}
2014-09-07 14:50:16 +02:00
function setSettings(newSettings) {
settings = newSettings;
return save();
}
function getSettings() {
return settings;
}
function getDefaultSettings() {
return {
hideDownvoted: true,
endlessScroll: false,
2014-09-07 14:50:16 +02:00
listPosts: {
safe: true,
sketchy: true,
unsafe: true,
},
};
}
function loginStateChanged() {
readFromUser(auth.getCurrentUser());
}
function readFromLocalStorage() {
readFromString(localStorage.getItem('browsingSettings'));
}
function readFromUser(user) {
readFromString(user.browsingSettings);
}
function readFromString(string) {
2014-09-08 22:02:28 +02:00
if (!string) {
2014-09-07 14:50:16 +02:00
return;
2014-09-08 22:02:28 +02:00
}
2014-09-07 14:50:16 +02:00
try {
if (typeof(string) === 'string' || string instanceof String) {
settings = JSON.parse(string);
} else {
settings = string;
}
2014-09-07 14:50:16 +02:00
} catch (e) {
}
}
function saveToLocalStorage() {
localStorage.setItem('browsingSettings', JSON.stringify(settings));
}
function saveToUser(user) {
var formData = {
browsingSettings: JSON.stringify(settings),
};
2014-11-28 23:18:14 +01:00
return api.post('/users/' + user.name, formData);
2014-09-07 14:50:16 +02:00
}
function save() {
return promise.make(function(resolve, reject) {
saveToLocalStorage();
if (auth.isLoggedIn()) {
2014-10-02 00:30:25 +02:00
promise.wait(saveToUser(auth.getCurrentUser()))
.then(resolve)
.fail(reject);
2014-09-07 14:50:16 +02:00
} else {
resolve();
}
});
}
return {
getSettings: getSettings,
setSettings: setSettings,
};
2014-09-08 22:02:28 +02:00
};
2014-09-07 14:50:16 +02:00
App.DI.registerSingleton('browsingSettings', ['promise', 'auth', 'api'], App.BrowsingSettings);