Skip to content

Commit

Permalink
Merge pull request #9048 from RocketChat/livechat-do-not-use-users-co…
Browse files Browse the repository at this point in the history
…llection

[BREAK] Decouple livechat visitors from regular users
  • Loading branch information
sampaiodiego authored Dec 27, 2017
2 parents c942b0c + 6c01dc8 commit ec8679c
Show file tree
Hide file tree
Showing 152 changed files with 1,628 additions and 526 deletions.
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ packages/meteor-timesync/
packages/rocketchat-emoji-emojione/generateEmojiIndex.js
packages/rocketchat-favico/favico.js
packages/rocketchat-katex/client/katex/katex.min.js
packages/rocketchat-livechat/app/node_modules
packages/rocketchat-livechat/.app/node_modules
packages/rocketchat-livechat/assets/rocketchat-livechat.min.js
packages/rocketchat-livechat/assets/rocket-livechat.js
packages/rocketchat-migrations/
Expand Down
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ cache:
- "$HOME/build/RocketChat/Rocket.Chat/node_modules"
- "$HOME/build/RocketChat/Rocket.Chat/.meteor/local"
- "$HOME/build/RocketChat/Rocket.Chat/packages/rocketchat-livechat/.npm"
- "$HOME/build/RocketChat/Rocket.Chat/packages/rocketchat-livechat/app/node_modules"
- "$HOME/build/RocketChat/Rocket.Chat/packages/rocketchat-livechat/app/.meteor/local"
- "$HOME/build/RocketChat/Rocket.Chat/packages/rocketchat-livechat/.app/node_modules"
- "$HOME/build/RocketChat/Rocket.Chat/packages/rocketchat-livechat/.app/.meteor/local"
before_install:
- if [ ! -e "$HOME/.meteor/meteor" ]; then curl https://install.meteor.com | sed s/--progress-bar/-sL/g | /bin/sh; fi
# Start X Virtual Frame Buffer for headless testing with real browsers
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ RocketChat.authz.roomAccessValidators = [
}
];

RocketChat.authz.canAccessRoom = function(room, user) {
RocketChat.authz.canAccessRoom = function(room, user, extraData) {
return RocketChat.authz.roomAccessValidators.some((validator) => {
return validator.call(this, room, user);
return validator.call(this, room, user, extraData);
});
};

Expand Down
5 changes: 4 additions & 1 deletion packages/rocketchat-i18n/i18n/en.i18n.json
Original file line number Diff line number Diff line change
Expand Up @@ -1061,6 +1061,8 @@
"LDAP_Username_Field": "Username Field",
"LDAP_Username_Field_Description": "Which field will be used as *username* for new users. Leave empty to use the username informed on login page.<br/>You can use template tags too, like `#{givenName}.#{sn}`.<br/>Default value is `sAMAccountName`.",
"Execute_Synchronization_Now": "Execute Synchronization Now",
"Lead_capture_email_regex": "Lead capture email regex",
"Lead_capture_phone_regex": "Lead capture phone regex",
"Least_Amount": "Least Amount",
"Leave_Group_Warning": "Are you sure you want to leave the group \"%s\"?",
"Leave_Livechat_Warning": "Are you sure you want to leave the livechat with \"%s\"?",
Expand Down Expand Up @@ -1587,6 +1589,7 @@
"Send_invitation_email_info": "You can send multiple email invitations at once.",
"Send_invitation_email_success": "You have successfully sent an invitation email to the following addresses:",
"Send_request_on_chat_close": "Send Request on Chat Close",
"Send_request_on_lead_capture": "Send request on lead capture",
"Send_request_on_offline_messages": "Send Request on Offline Messages",
"Send_Test": "Send Test",
"Send_welcome_email": "Send welcome email",
Expand Down Expand Up @@ -2058,4 +2061,4 @@
"your_message_optional": "your message (optional)",
"Your_password_is_wrong": "Your password is wrong!",
"Your_push_was_sent_to_s_devices": "Your push was sent to %s devices"
}
}
1 change: 1 addition & 0 deletions packages/rocketchat-lib/package.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ Package.onUse(function(api) {
api.addFiles('server/functions/deleteUser.js', 'server');
api.addFiles('server/functions/getFullUserData.js', 'server');
api.addFiles('server/functions/getRoomByNameOrIdWithOptionToJoin.js', 'server');
api.addFiles('server/functions/loadMessageHistory.js', 'server');
api.addFiles('server/functions/removeUserFromRoom.js', 'server');
api.addFiles('server/functions/saveUser.js', 'server');
api.addFiles('server/functions/saveCustomFields.js', 'server');
Expand Down
23 changes: 16 additions & 7 deletions packages/rocketchat-lib/server/functions/Notifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ RocketChat.Notifications = new class {
this.streamUser.allowWrite('logged');
this.streamAll.allowRead('all');
this.streamLogged.allowRead('logged');
this.streamRoom.allowRead(function(eventName) {
if (this.userId == null) {
return false;
}
this.streamRoom.allowRead(function(eventName, extraData) {
const [roomId] = eventName.split('/');
const user = Meteor.users.findOne(this.userId, {
fields: {
Expand All @@ -40,9 +37,12 @@ RocketChat.Notifications = new class {
console.warn(`Invalid streamRoom eventName: "${ eventName }"`);
return false;
}
if (room.t === 'l' && room.v._id === user._id) {
if (room.t === 'l' && extraData && extraData.token && room.v.token === extraData.token) {
return true;
}
if (this.userId == null) {
return false;
}
return room.usernames.indexOf(user.username) > -1;
});
this.streamRoomUsers.allowRead('none');
Expand Down Expand Up @@ -117,12 +117,21 @@ RocketChat.Notifications = new class {
}
};

RocketChat.Notifications.streamRoom.allowWrite(function(eventName, username) {
const [, e] = eventName.split('/');
RocketChat.Notifications.streamRoom.allowWrite(function(eventName, username, typing, extraData) {
const [roomId, e] = eventName.split('/');
if (e === 'webrtc') {
return true;
}
if (e === 'typing') {

// typing from livechat widget
if (extraData && extraData.token) {
const room = RocketChat.models.Rooms.findOneById(roomId);
if (room && room.t === 'l' && room.v.token === extraData.token) {
return true;
}
}

const user = Meteor.users.findOne(this.userId, {
fields: {
username: 1
Expand Down
88 changes: 88 additions & 0 deletions packages/rocketchat-lib/server/functions/loadMessageHistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import _ from 'underscore';

const hideMessagesOfType = [];

RocketChat.settings.get(/Message_HideType_.+/, function(key, value) {
const type = key.replace('Message_HideType_', '');
const types = type === 'mute_unmute' ? ['user-muted', 'user-unmuted'] : [type];

return types.forEach((type) => {
const index = hideMessagesOfType.indexOf(type);

if (value === true && index === -1) {
return hideMessagesOfType.push(type);
}

if (index > -1) {
return hideMessagesOfType.splice(index, 1);
}
});
});

RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, limit = 20, ls }) {
const options = {
sort: {
ts: -1
},
limit
};

if (!RocketChat.settings.get('Message_ShowEditedStatus')) {
options.fields = {
editedAt: 0
};
}

let records;
if (end != null) {
records = RocketChat.models.Messages.findVisibleByRoomIdBeforeTimestampNotContainingTypes(rid, end, hideMessagesOfType, options).fetch();
} else {
records = RocketChat.models.Messages.findVisibleByRoomIdNotContainingTypes(rid, hideMessagesOfType, options).fetch();
}

const UI_Use_Real_Name = RocketChat.settings.get('UI_Use_Real_Name') === true;

const messages = records.map((message) => {
message.starred = _.findWhere(message.starred, {
_id: userId
});
if (message.u && message.u._id && UI_Use_Real_Name) {
const user = RocketChat.models.Users.findOneById(message.u._id);
message.u.name = user && user.name;
}
if (message.mentions && message.mentions.length && UI_Use_Real_Name) {
message.mentions.forEach((mention) => {
const user = RocketChat.models.Users.findOneById(mention._id);
mention.name = user && user.name;
});
}
return message;
});

let unreadNotLoaded = 0;
let firstUnread;

if (ls != null) {
const firstMessage = messages[messages.length - 1];

if ((firstMessage != null ? firstMessage.ts : undefined) > ls) {
delete options.limit;

const unreadMessages = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestampsNotContainingTypes(rid, ls, firstMessage.ts, hideMessagesOfType, {
limit: 1,
sort: {
ts: 1
}
});

firstUnread = unreadMessages.fetch()[0];
unreadNotLoaded = unreadMessages.count();
}
}

return {
messages,
firstUnread,
unreadNotLoaded
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,11 @@ RocketChat.callbacks.add('afterSaveMessage', function(message, room, userId) {

const user = RocketChat.models.Users.findOneById(message.u._id);

// might be a livechat visitor
if (!user) {
return message;
}

/*
Increment unread couter if direct messages
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,5 @@ standard-minifier-css@1.3.5
standard-minifier-js@2.2.0
shell-server@0.3.0
dynamic-import@0.2.0

konecty:user-presence
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ jquery@1.11.10
kadira:blaze-layout@2.3.0
kadira:flow-router@2.12.1
konecty:nrr@2.0.2
konecty:user-presence@2.0.0
less@2.7.11
livedata@1.0.18
localstorage@1.2.0
Expand All @@ -56,6 +57,7 @@ momentjs:moment@2.20.1
mongo@1.3.1
mongo-dev-server@1.1.0
mongo-id@1.0.6
nooitaf:colors@1.1.2_1
npm-bcrypt@0.9.3
npm-mongo@2.2.33
observe-sequence@1.0.16
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import visitor from '../../imports/client/visitor';

this.CustomFields = (function() {
let queue = {};
let initiated = false;
Expand All @@ -13,7 +15,7 @@ this.CustomFields = (function() {

const init = function() {
Tracker.autorun(function() {
if (Meteor.userId()) {
if (visitor.getId()) {
initiated = true;
Object.keys(queue).forEach((key) => {
setCustomField.call(this, queue[key].token, key, queue[key].value, queue[key].overwrite);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* globals LivechatVideoCall, cordova, JitsiMeetExternalAPI */
import visitor from '../../imports/client/visitor';

LivechatVideoCall = new (class LivechatVideoCall {
constructor() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import visitor from '../../imports/client/visitor';

this.Livechat = new (class Livechat {
constructor() {
this._online = new ReactiveVar(null);
Expand Down Expand Up @@ -30,17 +32,17 @@ this.Livechat = new (class Livechat {
this.stream = new Meteor.Streamer('livechat-room');

Tracker.autorun(() => {
if (this._room.get() && Meteor.userId()) {
if (this._room.get() && visitor.getId()) {
RoomHistoryManager.getMoreIfIsEmpty(this._room.get());
visitor.subscribeToRoom(this._room.get());
visitor.setRoom(this._room.get());

Meteor.call('livechat:getAgentData', this._room.get(), (error, result) => {
Meteor.call('livechat:getAgentData', { roomId: this._room.get(), token: visitor.getToken() }, (error, result) => {
if (!error) {
this._agent.set(result);
}
});
this.stream.on(this._room.get(), (eventData) => {
this.stream.on(this._room.get(), { token: visitor.getToken() }, (eventData) => {
if (!eventData || !eventData.type) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import _ from 'underscore';
import s from 'underscore.string';
import toastr from 'toastr';
import visitor from '../../imports/client/visitor';

this.ChatMessages = class ChatMessages {
init(node) {
Expand Down Expand Up @@ -63,7 +64,7 @@ this.ChatMessages = class ChatMessages {
}
this.clearEditing();
const id = element.getAttribute('id');
const message = ChatMessage.findOne({ _id: id, 'u._id': Meteor.userId() });
const message = ChatMessage.findOne({ _id: id, 'u._id': visitor.getId() });
this.input.value = message.msg;
this.editing.element = element;
this.editing.index = index || this.getEditingIndex(element);
Expand Down Expand Up @@ -122,12 +123,14 @@ this.ChatMessages = class ChatMessages {
ChatMessage.update(result._id, _.omit(result, '_id'));
Livechat.room = result.rid;

visitor.setConnected();

parentCall('callback', 'chat-started');
}
});
};

if (!Meteor.userId()) {
if (!visitor.getId()) {
const guest = {
token: visitor.getToken()
};
Expand All @@ -141,13 +144,8 @@ this.ChatMessages = class ChatMessages {
return showError(error.reason);
}

Meteor.loginWithToken(result.token, (error) => {
if (error) {
return showError(error.reason);
}

sendMessage();
});
visitor.setId(result._id);
sendMessage();
});
} else {
sendMessage();
Expand Down Expand Up @@ -189,20 +187,6 @@ this.ChatMessages = class ChatMessages {
}
}

tryCompletion(input) {
let value = input.value.match(/[^\s]+$/);
if (value && value.length > 0) {
value = value[0];

const re = new RegExp(value, 'i');

const user = Meteor.users.findOne({ username: re }, { fields: { username: 1 } });
if (user) {
input.value = input.value.replace(value, `@${ user.username } `);
}
}
}

keyup(rid, event) {
let i;
const input = event.currentTarget;
Expand Down Expand Up @@ -247,12 +231,6 @@ this.ChatMessages = class ChatMessages {
return;
}

if (k === 9) {
event.preventDefault();
event.stopPropagation();
this.tryCompletion(input);
}

if (k === 27) {
if (this.editing.id) {
event.preventDefault();
Expand Down
Loading

0 comments on commit ec8679c

Please sign in to comment.