Refactor: Instead of getting `currentUser` from the Discourse namespace, use

`Discourse.User.current()`
This commit is contained in:
Robin Ward 2013-05-28 11:08:32 -04:00
parent 55526e24d6
commit 57f97880e6
26 changed files with 101 additions and 124 deletions

View File

@ -4,7 +4,7 @@
@class AdminDashboardController
@extends Ember.Controller
@namespace Discourse
@module Discourse
@module Discourse
**/
Discourse.AdminDashboardController = Ember.Controller.extend({
loading: true,
@ -12,11 +12,11 @@ Discourse.AdminDashboardController = Ember.Controller.extend({
problemsCheckInterval: '1 minute ago',
foundProblems: function() {
return(Discourse.currentUser.admin && this.get('problems') && this.get('problems').length > 0);
return(Discourse.User.current('admin') && this.get('problems') && this.get('problems').length > 0);
}.property('problems'),
thereWereProblems: function() {
if(!Discourse.currentUser.admin) { return false }
if(!Discourse.User.current('admin')) { return false }
if( this.get('foundProblems') ) {
this.set('hadProblems', true);
return true;

View File

@ -54,7 +54,7 @@ Discourse.AdminUser = Discourse.User.extend({
approve: function() {
this.set('can_approve', false);
this.set('approved', true);
this.set('approved_by', Discourse.get('currentUser'));
this.set('approved_by', Discourse.User.current());
Discourse.ajax("/admin/users/" + (this.get('id')) + "/approve", {type: 'PUT'});
},

View File

@ -52,38 +52,6 @@ Discourse = Ember.Application.createWithMixins({
}, 200);
}.observes('title', 'hasFocus', 'notify'),
currentUserChanged: function() {
// We don't want to receive any previous user notifications
var bus = Discourse.MessageBus;
bus.unsubscribe("/notification/*");
bus.callbackInterval = Discourse.SiteSettings.anon_polling_interval;
bus.enableLongPolling = false;
var user = this.get('currentUser');
if (user) {
bus.callbackInterval = Discourse.SiteSettings.polling_interval;
bus.enableLongPolling = true;
if (user.admin || user.moderator) {
bus.subscribe("/flagged_counts", function(data) {
user.set('site_flagged_posts_count', data.total);
});
}
bus.subscribe("/notification/" + user.id, (function(data) {
user.set('unread_notifications', data.unread_notifications);
user.set('unread_private_messages', data.unread_private_messages);
}), user.notification_channel_position);
bus.subscribe("/categories", function(data){
var site = Discourse.Site.instance();
data.categories.each(function(c){
site.updateCategory(c)
});
});
}
}.observes('currentUser'),
// The classes of buttons to show on a post
postButtons: function() {
return Discourse.SiteSettings.post_menu.split("|").map(function(i) {
@ -179,13 +147,11 @@ Discourse = Ember.Application.createWithMixins({
@method logout
**/
logout: function() {
Discourse.KeyValueStore.abandonLocal();
Discourse.ajax("/session/" + this.get('currentUser.username'), {
type: 'DELETE'
}).then(function() {
Discourse.User.logout().then(function() {
// Reloading will refresh unbound properties
Discourse.KeyValueStore.abandonLocal();
window.location.reload();
});
})
},
authenticationComplete: function(options) {

View File

@ -38,7 +38,7 @@ Discourse.ClickTrack = {
userId = $link.data('user-id');
if (!userId) userId = $article.data('user-id');
var ownLink = userId && (userId === Discourse.get('currentUser.id'));
var ownLink = userId && (userId === Discourse.User.current('id'));
// Build a Redirect URL
var trackingUrl = Discourse.getURL("/clicks/track?url=" + encodeURIComponent(href));
@ -99,7 +99,7 @@ Discourse.ClickTrack = {
}
// Otherwise, use a custom URL with a redirect
if (Discourse.get('currentUser.external_links_in_new_tab')) {
if (Discourse.User.current('external_links_in_new_tab')) {
var win = window.open(trackingUrl, '_blank');
win.focus();
} else {

View File

@ -72,9 +72,8 @@ Discourse.ScreenTrack = Ember.Object.extend({
return;
}
// We don't log anything unless we're logged in
if (!Discourse.get('currentUser')) {
return;
}
if (!Discourse.User.current()) return;
newTimings = {};
Object.values(this.timings, function(timing) {
if (!_this.totalTimings[timing.postNumber])

View File

@ -12,8 +12,10 @@ Discourse.ApplicationController = Discourse.Controller.extend({
needs: ['modal'],
showLogin: function() {
var _ref;
return (_ref = this.get('controllers.modal')) ? _ref.show(Discourse.LoginView.create()) : void 0;
var modalController = this.get('controllers.modal');
if (modalController) {
modalController.show(Discourse.LoginView.create())
}
},
routeChanged: function(){

View File

@ -94,9 +94,9 @@ Discourse.ComposerController = Discourse.Controller.extend({
opts = opts || {};
_this.close();
if (composer.get('creatingTopic')) {
Discourse.set('currentUser.topic_count', Discourse.get('currentUser.topic_count') + 1);
Discourse.set('currentUser.topic_count', Discourse.User.current('topic_count') + 1);
} else {
Discourse.set('currentUser.reply_count', Discourse.get('currentUser.reply_count') + 1);
Discourse.set('currentUser.reply_count', Discourse.User.current('reply_count') + 1);
}
Discourse.URL.routeTo(opts.post.get('url'));
}, function(error) {
@ -133,7 +133,7 @@ Discourse.ComposerController = Discourse.Controller.extend({
if (this.get('content.editingPost')) return;
// If creating a topic, use topic_count, otherwise post_count
var count = this.get('content.creatingTopic') ? Discourse.get('currentUser.topic_count') : Discourse.get('currentUser.reply_count');
var count = this.get('content.creatingTopic') ? Discourse.User.current('topic_count') : Discourse.User.current('reply_count');
if (count >= Discourse.SiteSettings.educate_until_posts) {
this.set('educationClosed', true);
this.set('educationContents', '');

View File

@ -1,7 +1,7 @@
/**
This controller supports actions when listing categories
@class ListCategoriesController
@class ListCategoriesController
@extends Discourse.ObjectController
@namespace Discourse
@module Discourse
@ -9,34 +9,30 @@
Discourse.ListCategoriesController = Discourse.ObjectController.extend({
needs: ['modal'],
categoriesEven: (function() {
if (this.blank('categories')) {
return Em.A();
}
categoriesEven: function() {
if (this.blank('categories')) return Em.A();
return this.get('categories').filter(function(item, index) {
return (index % 2) === 0;
});
}).property('categories.@each'),
}.property('categories.@each'),
categoriesOdd: (function() {
if (this.blank('categories')) {
return Em.A();
}
categoriesOdd: function() {
if (this.blank('categories')) return Em.A();
return this.get('categories').filter(function(item, index) {
return (index % 2) === 1;
});
}).property('categories.@each'),
}.property('categories.@each'),
editCategory: function(category) {
this.get('controllers.modal').show(Discourse.EditCategoryView.create({ category: category }));
return false;
},
canEdit: (function() {
var u;
u = Discourse.get('currentUser');
canEdit: function() {
var u = Discourse.User.current();
return u && u.admin;
}).property()
}.property()
});

View File

@ -15,7 +15,7 @@ Discourse.ListController = Discourse.Controller.extend({
availableNavItems: function() {
var summary = this.get('filterSummary');
var loggedOn = !!Discourse.get('currentUser');
var loggedOn = !!Discourse.User.current();
return Discourse.SiteSettings.top_menu.split("|").map(function(i) {
return Discourse.NavItem.fromText(i, {
loggedOn: loggedOn,
@ -90,7 +90,7 @@ Discourse.ListController = Discourse.Controller.extend({
canEditCategory: function() {
if( this.present('category') ) {
var u = Discourse.get('currentUser');
var u = Discourse.User.current();
return u && u.admin;
} else {
return false;

View File

@ -62,8 +62,8 @@ Discourse.PreferencesController = Discourse.ObjectController.extend({
return model.save().then(function() {
// model was saved
preferencesController.set('saving', false);
if (Discourse.currentUser.id === model.get('id')) {
Discourse.currentUser.set('name', model.get('name'));
if (Discourse.User.current('id') === model.get('id')) {
Discourse.User.current().set('name', model.get('name'));
}
preferencesController.set('content.bio_cooked',

View File

@ -31,7 +31,8 @@ Discourse.QuoteButtonController = Discourse.Controller.extend({
**/
selectText: function(postId) {
// anonymous users cannot "quote-reply"
if (!Discourse.get('currentUser')) return;
if (!Discourse.User.current()) return;
// don't display the "quote-reply" button if we can't create a post
if (!this.get('controllers.topic.content.can_create_post')) return;

View File

@ -415,7 +415,7 @@ Discourse.TopicController = Discourse.ObjectController.extend(Discourse.Selected
},
toggleBookmark: function(post) {
if (!Discourse.get('currentUser')) {
if (!Discourse.User.current()) {
alert(Em.String.i18n("bookmarks.not_bookmarked"));
return;
}
@ -480,7 +480,7 @@ Discourse.TopicController = Discourse.ObjectController.extend(Discourse.Selected
deletePost: function(post) {
// Moderators can delete posts. Regular users can only create a deleted at message.
if (Discourse.get('currentUser.staff')) {
if (Discourse.User.current('staff')) {
post.set('deleted_at', new Date());
} else {
post.set('cooked', Discourse.Markdown.cook(Em.String.i18n("post.deleted_by_author")));

View File

@ -8,13 +8,13 @@
**/
Discourse.UserController = Discourse.ObjectController.extend({
viewingSelf: (function() {
return this.get('content.username') === Discourse.get('currentUser.username');
}).property('content.username', 'Discourse.currentUser.username'),
viewingSelf: function() {
return this.get('content.username') === Discourse.User.current('username');
}.property('content.username'),
canSeePrivateMessages: (function() {
return this.get('viewingSelf') || Discourse.get('currentUser.staff');
}).property('viewingSelf', 'Discourse.currentUser')
canSeePrivateMessages: function() {
return this.get('viewingSelf') || Discourse.User.current('staff');
}.property('viewingSelf')
});

View File

@ -348,20 +348,3 @@ Handlebars.registerHelper('date', function(property, options) {
return new Handlebars.SafeString("<span class='date' title='" + fullReadable + "'>" + displayDate + "</span>");
});
/**
A personalized name for display
@method personalizedName
@for Handlebars
**/
Handlebars.registerHelper('personalizedName', function(property, options) {
var name, username;
name = Ember.Handlebars.get(this, property, options);
if (options.hash.usernamePath) {
username = Ember.Handlebars.get(this, options.hash.usernamePath, options);
}
if (username !== Discourse.get('currentUser.username')) {
return name;
}
return Em.String.i18n('you');
});

View File

@ -52,7 +52,7 @@ Discourse.ActionSummary = Discourse.Model.extend({
// Add ourselves to the users who liked it if present
if (this.present('users')) {
this.users.pushObject(Discourse.get('currentUser'));
this.users.pushObject(Discourse.User.current());
}
// Create our post action

View File

@ -69,7 +69,7 @@ Discourse.Composer = Discourse.Model.extend({
}.property('editingPost', 'creatingTopic', 'post.post_number'),
showAdminOptions: function() {
if (this.get('creatingTopic') && Discourse.get('currentUser.staff')) return true;
if (this.get('creatingTopic') && Discourse.User.current('staff')) return true;
return false;
}.property('editTitle'),
@ -340,7 +340,7 @@ Discourse.Composer = Discourse.Model.extend({
createPost: function(opts) {
var post = this.get('post'),
topic = this.get('topic'),
currentUser = Discourse.get('currentUser'),
currentUser = Discourse.User.current(),
addedToStream = false;
// The post number we'll probably get from the server
@ -384,7 +384,7 @@ Discourse.Composer = Discourse.Model.extend({
// Update last post
topic.set('last_posted_at', new Date());
topic.set('highest_post_number', createdPost.get('post_number'));
topic.set('last_poster', Discourse.get('currentUser'));
topic.set('last_poster', Discourse.User.current());
topic.set('filtered_posts_count', topic.get('filtered_posts_count') + 1);
// Set the topic view for the new post
@ -479,7 +479,7 @@ Discourse.Composer = Discourse.Model.extend({
flashDraftStatusForNewUser: function() {
var $draftStatus = $('#draft-status');
if (Discourse.get('currentUser.trust_level') === 0) {
if (Discourse.User.current('trust_level') === 0) {
$draftStatus.toggleClass('flash', true);
setTimeout(function() { $draftStatus.removeClass('flash'); }, 250);
}

View File

@ -9,12 +9,10 @@
Discourse.Post = Discourse.Model.extend({
shareUrl: function() {
var user = Discourse.get('currentUser');
if (this.get('postnumber') === 1){
return this.get('topic.url');
} else {
return this.get('url') + (user ? '?u=' + user.get('username_lower') : '');
}
if (this.get('postnumber') === 1) return this.get('topic.url');
var user = Discourse.User.current();
return this.get('url') + (user ? '?u=' + user.get('username_lower') : '');
}.property('url'),
new_user: function() {

View File

@ -38,7 +38,7 @@ Discourse.Topic = Discourse.Model.extend({
}.property('categoryName'),
shareUrl: function(){
var user = Discourse.get('currentUser');
var user = Discourse.User.current();
return this.get('url') + (user ? '?u=' + user.get('username_lower') : '');
}.property('url'),
@ -310,7 +310,7 @@ Discourse.Topic = Discourse.Model.extend({
if (typeof this.get('notifications_reason_id') === 'number') {
locale_string += "_" + this.get('notifications_reason_id');
}
return Em.String.i18n(locale_string, { username: Discourse.currentUser.username.toLowerCase() });
return Em.String.i18n(locale_string, { username: Discourse.User.current('username_lower') });
}.property('notification_level', 'notifications_reason_id'),
updateNotifications: function(v) {

View File

@ -275,6 +275,45 @@ Discourse.User = Discourse.Model.extend({
});
Discourse.User.reopenClass({
/**
Returns the currently logged in user
@method current
@param {String} optional property to return from the user if the user exists
@returns {Discourse.User} the logged in user
**/
current: function(property) {
if (!this.currentUser) {
var userJson = PreloadStore.get('currentUser');
if (userJson) {
this.currentUser = Discourse.User.create(userJson);
}
}
// If we found the current user
if (this.currentUser && property) {
return this.currentUser.get(property);
}
return this.currentUser;
},
/**
Logs out the currently logged in user
@method logout
@returns {Promise} resolved when the logout finishes
**/
logout: function() {
var discourseUserClass = this;
return Discourse.ajax("/session/" + Discourse.User.current('username'), {
type: 'DELETE'
}).then(function () {
discourseUserClass.currentUser = null;
});
},
/**
Checks if given username is valid for this email address

View File

@ -14,7 +14,7 @@ Discourse.UserAction = Discourse.Model.extend({
var actions = [ua.LIKE, ua.WAS_LIKED, ua.STAR, ua.EDIT, ua.BOOKMARK, ua.GOT_PRIVATE_MESSAGE, ua.NEW_PRIVATE_MESSAGE];
var icon = "";
var sentence = "";
var sameUser = (this.get('username') === Discourse.get('currentUser.username'));
var sameUser = (this.get('username') === Discourse.User.current('username'));
if (action === null || actions.indexOf(action) >= 0) {
if (this.get('isPM')) {
@ -60,7 +60,7 @@ Discourse.UserAction = Discourse.Model.extend({
sentence = Em.String.i18n('user_action.you_mentioned_user', { user: this.get('target_name'),
user1Url: this.get('userUrl'), user2Url: this.get('targetUserUrl') });
} else {
if (this.get('target_username') === Discourse.get('currentUser.username')) {
if (this.get('target_username') === Discourse.User.current('username')) {
sentence = Em.String.i18n('user_action.user_mentioned_you', { user: this.get('name'),
user1Url: this.get('userUrl'), user2Url: this.get('targetUserUrl') });
} else {

View File

@ -27,7 +27,6 @@ Discourse.UserStream = Discourse.Model.extend({
if (result && result.user_actions && result.user_actions.each) {
var copy = Em.A();
result.user_actions.each(function(i) {
console.log(i);
return copy.pushObject(Discourse.UserAction.create(i));
});
copy = Discourse.UserAction.collapseStream(copy);

View File

@ -8,12 +8,6 @@
**/
Discourse.ApplicationRoute = Discourse.Route.extend({
setupController: function(controller) {
//Discourse.set('site', Discourse.Site.instance());
var currentUser = PreloadStore.get('currentUser');
if (currentUser) {
Discourse.set('currentUser', Discourse.User.create(currentUser));
}
// make sure we delete preloaded data
PreloadStore.remove('currentUser');
Discourse.set('currentUser', Discourse.User.current());
}
});

View File

@ -150,7 +150,7 @@ Discourse.PostMenuView = Discourse.View.extend({
// Bookmark button
renderBookmark: function(post, buffer) {
if (!Discourse.get('currentUser')) return;
if (!Discourse.User.current()) return;
var icon = 'bookmark';
if (!this.get('post.bookmarked')) {

View File

@ -72,7 +72,7 @@ Discourse.QuoteButtonView = Discourse.View.extend({
selectText: function(target, controller) {
var $target = $(target);
// quoting as been disabled by the user
if (!Discourse.get('currentUser.enable_quoting')) return;
if (!Discourse.User.current('enable_quoting')) return;
// retrieve the post id from the DOM
var postId = $target.closest('.boxed').data('post-id');
// select the text

View File

@ -19,7 +19,7 @@ Discourse.TopicFooterButtonsView = Ember.ContainerView.extend({
createButtons: function() {
var topic;
topic = this.get('topic');
if (Discourse.get('currentUser')) {
if (Discourse.User.current()) {
if (!topic.get('isPrivateMessage')) {
// We hide some controls from private messages
@ -83,7 +83,7 @@ Discourse.TopicFooterButtonsView = Ember.ContainerView.extend({
// Hide the button if it becomes unpinned
unpinned: function() {
// When not logged in don't show the button
if (!Discourse.get('currentUser')) return 'hidden'
if (!Discourse.User.current()) return 'hidden'
return this.get('controller.pinned') ? null : 'hidden';
}.property('controller.pinned'),

View File

@ -12,7 +12,7 @@ Discourse.UserSelector = Discourse.TextField.extend({
dataSource: function(term) {
var exclude = selected;
if (_this.get('excludeCurrentUser')){
exclude = exclude.concat([Discourse.get('currentUser.username')]);
exclude = exclude.concat([Discourse.User.current('username')]);
}
return Discourse.UserSearch.search({
term: term,