diff --git a/src/notifications.js b/src/notifications.js index c614dd0272..fde6a7209c 100644 --- a/src/notifications.js +++ b/src/notifications.js @@ -19,18 +19,37 @@ var async = require('async'), Notifications.get = function(nid, uid, callback) { db.exists('notifications:' + nid, function(err, exists) { - if(!exists) { + if (err) { + winston.error('[notifications.get] Could not retrieve nid ' + nid + ': ' + err.message); return callback(null); } - db.sortedSetRank('uid:' + uid + ':notifications:read', nid, function(err, rank) { + if (exists) { + db.sortedSetRank('uid:' + uid + ':notifications:read', nid, function(err, rank) { - db.getObjectFields('notifications:' + nid, ['nid', 'text', 'score', 'path', 'datetime', 'uniqueId'], function(err, notification) { + db.getObjectFields('notifications:' + nid, ['nid', 'text', 'score', 'path', 'datetime', 'uniqueId'], function(err, notification) { - notification.read = rank !== null ? true:false; - callback(notification); + notification.read = rank !== null ? true:false; + callback(notification); + }); }); - }); + } else { + // Remove from the user's boxes + if (process.env.NODE_ENV === 'development') { + winston.info('[notifications.get] nid ' + nid + ' not found. Removing.'); + } + + async.parallel([ + function(next) { + db.sortedSetRemove('uid:' + uid + ':notifications:unread', nid, next); + }, + function(next) { + db.sortedSetRemove('uid:' + uid + ':notifications:read', nid, next); + } + ], function(err) { + callback(null); + }); + } }); }; diff --git a/src/user.js b/src/user.js index 1b8a17069a..d0a22520df 100644 --- a/src/user.js +++ b/src/user.js @@ -999,12 +999,8 @@ var bcrypt = require('bcryptjs'), async.map(nids, function(nid, next) { notifications.get(nid, uid, function(notif_data) { - if(!notif_data) { - db.sortedSetRemove(set, nid); - } else { - if(typeof iterator === 'function') { - iterator(notif_data); - } + if(typeof iterator === 'function') { + iterator(notif_data); } next(null, notif_data); @@ -1018,7 +1014,9 @@ var bcrypt = require('bcryptjs'), async.parallel({ unread: function(next) { getNotifications('uid:' + uid + ':notifications:unread', 0, 9, function(notif_data) { - notif_data.readClass = !notif_data.read ? 'label-warning' : ''; + if (notif_data) { + notif_data.readClass = !notif_data.read ? 'label-warning' : ''; + } }, next); }, read: function(next) { @@ -1029,6 +1027,14 @@ var bcrypt = require('bcryptjs'), return calback(err); } + // Remove empties + notifications.read = notifications.read.filter(function(notifObj) { + return notifObj; + }); + notifications.unread = notifications.unread.filter(function(notifObj) { + return notifObj; + }); + // Limit the number of notifications to `maxNotifs`, prioritising unread notifications if (notifications.read.length + notifications.unread.length > maxNotifs) { notifications.read.length = maxNotifs - notifications.unread.length;