diff --git a/public/js/controllers/groupsCtrl.js b/public/js/controllers/groupsCtrl.js index dddb4ac628..bd372d4c7c 100644 --- a/public/js/controllers/groupsCtrl.js +++ b/public/js/controllers/groupsCtrl.js @@ -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); }); } } diff --git a/src/controllers/groups.js b/src/controllers/groups.js index 39e62b330e..cac0aec29f 100644 --- a/src/controllers/groups.js +++ b/src/controllers/groups.js @@ -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) }); }