-
Notifications
You must be signed in to change notification settings - Fork 10.7k
/
ReadReceipt.js
82 lines (68 loc) · 2.67 KB
/
ReadReceipt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { Random } from 'meteor/random';
import ModelReadReceipts from '../models/ReadReceipts';
const rawReadReceipts = ModelReadReceipts.model.rawCollection();
// debounced function by roomId, so multiple calls within 2 seconds to same roomId runs only once
const list = {};
const debounceByRoomId = function(fn) {
return function(roomId, ...args) {
clearTimeout(list[roomId]);
list[roomId] = setTimeout(() => { console.log('vai rodar'); fn.call(this, roomId, ...args); }, 2000);
};
};
const updateMessages = debounceByRoomId(Meteor.bindEnvironment((roomId) => {
// @TODO maybe store firstSubscription in room object so we don't need to call the above update method
// if firstSubscription on room didn't change
const firstSubscription = RocketChat.models.Subscriptions.getMinimumLastSeenByRoomId(roomId);
// console.log('firstSubscription ->', firstSubscription);
RocketChat.models.Messages.setAsRead(roomId, firstSubscription.ls);
}));
export const ReadReceipt = {
markMessagesAsRead(roomId, userId, userLastSeen) {
if (!RocketChat.settings.get('Message_Read_Receipt_Enabled')) {
return;
}
const room = RocketChat.models.Rooms.findOneById(roomId, { fields: { lm: 1 } });
// if users last seen is greadebounceByRoomIdter than room's last message, it means the user already have this room marked as read
if (userLastSeen > room.lm) {
return;
}
this.storeReadReceipts(RocketChat.models.Messages.findUnreadMessagesByRoomAndDate(roomId, userLastSeen), roomId, userId);
updateMessages(roomId);
},
markMessageAsReadBySender(message, roomId, userId) {
if (!RocketChat.settings.get('Message_Read_Receipt_Enabled')) {
return;
}
// this will usually happens if the message sender is the only one on the room
const firstSubscription = RocketChat.models.Subscriptions.getMinimumLastSeenByRoomId(roomId);
if (message.unread && message.ts < firstSubscription.ls) {
RocketChat.models.Messages.setAsReadById(message._id, firstSubscription.ls);
}
this.storeReadReceipts([{ _id: message._id }], roomId, userId);
},
storeReadReceipts(messages, roomId, userId) {
if (RocketChat.settings.get('Message_Read_Receipt_Store_Users')) {
const ts = new Date();
const receipts = messages.map(message => {
return {
_id: Random.id(),
roomId,
userId,
messageId: message._id,
ts
};
});
try {
rawReadReceipts.insertMany(receipts);
} catch (e) {
console.error('Error inserting read receipts per user');
}
}
},
getReceipts(message) {
return ModelReadReceipts.findByMessageId(message._id).map(receipt => ({
...receipt,
user: RocketChat.models.Users.findOneById(receipt.userId, { fields: { username: 1, name: 1 }})
}));
}
};