Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NEW] Message read receipts #9717

Merged
merged 9 commits into from
Feb 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions client/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import '/imports/startup/client';
4 changes: 4 additions & 0 deletions imports/message-read-receipt/client/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import './main';
import './message';
import './readReceipts';
import './room';
7 changes: 7 additions & 0 deletions imports/message-read-receipt/client/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Template.main.helpers({
readReceiptsEnabled() {
if (RocketChat.settings.get('Message_Read_Receipt_Store_Users')) {
return 'read-receipts-enabled';
}
}
});
13 changes: 13 additions & 0 deletions imports/message-read-receipt/client/message.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Template } from 'meteor/templating';

Template.message.helpers({
readReceipt() {
if (!RocketChat.settings.get('Message_Read_Receipt_Enabled')) {
return;
}

return {
readByEveryone: (!this.unread && 'read') || 'color-component-color'
};
}
});
51 changes: 51 additions & 0 deletions imports/message-read-receipt/client/readReceipts.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
.read-receipt {
position: absolute;
top: 2px;
right: 0.5rem;
}

.read-receipt .rc-icon {
height: 0.8em;
width: 0.8em;
}

.message:hover .read-receipt, .message.active .read-receipt {
display: none;
}

.read-receipts-enabled .read-receipt {
cursor: pointer;
}

.read-receipt.read {
color: #1d74f5;
color: var(--rc-color-button-primary);
font-style: normal;
}

.message.temp .read-receipt {
opacity: 0.4;
}

.read-receipts__user {
display: flex;
padding: 8px 8px;
align-items: center;
}

.read-receipts__name {
flex: 1 1 auto;
margin: 0 10px;
font-size: 16px;
}

.read-receipts__time {
font-size: 80%;
}

.read-receipts__user > .avatar {
width: 36px;
width: var(--sidebar-account-thumb-size);
height: 36px;
height: var(--sidebar-account-thumb-size);
}
16 changes: 16 additions & 0 deletions imports/message-read-receipt/client/readReceipts.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<template name="readReceipts">
{{#if isLoading}}
{{> loading class="loading-animation--primary"}}
{{else}}
<p>{{_ "Read_by"}}:</p>
<ul class="read-receipts">
{{#each receipts}}
<li class="read-receipts__user background-transparent-dark-hover">
{{> avatar username=user.username}}
<div class="read-receipts__name color-primary-font-color">{{displayName}}</div>
<span class="read-receipts__time color-info-font-color" title="{{dateTime}}">{{time}}</span>
</li>
{{/each}}
</ul>
{{/if}}
</template>
35 changes: 35 additions & 0 deletions imports/message-read-receipt/client/readReceipts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ReactiveVar } from 'meteor/reactive-var';
import moment from 'moment';

import './readReceipts.css';
import './readReceipts.html';

Template.readReceipts.helpers({
receipts() {
return Template.instance().readReceipts.get();
},
displayName() {
return (RocketChat.settings.get('UI_Use_Real_Name') && this.user.name) || this.user.username;
},
time() {
return moment(this.ts).format('L LTS');
},
isLoading() {
return Template.instance().loading.get();
}
});

Template.readReceipts.onCreated(function readReceiptsOnCreated() {
this.loading = new ReactiveVar(false);
this.readReceipts = new ReactiveVar([]);
});

Template.readReceipts.onRendered(function readReceiptsOnRendered() {
this.loading.set(true);
Meteor.call('getReadReceipts', { messageId: this.data.messageId }, (error, result) => {
if (!error) {
this.readReceipts.set(result);
}
this.loading.set(false);
});
});
24 changes: 24 additions & 0 deletions imports/message-read-receipt/client/room.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
RocketChat.MessageAction.addButton({
id: 'receipt-detail',
icon: 'info-circled',
label: 'Message_info',
context: ['starred', 'message', 'message-mobile'],
action() {
const message = this._arguments[1];
modal.open({
title: t('Message_info'),
content: 'readReceipts',
data: {
messageId: message._id
},
showConfirmButton: true,
showCancelButton: false,
confirmButtonText: t('Close')
});
},
condition() {
return RocketChat.settings.get('Message_Read_Receipt_Store_Users');
},
order: 1,
group: 'menu'
});
20 changes: 20 additions & 0 deletions imports/message-read-receipt/server/api/methods/getReadReceipts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Meteor } from 'meteor/meteor';

import { ReadReceipt } from '../../lib/ReadReceipt';

Meteor.methods({
getReadReceipts({ messageId }) {
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getReadReceipts' });
}

const message = RocketChat.models.Messages.findOneById(messageId);

const room = Meteor.call('canAccessRoom', message.rid, Meteor.userId());
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'getReadReceipts' });
}

return ReadReceipt.getReceipts(message);
}
});
5 changes: 5 additions & 0 deletions imports/message-read-receipt/server/dbIndexes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
RocketChat.models.Messages.tryEnsureIndex({
unread: 1
}, {
sparse: true
});
10 changes: 10 additions & 0 deletions imports/message-read-receipt/server/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ReadReceipt } from './lib/ReadReceipt';

RocketChat.callbacks.add('afterSaveMessage', (message, room) => {

// set subscription as read right after message was sent
RocketChat.models.Subscriptions.setAsReadByRoomIdAndUserId(room._id, message.u._id);

// mark message as read as well
ReadReceipt.markMessageAsReadBySender(message, room._id, message.u._id);
});
5 changes: 5 additions & 0 deletions imports/message-read-receipt/server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import './dbIndexes';
import './hooks';
import './settings';

import './api/methods/getReadReceipts';
86 changes: 86 additions & 0 deletions imports/message-read-receipt/server/lib/ReadReceipt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
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(() => { 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
const firstSubscription = RocketChat.models.Subscriptions.getMinimumLastSeenByRoomId(roomId);
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;
}

if (userLastSeen) {
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
};
});

if (receipts.length === 0) {
return;
}

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 }})
}));
}
};
19 changes: 19 additions & 0 deletions imports/message-read-receipt/server/models/ReadReceipts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class ModelReadReceipts extends RocketChat.models._Base {
constructor() {
super(...arguments);

this.tryEnsureIndex({
roomId: 1,
userId: 1,
messageId: 1
}, {
unique: 1
});
}

findByMessageId(messageId) {
return this.find({ messageId });
}
}

export default new ModelReadReceipts('message_read_receipt');
12 changes: 12 additions & 0 deletions imports/message-read-receipt/server/settings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
RocketChat.settings.add('Message_Read_Receipt_Enabled', false, {
group: 'Message',
type: 'boolean',
public: true
});

RocketChat.settings.add('Message_Read_Receipt_Store_Users', false, {
group: 'Message',
type: 'boolean',
public: true,
enableQuery: { _id: 'Message_Read_Receipt_Enabled', value: true }
});
1 change: 1 addition & 0 deletions imports/startup/client/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import '../../message-read-receipt/client';
1 change: 1 addition & 0 deletions imports/startup/server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import '../../message-read-receipt/server';
5 changes: 5 additions & 0 deletions packages/rocketchat-i18n/i18n/en.i18n.json
Original file line number Diff line number Diff line change
Expand Up @@ -1252,11 +1252,15 @@
"Message_HideType_ru": "Hide \"User Removed\" messages",
"Message_HideType_uj": "Hide \"User Join\" messages",
"Message_HideType_ul": "Hide \"User Leave\" messages",
"Message_info": "Message info",
"Message_KeepHistory": "Keep Per Message Editing History",
"Message_MaxAll": "Maximum Channel Size for ALL Message",
"Message_MaxAllowedSize": "Maximum Allowed Characters Per Message",
"Message_pinning": "Message pinning",
"Message_QuoteChainLimit": "Maximum Number of Chained Quotes",
"Message_Read_Receipt_Enabled": "Show Read Receipts",
"Message_Read_Receipt_Store_Users": "Detailed Read Receipts",
"Message_Read_Receipt_Store_Users_Description": "Shows each user's read receipts",
"Message_removed": "Message removed",
"Message_sent_by_email": "Message sent by Email",
"Message_SetNameToAliasEnabled": "Set a User Name to Alias in Message",
Expand Down Expand Up @@ -1522,6 +1526,7 @@
"React_when_read_only_changed_successfully": "Allow reacting when read only changed successfully",
"Reacted_with": "Reacted with",
"Reactions": "Reactions",
"Read_by": "Read by",
"Read_only": "Read Only",
"Read_only_changed_successfully": "Read only changed successfully",
"Read_only_channel": "Read Only Channel",
Expand Down
3 changes: 3 additions & 0 deletions packages/rocketchat-lib/client/methods/sendMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ Meteor.methods({
message.u.name = user.name;
}
message.temp = true;
if (RocketChat.settings.get('Message_Read_Receipt_Enabled')) {
message.unread = true;
}
message = RocketChat.callbacks.run('beforeSaveMessage', message);
RocketChat.promises.run('onClientMessageReceived', message).then(function(message) {
ChatMessage.insert(message);
Expand Down
5 changes: 5 additions & 0 deletions packages/rocketchat-lib/server/functions/sendMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) {
});
}
}

if (RocketChat.settings.get('Message_Read_Receipt_Enabled')) {
message.unread = true;
}

message = RocketChat.callbacks.run('beforeSaveMessage', message);
if (message) {
// Avoid saving sandstormSessionId to the database
Expand Down
Loading