-
Notifications
You must be signed in to change notification settings - Fork 10k
/
Livechat.js
1432 lines (1196 loc) · 41.6 KB
/
Livechat.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dns from 'dns';
import { Meteor } from 'meteor/meteor';
import { Match, check } from 'meteor/check';
import { Random } from 'meteor/random';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import { HTTP } from 'meteor/http';
import _ from 'underscore';
import s from 'underscore.string';
import moment from 'moment-timezone';
import UAParser from 'ua-parser-js';
import { Users as UsersRaw, LivechatVisitors, LivechatCustomField, Settings } from '@rocket.chat/models';
import { VideoConf, api } from '@rocket.chat/core-services';
import { QueueManager } from './QueueManager';
import { RoutingManager } from './RoutingManager';
import { Analytics } from './Analytics';
import { settings } from '../../../settings/server';
import { getTimezone } from '../../../utils/server/lib/getTimezone';
import { callbacks } from '../../../../lib/callbacks';
import {
Users,
LivechatRooms,
Messages,
Subscriptions,
Rooms,
LivechatDepartmentAgents,
LivechatDepartment,
LivechatInquiry,
} from '../../../models/server';
import { Logger } from '../../../logger/server';
import { hasPermission, hasRole, canAccessRoom, roomAccessAttributes } from '../../../authorization/server';
import * as Mailer from '../../../mailer';
import { sendMessage } from '../../../lib/server/functions/sendMessage';
import { updateMessage } from '../../../lib/server/functions/updateMessage';
import { deleteMessage } from '../../../lib/server/functions/deleteMessage';
import { FileUpload } from '../../../file-upload/server';
import { normalizeTransferredByData, parseAgentCustomFields, updateDepartmentAgents, validateEmail } from './Helper';
import { Apps, AppEvents } from '../../../apps/server';
import { businessHourManager } from '../business-hour';
import { addUserRoles } from '../../../../server/lib/roles/addUserRoles';
import { removeUserFromRoles } from '../../../../server/lib/roles/removeUserFromRoles';
const logger = new Logger('Livechat');
const dnsResolveMx = Meteor.wrapAsync(dns.resolveMx);
export const Livechat = {
Analytics,
historyMonitorType: 'url',
logger,
webhookLogger: logger.section('Webhook'),
findGuest(token) {
return LivechatVisitors.getVisitorByToken(token, {
projection: {
name: 1,
username: 1,
token: 1,
visitorEmails: 1,
department: 1,
},
});
},
online(department, skipNoAgentSetting = false, skipFallbackCheck = false) {
Livechat.logger.debug(`Checking online agents ${department ? `for department ${department}` : ''}`);
if (!skipNoAgentSetting && settings.get('Livechat_accept_chats_with_no_agents')) {
Livechat.logger.debug('Can accept without online agents: true');
return true;
}
if (settings.get('Livechat_assign_new_conversation_to_bot')) {
Livechat.logger.debug(`Fetching online bot agents for department ${department}`);
const botAgents = Livechat.getBotAgents(department);
const onlineBots = botAgents.count();
Livechat.logger.debug(`Found ${onlineBots} online`);
if (onlineBots > 0) {
return true;
}
}
const agentsOnline = Livechat.checkOnlineAgents(department, {}, skipFallbackCheck);
Livechat.logger.debug(`Are online agents ${department ? `for department ${department}` : ''}?: ${agentsOnline}`);
return agentsOnline;
},
getNextAgent(department) {
return RoutingManager.getNextAgent(department);
},
getAgents(department) {
if (department) {
// TODO: This and all others should get the user's info as well
return LivechatDepartmentAgents.findByDepartmentId(department);
}
return Users.findAgents();
},
getOnlineAgents(department, agent) {
if (agent?.agentId) {
return Users.findOnlineAgents(agent.agentId);
}
if (department) {
return LivechatDepartmentAgents.getOnlineForDepartment(department);
}
return Users.findOnlineAgents();
},
checkOnlineAgents(department, agent, skipFallbackCheck = false) {
if (agent?.agentId) {
return Users.checkOnlineAgents(agent.agentId);
}
if (department) {
const onlineForDep = LivechatDepartmentAgents.checkOnlineForDepartment(department);
if (onlineForDep || skipFallbackCheck) {
return onlineForDep;
}
const dep = LivechatDepartment.findOneById(department);
if (!dep?.fallbackForwardDepartment) {
return onlineForDep;
}
return this.checkOnlineAgents(dep?.fallbackForwardDepartment);
}
return Users.checkOnlineAgents();
},
getBotAgents(department) {
if (department) {
return LivechatDepartmentAgents.getBotsForDepartment(department);
}
return Users.findBotAgents();
},
getRequiredDepartment(onlineRequired = true) {
const departments = LivechatDepartment.findEnabledWithAgents();
return departments.fetch().find((dept) => {
if (!dept.showOnRegistration) {
return false;
}
if (!onlineRequired) {
return true;
}
const onlineAgents = LivechatDepartmentAgents.getOnlineForDepartment(dept._id);
return onlineAgents && onlineAgents.count() > 0;
});
},
async getRoom(guest, message, roomInfo, agent, extraData) {
if (!this.enabled()) {
throw new Meteor.Error('error-omnichannel-is-disabled');
}
Livechat.logger.debug(`Attempting to find or create a room for visitor ${guest._id}`);
let room = LivechatRooms.findOneById(message.rid);
let newRoom = false;
if (room && !room.open) {
Livechat.logger.debug(`Last room for visitor ${guest._id} closed. Creating new one`);
message.rid = Random.id();
room = null;
}
if (guest.department && !LivechatDepartment.findOneById(guest.department)) {
await LivechatVisitors.removeDepartmentById(guest._id);
guest = await LivechatVisitors.findOneById(guest._id);
}
if (room == null) {
const defaultAgent = callbacks.run('livechat.checkDefaultAgentOnNewRoom', agent, guest);
// if no department selected verify if there is at least one active and pick the first
if (!defaultAgent && !guest.department) {
const department = this.getRequiredDepartment();
Livechat.logger.debug(`No department or default agent selected for ${guest._id}`);
if (department) {
Livechat.logger.debug(`Assigning ${guest._id} to department ${department._id}`);
guest.department = department._id;
}
}
// delegate room creation to QueueManager
Livechat.logger.debug(`Calling QueueManager to request a room for visitor ${guest._id}`);
room = await QueueManager.requestRoom({
guest,
message,
roomInfo,
agent: defaultAgent,
extraData,
});
newRoom = true;
Livechat.logger.debug(`Room obtained for visitor ${guest._id} -> ${room._id}`);
}
if (!room || room.v.token !== guest.token) {
Livechat.logger.debug(`Visitor ${guest._id} trying to access another visitor's room`);
throw new Meteor.Error('cannot-access-room');
}
if (newRoom) {
Messages.setRoomIdByToken(guest.token, room._id);
}
return { room, newRoom };
},
async sendMessage({ guest, message, roomInfo, agent }) {
const { room, newRoom } = await this.getRoom(guest, message, roomInfo, agent);
if (guest.name) {
message.alias = guest.name;
}
return _.extend(sendMessage(guest, message, room), {
newRoom,
showConnecting: this.showConnecting(),
});
},
updateMessage({ guest, message }) {
check(message, Match.ObjectIncluding({ _id: String }));
const originalMessage = Messages.findOneById(message._id);
if (!originalMessage || !originalMessage._id) {
return;
}
const editAllowed = settings.get('Message_AllowEditing');
const editOwn = originalMessage.u && originalMessage.u._id === guest._id;
if (!editAllowed || !editOwn) {
throw new Meteor.Error('error-action-not-allowed', 'Message editing not allowed', {
method: 'livechatUpdateMessage',
});
}
updateMessage(message, guest);
return true;
},
async deleteMessage({ guest, message }) {
Livechat.logger.debug(`Attempting to delete a message by visitor ${guest._id}`);
check(message, Match.ObjectIncluding({ _id: String }));
const msg = Messages.findOneById(message._id);
if (!msg || !msg._id) {
return;
}
const deleteAllowed = settings.get('Message_AllowDeleting');
const editOwn = msg.u && msg.u._id === guest._id;
if (!deleteAllowed || !editOwn) {
Livechat.logger.debug('Cannot delete message: not allowed');
throw new Meteor.Error('error-action-not-allowed', 'Message deleting not allowed', {
method: 'livechatDeleteMessage',
});
}
await deleteMessage(message, guest);
return true;
},
async registerGuest({ id, token, name, email, department, phone, username, connectionData, status = 'online' } = {}) {
check(token, String);
check(id, Match.Maybe(String));
Livechat.logger.debug(`New incoming conversation: id: ${id} | token: ${token}`);
let userId;
const updateUser = {
$set: {
token,
status,
...(phone?.number ? { phone: [{ phoneNumber: phone.number }] } : {}),
...(name ? { name } : {}),
},
};
if (email) {
email = email.trim().toLowerCase();
validateEmail(email);
updateUser.$set.visitorEmails = [{ address: email }];
}
if (department) {
Livechat.logger.debug(`Attempt to find a department with id/name ${department}`);
const dep = LivechatDepartment.findOneByIdOrName(department);
if (!dep) {
Livechat.logger.debug('Invalid department provided');
throw new Meteor.Error('error-invalid-department', 'The provided department is invalid', {
method: 'registerGuest',
});
}
Livechat.logger.debug(`Assigning visitor ${token} to department ${dep._id}`);
updateUser.$set.department = dep._id;
}
const user = await LivechatVisitors.getVisitorByToken(token, { projection: { _id: 1 } });
let existingUser = null;
if (user) {
Livechat.logger.debug('Found matching user by token');
userId = user._id;
} else if (phone?.number && (existingUser = await LivechatVisitors.findOneVisitorByPhone(phone.number))) {
Livechat.logger.debug('Found matching user by phone number');
userId = existingUser._id;
// Don't change token when matching by phone number, use current visitor token
updateUser.$set.token = existingUser.token;
} else if (email && (existingUser = await LivechatVisitors.findOneGuestByEmailAddress(email))) {
Livechat.logger.debug('Found matching user by email');
userId = existingUser._id;
} else {
Livechat.logger.debug(`No matches found. Attempting to create new user with token ${token}`);
if (!username) {
username = await LivechatVisitors.getNextVisitorUsername();
}
const userData = {
username,
status,
ts: new Date(),
...(id && { _id: id }),
};
if (settings.get('Livechat_Allow_collect_and_store_HTTP_header_informations')) {
Livechat.logger.debug(`Saving connection data for visitor ${token}`);
const connection = this.connection || connectionData;
if (connection && connection.httpHeaders) {
userData.userAgent = connection.httpHeaders['user-agent'];
userData.ip = connection.httpHeaders['x-real-ip'] || connection.httpHeaders['x-forwarded-for'] || connection.clientAddress;
userData.host = connection.httpHeaders.host;
}
}
userId = (await LivechatVisitors.insertOne(userData)).insertedId;
}
await LivechatVisitors.updateById(userId, updateUser);
return userId;
},
async setDepartmentForGuest({ token, department } = {}) {
check(token, String);
check(department, String);
Livechat.logger.debug(`Switching departments for user with token ${token} (to ${department})`);
const updateUser = {
$set: {
department,
},
};
const dep = LivechatDepartment.findOneById(department);
if (!dep) {
throw new Meteor.Error('invalid-department', 'Provided department does not exists', {
method: 'setDepartmentForGuest',
});
}
const user = await LivechatVisitors.getVisitorByToken(token, { projection: { _id: 1 } });
if (user) {
return LivechatVisitors.updateById(user._id, updateUser);
}
return false;
},
async saveGuest(guestData, userId) {
const { _id, name, email, phone, livechatData = {} } = guestData;
Livechat.logger.debug(`Saving data for visitor ${_id}`);
const updateData = {};
if (name) {
updateData.name = name;
}
if (email) {
updateData.email = email;
}
if (phone) {
updateData.phone = phone;
}
const customFields = {};
if ((!userId || hasPermission(userId, 'edit-livechat-room-customfields')) && Object.keys(livechatData).length) {
Livechat.logger.debug(`Saving custom fields for visitor ${_id}`);
const fields = LivechatCustomField.findByScope('visitor');
for await (const field of fields) {
if (!livechatData.hasOwnProperty(field._id)) {
continue;
}
const value = s.trim(livechatData[field._id]);
if (value !== '' && field.regexp !== undefined && field.regexp !== '') {
const regexp = new RegExp(field.regexp);
if (!regexp.test(value)) {
throw new Meteor.Error(TAPi18n.__('error-invalid-custom-field-value', { field: field.label }));
}
}
customFields[field._id] = value;
}
updateData.livechatData = customFields;
Livechat.logger.debug(`About to update ${Object.keys(customFields).length} custom fields for visitor ${_id}`);
}
const ret = await LivechatVisitors.saveGuestById(_id, updateData);
Meteor.defer(() => {
Apps.triggerEvent(AppEvents.IPostLivechatGuestSaved, _id);
callbacks.run('livechat.saveGuest', updateData);
});
return ret;
},
closeRoom({ user, visitor, room, comment, options = {} }) {
Livechat.logger.debug(`Attempting to close room ${room._id}`);
if (!room || room.t !== 'l' || !room.open) {
return false;
}
const params = callbacks.run('livechat.beforeCloseRoom', { room, options });
const { extraData } = params;
const now = new Date();
const { _id: rid, servedBy, transcriptRequest } = room;
const serviceTimeDuration = servedBy && (now.getTime() - servedBy.ts) / 1000;
const closeData = {
closedAt: now,
chatDuration: (now.getTime() - room.ts) / 1000,
...(serviceTimeDuration && { serviceTimeDuration }),
...extraData,
};
Livechat.logger.debug(`Room ${room._id} was closed at ${closeData.closedAt} (duration ${closeData.chatDuration})`);
if (user) {
Livechat.logger.debug(`Closing by user ${user._id}`);
closeData.closer = 'user';
closeData.closedBy = {
_id: user._id,
username: user.username,
};
} else if (visitor) {
Livechat.logger.debug(`Closing by visitor ${visitor._id}`);
closeData.closer = 'visitor';
closeData.closedBy = {
_id: visitor._id,
username: visitor.username,
};
}
LivechatRooms.closeByRoomId(rid, closeData);
LivechatInquiry.removeByRoomId(rid);
Subscriptions.removeByRoomId(rid);
const message = {
t: 'livechat-close',
msg: comment,
groupable: false,
transcriptRequested: !!transcriptRequest,
};
// Retreive the closed room
room = LivechatRooms.findOneByIdOrName(rid);
Livechat.logger.debug(`Sending closing message to room ${room._id}`);
sendMessage(user || visitor, message, room);
Messages.createCommandWithRoomIdAndUser('promptTranscript', rid, closeData.closedBy);
Meteor.defer(() => {
/**
* @deprecated the `AppEvents.ILivechatRoomClosedHandler` event will be removed
* in the next major version of the Apps-Engine
*/
Apps.getBridges().getListenerBridge().livechatEvent(AppEvents.ILivechatRoomClosedHandler, room);
Apps.getBridges().getListenerBridge().livechatEvent(AppEvents.IPostLivechatRoomClosed, room);
});
callbacks.runAsync('livechat.closeRoom', room);
return true;
},
removeRoom(rid) {
Livechat.logger.debug(`Deleting room ${rid}`);
check(rid, String);
const room = LivechatRooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'livechat:removeRoom',
});
}
Messages.removeByRoomId(rid);
Subscriptions.removeByRoomId(rid);
LivechatInquiry.removeByRoomId(rid);
return LivechatRooms.removeById(rid);
},
async setCustomFields({ token, key, value, overwrite } = {}) {
check(token, String);
check(key, String);
check(value, String);
check(overwrite, Boolean);
Livechat.logger.debug(`Setting custom fields data for visitor with token ${token}`);
const customField = await LivechatCustomField.findOneById(key);
if (!customField) {
throw new Meteor.Error('invalid-custom-field');
}
if (customField.regexp !== undefined && customField.regexp !== '') {
const regexp = new RegExp(customField.regexp);
if (!regexp.test(value)) {
throw new Meteor.Error(TAPi18n.__('error-invalid-custom-field-value', { field: key }));
}
}
if (customField.scope === 'room') {
return LivechatRooms.updateDataByToken(token, key, value, overwrite);
}
return LivechatVisitors.updateLivechatDataByToken(token, key, value, overwrite);
},
enabled() {
return settings.get('Livechat_enabled');
},
getInitSettings() {
const rcSettings = {};
Promise.await(
Settings.findNotHiddenPublic([
'Livechat_title',
'Livechat_title_color',
'Livechat_enable_message_character_limit',
'Livechat_message_character_limit',
'Message_MaxAllowedSize',
'Livechat_enabled',
'Livechat_registration_form',
'Livechat_allow_switching_departments',
'Livechat_offline_title',
'Livechat_offline_title_color',
'Livechat_offline_message',
'Livechat_offline_success_message',
'Livechat_offline_form_unavailable',
'Livechat_display_offline_form',
'Omnichannel_call_provider',
'Language',
'Livechat_enable_transcript',
'Livechat_transcript_message',
'Livechat_fileupload_enabled',
'FileUpload_Enabled',
'Livechat_conversation_finished_message',
'Livechat_conversation_finished_text',
'Livechat_name_field_registration_form',
'Livechat_email_field_registration_form',
'Livechat_registration_form_message',
'Livechat_force_accept_data_processing_consent',
'Livechat_data_processing_consent_text',
'Livechat_show_agent_info',
'Livechat_clear_local_storage_when_chat_ended',
]).forEach((setting) => {
rcSettings[setting._id] = setting.value;
}),
);
rcSettings.Livechat_history_monitor_type = settings.get('Livechat_history_monitor_type');
rcSettings.Livechat_Show_Connecting = this.showConnecting();
return rcSettings;
},
async saveRoomInfo(roomData, guestData, userId) {
Livechat.logger.debug(`Saving room information on room ${roomData._id}`);
const { livechatData = {} } = roomData;
const customFields = {};
if ((!userId || hasPermission(userId, 'edit-livechat-room-customfields')) && Object.keys(livechatData).length) {
Livechat.logger.debug(`Updating custom fields on room ${roomData._id}`);
const fields = LivechatCustomField.findByScope('room');
for await (const field of fields) {
if (!livechatData.hasOwnProperty(field._id)) {
continue;
}
const value = s.trim(livechatData[field._id]);
if (value !== '' && field.regexp !== undefined && field.regexp !== '') {
const regexp = new RegExp(field.regexp);
if (!regexp.test(value)) {
throw new Meteor.Error(TAPi18n.__('error-invalid-custom-field-value', { field: field.label }));
}
}
customFields[field._id] = value;
}
roomData.livechatData = customFields;
Livechat.logger.debug(`About to update ${Object.keys(customFields).length} custom fields on room ${roomData._id}`);
}
if (!LivechatRooms.saveRoomById(roomData)) {
Livechat.logger.debug(`Failed to save room information on room ${roomData._id}`);
return false;
}
Meteor.defer(() => {
Apps.triggerEvent(AppEvents.IPostLivechatRoomSaved, roomData._id);
});
callbacks.runAsync('livechat.saveRoom', roomData);
if (guestData?.name?.trim().length) {
const { _id: rid } = roomData;
const { name } = guestData;
return (
Rooms.setFnameById(rid, name) &&
LivechatInquiry.setNameByRoomId(rid, name) &&
// This one needs to be the last since the agent may not have the subscription
// when the conversation is in the queue, then the result will be 0(zero)
Subscriptions.updateDisplayNameByRoomId(rid, name)
);
}
},
closeOpenChats(userId, comment) {
Livechat.logger.debug(`Closing open chats for user ${userId}`);
const user = Users.findOneById(userId);
LivechatRooms.findOpenByAgent(userId).forEach((room) => {
this.closeRoom({ user, room, comment });
});
},
forwardOpenChats(userId) {
Livechat.logger.debug(`Transferring open chats for user ${userId}`);
LivechatRooms.findOpenByAgent(userId).forEach((room) => {
// TODO: refactor to use normal await
const guest = Promise.await(LivechatVisitors.findOneById(room.v._id));
const user = Users.findOneById(userId);
const { _id, username, name } = user;
const transferredBy = normalizeTransferredByData({ _id, username, name }, room);
Promise.await(
this.transfer(room, guest, {
roomId: room._id,
transferredBy,
departmentId: guest.department,
}),
);
});
},
savePageHistory(token, roomId, pageInfo) {
Livechat.logger.debug(`Saving page movement history for visitor with token ${token}`);
if (pageInfo.change !== Livechat.historyMonitorType) {
return;
}
const user = Users.findOneById('rocket.cat');
const pageTitle = pageInfo.title;
const pageUrl = pageInfo.location.href;
const extraData = {
navigation: {
page: pageInfo,
token,
},
};
if (!roomId) {
// keep history of unregistered visitors for 1 month
const keepHistoryMiliseconds = 2592000000;
extraData.expireAt = new Date().getTime() + keepHistoryMiliseconds;
}
if (!settings.get('Livechat_Visitor_navigation_as_a_message')) {
extraData._hidden = true;
}
return Messages.createNavigationHistoryWithRoomIdMessageAndUser(roomId, `${pageTitle} - ${pageUrl}`, user, extraData);
},
saveTransferHistory(room, transferData) {
Livechat.logger.debug(`Saving transfer history for room ${room._id}`);
const { departmentId: previousDepartment } = room;
const { department: nextDepartment, transferredBy, transferredTo, scope, comment } = transferData;
check(
transferredBy,
Match.ObjectIncluding({
_id: String,
username: String,
name: Match.Maybe(String),
type: String,
}),
);
const { _id, username } = transferredBy;
const scopeData = scope || (nextDepartment ? 'department' : 'agent');
Livechat.logger.debug(`Storing new chat transfer of ${room._id} [Transfered by: ${_id} to ${scopeData}]`);
const transfer = {
transferData: {
transferredBy,
ts: new Date(),
scope: scopeData,
comment,
...(previousDepartment && { previousDepartment }),
...(nextDepartment && { nextDepartment }),
...(transferredTo && { transferredTo }),
},
};
const type = 'livechat_transfer_history';
const transferMessage = {
t: type,
rid: room._id,
ts: new Date(),
msg: '',
u: {
_id,
username,
},
groupable: false,
};
Object.assign(transferMessage, transfer);
sendMessage(transferredBy, transferMessage, room);
},
async transfer(room, guest, transferData) {
Livechat.logger.debug(`Transfering room ${room._id} [Transfered by: ${transferData?.transferredBy?._id}]`);
if (room.onHold) {
Livechat.logger.debug('Cannot transfer. Room is on hold');
throw new Error('error-room-onHold');
}
if (transferData.departmentId) {
transferData.department = LivechatDepartment.findOneById(transferData.departmentId, {
fields: { name: 1 },
});
Livechat.logger.debug(`Transfering room ${room._id} to department ${transferData.department?._id}`);
}
return RoutingManager.transferRoom(room, guest, transferData);
},
returnRoomAsInquiry(rid, departmentId, overrideTransferData = {}) {
Livechat.logger.debug(`Transfering room ${rid} to ${departmentId ? 'department' : ''} queue`);
const room = LivechatRooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'livechat:returnRoomAsInquiry',
});
}
if (!room.open) {
throw new Meteor.Error('room-closed', 'Room closed', {
method: 'livechat:returnRoomAsInquiry',
});
}
if (room.onHold) {
throw new Meteor.Error('error-room-onHold', 'Room On Hold', {
method: 'livechat:returnRoomAsInquiry',
});
}
if (!room.servedBy) {
return false;
}
const user = Users.findOne(room.servedBy._id);
if (!user || !user._id) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'livechat:returnRoomAsInquiry',
});
}
// find inquiry corresponding to room
const inquiry = LivechatInquiry.findOne({ rid });
if (!inquiry) {
return false;
}
const transferredBy = normalizeTransferredByData(user, room);
Livechat.logger.debug(`Transfering room ${room._id} by user ${transferredBy._id}`);
const transferData = { roomId: rid, scope: 'queue', departmentId, transferredBy, ...overrideTransferData };
try {
this.saveTransferHistory(room, transferData);
RoutingManager.unassignAgent(inquiry, departmentId);
} catch (e) {
this.logger.error(e);
throw new Meteor.Error('error-returning-inquiry', 'Error returning inquiry to the queue', {
method: 'livechat:returnRoomAsInquiry',
});
}
callbacks.runAsync('livechat:afterReturnRoomAsInquiry', { room });
return true;
},
sendRequest(postData, callback, attempts = 10) {
if (!attempts) {
return;
}
const secretToken = settings.get('Livechat_secret_token');
const headers = { 'X-RocketChat-Livechat-Token': secretToken };
const options = {
data: postData,
...(secretToken !== '' && secretToken !== undefined && { headers }),
};
try {
return HTTP.post(settings.get('Livechat_webhookUrl'), options);
} catch (err) {
Livechat.webhookLogger.error({ msg: `Response error on ${11 - attempts} try ->`, err });
// try 10 times after 10 seconds each
attempts - 1 && Livechat.webhookLogger.warn('Will try again in 10 seconds ...');
setTimeout(
Meteor.bindEnvironment(function () {
Livechat.sendRequest(postData, callback, attempts - 1);
}),
10000,
);
}
},
async getLivechatRoomGuestInfo(room) {
const visitor = await LivechatVisitors.findOneById(room.v._id);
const agent = Users.findOneById(room.servedBy && room.servedBy._id);
const ua = new UAParser();
ua.setUA(visitor.userAgent);
const postData = {
_id: room._id,
label: room.fname || room.label, // using same field for compatibility
topic: room.topic,
createdAt: room.ts,
lastMessageAt: room.lm,
tags: room.tags,
customFields: room.livechatData,
visitor: {
_id: visitor._id,
token: visitor.token,
name: visitor.name,
username: visitor.username,
email: null,
phone: null,
department: visitor.department,
ip: visitor.ip,
os: ua.getOS().name && `${ua.getOS().name} ${ua.getOS().version}`,
browser: ua.getBrowser().name && `${ua.getBrowser().name} ${ua.getBrowser().version}`,
customFields: visitor.livechatData,
},
};
if (agent) {
const customFields = parseAgentCustomFields(agent.customFields);
postData.agent = {
_id: agent._id,
username: agent.username,
name: agent.name,
email: null,
...(customFields && { customFields }),
};
if (agent.emails && agent.emails.length > 0) {
postData.agent.email = agent.emails[0].address;
}
}
if (room.crmData) {
postData.crmData = room.crmData;
}
if (visitor.visitorEmails && visitor.visitorEmails.length > 0) {
postData.visitor.email = visitor.visitorEmails;
}
if (visitor.phone && visitor.phone.length > 0) {
postData.visitor.phone = visitor.phone;
}
return postData;
},
addAgent(username) {
check(username, String);
const user = Users.findOneByUsername(username, { fields: { _id: 1, username: 1 } });
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'livechat:addAgent' });
}
if (addUserRoles(user._id, ['livechat-agent'])) {
Users.setOperator(user._id, true);
this.setUserStatusLivechat(user._id, user.status !== 'offline' ? 'available' : 'not-available');
return user;
}
return false;
},
addManager(username) {
check(username, String);
const user = Users.findOneByUsername(username, { fields: { _id: 1, username: 1 } });
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'livechat:addManager',
});
}
if (addUserRoles(user._id, ['livechat-manager'])) {
return user;
}
return false;
},
removeAgent(username) {
check(username, String);
const user = Users.findOneByUsername(username, { fields: { _id: 1 } });
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'livechat:removeAgent',
});
}
const { _id } = user;
if (removeUserFromRoles(_id, ['livechat-agent'])) {
Users.setOperator(_id, false);
Users.removeLivechatData(_id);
this.setUserStatusLivechat(_id, 'not-available');
LivechatDepartmentAgents.removeByAgentId(_id);
Promise.await(Promise.all([LivechatVisitors.removeContactManagerByUsername(username), UsersRaw.unsetExtension(_id)]));
return true;
}
return false;
},
removeManager(username) {
check(username, String);
const user = Users.findOneByUsername(username, { fields: { _id: 1 } });
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'livechat:removeManager',
});
}
return removeUserFromRoles(user._id, ['livechat-manager']);
},
async removeGuest(_id) {
check(_id, String);
const guest = await LivechatVisitors.findOneById(_id, { projection: { _id: 1 } });
if (!guest) {
throw new Meteor.Error('error-invalid-guest', 'Invalid guest', {
method: 'livechat:removeGuest',
});
}
await this.cleanGuestHistory(_id);
return LivechatVisitors.removeById(_id);
},
setUserStatusLivechat(userId, status) {
const user = Users.setLivechatStatus(userId, status);
callbacks.runAsync('livechat.setUserStatusLivechat', { userId, status });
return user;
},
setUserStatusLivechatIf(userId, status, condition, fields) {
const user = Promise.await(UsersRaw.setLivechatStatusIf(userId, status, condition, fields));
callbacks.runAsync('livechat.setUserStatusLivechat', { userId, status });
return user;
},
async cleanGuestHistory(_id) {
const guest = await LivechatVisitors.findOneById(_id);
if (!guest) {
throw new Meteor.Error('error-invalid-guest', 'Invalid guest', {
method: 'livechat:cleanGuestHistory',
});
}