update chat if necessary after new message posted or deleted

This commit is contained in:
Matteo Pagliazzi 2013-11-08 17:03:10 +01:00
parent a5999a7be3
commit a78297f129
2 changed files with 22 additions and 6 deletions

View file

@ -86,8 +86,13 @@ habitrpg.controller("GroupsCtrl", ['$scope', '$rootScope', 'Groups', '$http', 'A
$scope.postChat = function(group, message){
if (_.isEmpty(message) || $scope._sending) return;
$scope._sending = true;
Groups.Group.postChat({gid: group._id, message:message}, undefined, function(data){
group.chat = data.chat;
var previousMsg = (group.chat && group.chat[0]) ? group.chat[0].id : false;
Groups.Group.postChat({gid: group._id, message:message, previousMsg: previousMsg}, undefined, function(data){
if(data.chat){
group.chat = data.chat;
}else if(data.message){
group.chat.unshift(data.message);
}
$scope._chatMessage = '';
$scope._sending = false;
}, function(err){
@ -97,9 +102,12 @@ habitrpg.controller("GroupsCtrl", ['$scope', '$rootScope', 'Groups', '$http', 'A
$scope.deleteChatMessage = function(group, message){
if(message.uuid === User.user.id || (User.user.backer && User.user.backer.admin)){
Groups.Group.deleteChatMessage({gid: group._id, messageId: message.id}, undefined, function(){
var i = _.indexOf(group.chat, message);
if(i !== -1) group.chat.splice(i, 1);
var previousMsg = (group.chat && group.chat[0]) ? group.chat[0].id : false;
Groups.Group.deleteChatMessage({gid:group._id, messageId:message.id, previousMsg:previousMsg}, undefined, function(data){
if(data.chat) group.chat = data.chat;
var i = _.findIndex(group.chat, {id: message.id});
if(i !== -1) group.chat.splice(i, 1);
});
}
}

View file

@ -206,6 +206,9 @@ api.postChat = function(req, res, next) {
timestamp: +(new Date)
};
var lastClientMsg = req.query.previousMsg;
var chatUpdated = (lastClientMsg && group.chat && group.chat[0] && group.chat[0].id !== lastClientMsg) ? true : false;
group.chat.unshift(message);
group.chat.splice(200);
@ -217,6 +220,8 @@ api.postChat = function(req, res, next) {
group.save(function(err, saved){
if (err) return res.json(500, {err:err});
if(!chatUpdated) return res.json({message: saved.chat[0]});
res.json({chat: saved.chat});
});
}
@ -231,9 +236,12 @@ api.deleteChatMessage = function(req, res){
if(user._id !== message.uuid && !(user.backer && user.backer.admin))
return res.json(401, {err: "Not authorized to delete this message!"})
var lastClientMsg = req.query.previousMsg;
var chatUpdated = (lastClientMsg && group.chat && group.chat[0] && group.chat[0].id !== lastClientMsg) ? true : false;
Group.update({_id:group._id}, {$pull:{chat:{id: req.params.messageId}}}, function(err){
if(err) return res.json(500, {err: err});
res.send(204);
return chatUpdated ? res.json({chat: group.chat}) : res.send(204)
});
}