2016-07-12 03:42:54 +08:00
|
|
|
import { Tracker } from 'meteor/tracker';
|
|
|
|
|
2016-07-07 20:50:32 +08:00
|
|
|
import Storage from '/imports/ui/services/storage/session';
|
2016-07-08 00:51:55 +08:00
|
|
|
import Auth from '/imports/ui/services/auth';
|
2017-07-12 20:42:16 +08:00
|
|
|
import Chats from '/imports/api/2.0/chat';
|
2016-07-05 02:53:47 +08:00
|
|
|
|
2016-08-17 23:48:03 +08:00
|
|
|
const CHAT_CONFIG = Meteor.settings.public.chat;
|
|
|
|
const STORAGE_KEY = CHAT_CONFIG.storage_key;
|
2016-07-05 02:53:47 +08:00
|
|
|
|
2016-07-12 00:28:55 +08:00
|
|
|
class UnreadMessagesTracker {
|
|
|
|
constructor() {
|
2017-06-03 03:25:02 +08:00
|
|
|
this._tracker = new Tracker.Dependency();
|
2016-07-12 03:42:54 +08:00
|
|
|
this._unreadChats = Storage.getItem('UNREAD_CHATS') || {};
|
2016-07-12 00:28:55 +08:00
|
|
|
}
|
2016-07-05 02:53:47 +08:00
|
|
|
|
2016-07-12 00:28:55 +08:00
|
|
|
get(chatID) {
|
2016-07-12 03:42:54 +08:00
|
|
|
this._tracker.depend();
|
2016-07-12 00:28:55 +08:00
|
|
|
return this._unreadChats[chatID] || 0;
|
2016-07-05 02:53:47 +08:00
|
|
|
}
|
|
|
|
|
2016-07-12 00:28:55 +08:00
|
|
|
update(chatID, timestamp = 0) {
|
2017-06-03 03:25:02 +08:00
|
|
|
const currentValue = this.get(chatID);
|
2016-07-12 00:28:55 +08:00
|
|
|
if (currentValue < timestamp) {
|
|
|
|
this._unreadChats[chatID] = timestamp;
|
2016-07-12 03:42:54 +08:00
|
|
|
this._tracker.changed();
|
2016-07-12 00:28:55 +08:00
|
|
|
Storage.setItem(STORAGE_KEY, this._unreadChats);
|
|
|
|
}
|
2016-07-05 02:53:47 +08:00
|
|
|
|
2016-07-12 00:28:55 +08:00
|
|
|
return this._unreadChats[chatID];
|
2016-07-11 20:34:58 +08:00
|
|
|
}
|
|
|
|
|
2016-07-12 00:28:55 +08:00
|
|
|
count(chatID) {
|
2017-06-03 03:25:02 +08:00
|
|
|
const filter = {
|
2017-07-12 21:54:54 +08:00
|
|
|
'message.fromTime': {
|
2016-07-12 00:28:55 +08:00
|
|
|
$gt: this.get(chatID),
|
|
|
|
},
|
2017-07-12 21:54:54 +08:00
|
|
|
'message.fromUserId': { $ne: Auth.userID },
|
2016-07-12 00:28:55 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// Minimongo does not support $eq. See https://github.com/meteor/meteor/issues/4142
|
2017-07-12 21:54:54 +08:00
|
|
|
if (chatID === 'public_chat_userid') {
|
|
|
|
filter['message.toUserId'] = { $not: { $ne: chatID } };
|
2016-07-12 00:28:55 +08:00
|
|
|
} else {
|
2017-07-12 21:54:54 +08:00
|
|
|
filter['message.toUserId'] = { $not: { $ne: Auth.userID } };
|
|
|
|
filter['message.fromUserId'].$not = { $ne: chatID };
|
2016-07-12 00:28:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return Chats.find(filter).count();
|
|
|
|
}
|
2017-06-03 03:25:02 +08:00
|
|
|
}
|
2016-07-05 02:53:47 +08:00
|
|
|
|
2017-06-03 03:25:02 +08:00
|
|
|
const UnreadTrackerSingleton = new UnreadMessagesTracker();
|
2016-07-12 00:28:55 +08:00
|
|
|
export default UnreadTrackerSingleton;
|