Skip to content

Commit

Permalink
Fix Livechat API stuff.
Browse files Browse the repository at this point in the history
  • Loading branch information
renatobecker committed Sep 19, 2018
1 parent 46ce71f commit 41994f1
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 48 deletions.
11 changes: 6 additions & 5 deletions packages/rocketchat-livechat/server/api/lib/livechat.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import _ from 'underscore';
import LivechatVisitors from '../../models/LivechatVisitors';

export const online = RocketChat.models.Users.findOnlineAgents().count() > 0;
export function online() {
return RocketChat.models.Users.findOnlineAgents().count() > 0;
}

export function findTriggers() {
return RocketChat.models.LivechatTrigger.findEnabled().fetch().map((trigger) => _.pick(trigger, '_id', 'actions', 'conditions'));
Expand Down Expand Up @@ -46,14 +48,14 @@ export function getRoom(guest, rid) {
ts: new Date(),
};

return RocketChat.Livechat.getRoom(guest, message, { jitsiTimeout: new Date(Date.now() + 3600 * 1000) });
return RocketChat.Livechat.getRoom(guest, message);
}

export function findAgent(agentId) {
return RocketChat.models.Users.getAgentInfo(agentId);
}

const config = () => {
export function settings() {
const initSettings = RocketChat.Livechat.getInitSettings();

return {
Expand Down Expand Up @@ -92,7 +94,6 @@ const config = () => {
values: ['1', '2', '3', '4', '5'],
},
};
};
}

export const settings = config();

46 changes: 24 additions & 22 deletions packages/rocketchat-livechat/server/api/v1/config.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,34 @@
import livechat from '../lib/livechat';
import { findRoom, findGuest, settings, online } from '../lib/livechat';

RocketChat.API.v1.addRoute('livechat/config', {
get() {
const config = livechat.settings;
if (!config.enabled) {
return RocketChat.API.v1.success({ config: { enabled: false } });
}
try {
check(this.queryParams, {
token: Match.Maybe(String),
});

const { online } = livechat;
Object.assign(config, { online });
return RocketChat.API.v1.success({ config });
},
});
const config = settings();
if (!config.enabled) {
return RocketChat.API.v1.success({ config: { enabled: false } });
}

RocketChat.API.v1.addRoute('livechat/config/:token', {
get() {
const config = livechat.settings;
if (!config.enabled) {
return RocketChat.API.v1.success({ config: { enabled: false } });
}
const { status } = online();

let guest;
let room;
let agent;

const { online } = livechat;
const guest = livechat.findGuest(this.urlParams.token);
const room = livechat.findRoom(this.urlParams.token);
const agent = room && room.servedBy && RocketChat.models.Users.getAgentInfo(room.servedBy._id);
if (this.queryParams.token) {
guest = findGuest(this.queryParams.token);
room = findRoom(this.queryParams.token);
agent = room && room.servedBy && RocketChat.models.Users.getAgentInfo(room.servedBy._id);
}

Object.assign(config, { online, guest, room, agent });
Object.assign(config, { online: status, guest, room, agent });

return RocketChat.API.v1.success({ config });
return RocketChat.API.v1.success({ config });
} catch (e) {
return RocketChat.API.v1.failure(e);
}
},
});
2 changes: 1 addition & 1 deletion packages/rocketchat-livechat/server/api/v1/room.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ RocketChat.API.v1.addRoute('livechat/room.survey', {
throw new Meteor.Error('invalid-room');
}

const config = settings;
const config = settings();
if (!config.survey || !config.survey.items || !config.survey.values) {
throw new Meteor.Error('invalid-livechat-config');
}
Expand Down
3 changes: 2 additions & 1 deletion packages/rocketchat-livechat/server/api/v1/videoCall.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ RocketChat.API.v1.addRoute('livechat/video.call/:token', {

const rid = this.queryParams.rid || Random.id();
const { room } = getRoom(guest, rid);
const config = settings;
const config = settings();
if (!config.theme || !config.theme.actionLinks) {
throw new Meteor.Error('invalid-livechat-config');
}
Expand All @@ -34,6 +34,7 @@ RocketChat.API.v1.addRoute('livechat/video.call/:token', {
domain: RocketChat.settings.get('Jitsi_Domain'),
provider: 'jitsi',
room: RocketChat.settings.get('Jitsi_URL_Room_Prefix') + RocketChat.settings.get('uniqueID') + rid,
timeout: new Date(Date.now() + 3600 * 1000),
};

return RocketChat.API.v1.success({ videoCall });
Expand Down
7 changes: 6 additions & 1 deletion packages/rocketchat-livechat/server/api/v1/visitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,14 @@ RocketChat.API.v1.addRoute('livechat/visitor', {
});

const { token, customFields } = this.bodyParams.visitor;
const guest = this.bodyParams.visitor;

if (this.bodyParams.visitor.phone) {
guest.phone = { number: this.bodyParams.visitor.phone };
}

let visitor = LivechatVisitors.getVisitorByToken(token);
const visitorId = (visitor) ? visitor._id : RocketChat.Livechat.registerGuest(this.bodyParams.visitor);
const visitorId = RocketChat.Livechat.registerGuest(guest);

if (customFields && customFields instanceof Array) {
customFields.forEach((field) => {
Expand Down
36 changes: 18 additions & 18 deletions packages/rocketchat-livechat/server/lib/Livechat.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ RocketChat.Livechat = {
if (RocketChat.settings.get('Livechat_Routing_Method') === 'External') {
for (let i = 0; i < 10; i++) {
try {
const queryString = department ? `?departmentId=${ department }` : '';
const result = HTTP.call('GET', `${ RocketChat.settings.get('Livechat_External_Queue_URL') }${ queryString }`, {
const queryString = department ? `?departmentId=${department}` : '';
const result = HTTP.call('GET', `${RocketChat.settings.get('Livechat_External_Queue_URL')}${queryString}`, {
headers: {
'User-Agent': 'RocketChat Server',
Accept: 'application/json',
Expand Down Expand Up @@ -416,7 +416,7 @@ RocketChat.Livechat = {
extraData._hidden = true;
}

return RocketChat.models.Messages.createNavigationHistoryWithRoomIdMessageAndUser(roomId, `${ pageTitle } - ${ pageUrl }`, user, extraData);
return RocketChat.models.Messages.createNavigationHistoryWithRoomIdMessageAndUser(roomId, `${pageTitle} - ${pageUrl}`, user, extraData);
}

return;
Expand Down Expand Up @@ -567,7 +567,7 @@ RocketChat.Livechat = {
};
return HTTP.post(RocketChat.settings.get('Livechat_webhookUrl'), options);
} catch (e) {
RocketChat.Livechat.logger.webhook.error(`Response error on ${ trying } try ->`, e);
RocketChat.Livechat.logger.webhook.error(`Response error on ${trying} try ->`, e);
// try 10 times after 10 seconds each
if (trying < 10) {
RocketChat.Livechat.logger.webhook.warn('Will try again in 10 seconds ...');
Expand Down Expand Up @@ -603,8 +603,8 @@ RocketChat.Livechat = {
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 }`),
os: ua.getOS().name && (`${ua.getOS().name} ${ua.getOS().version}`),
browser: ua.getBrowser().name && (`${ua.getBrowser().name} ${ua.getBrowser().version}`),
customFields: visitor.livechatData,
},
};
Expand Down Expand Up @@ -778,7 +778,7 @@ RocketChat.Livechat = {
throw new Meteor.Error('error-invalid-room', 'Invalid room');
}

const messages = RocketChat.models.Messages.findVisibleByRoomIdNotContainingTypes(rid, ['livechat_navigation_history'], { sort: { ts : 1 } });
const messages = RocketChat.models.Messages.findVisibleByRoomIdNotContainingTypes(rid, ['livechat_navigation_history'], { sort: { ts: 1 } });

let html = '<div> <hr>';
messages.forEach((message) => {
Expand All @@ -795,13 +795,13 @@ RocketChat.Livechat = {

const datetime = moment(message.ts).locale(userLanguage).format('LLL');
const singleMessage = `
<p><strong>${ author }</strong> <em>${ datetime }</em></p>
<p>${ message.msg }</p>
<p><strong>${ author}</strong> <em>${datetime}</em></p>
<p>${ message.msg}</p>
`;
html = html + singleMessage;
});

html = `${ html }</div>`;
html = `${html}</div>`;

let fromEmail = RocketChat.settings.get('From_Email').match(/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/i);

Expand All @@ -827,13 +827,13 @@ RocketChat.Livechat = {
return false;
}

const message = (`${ data.message }`).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
const message = (`${data.message}`).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');

const html = `
<h1>New livechat message</h1>
<p><strong>Visitor name:</strong> ${ data.name }</p>
<p><strong>Visitor email:</strong> ${ data.email }</p>
<p><strong>Message:</strong><br>${ message }</p>`;
<p><strong>Visitor name:</strong> ${ data.name}</p>
<p><strong>Visitor email:</strong> ${ data.email}</p>
<p><strong>Message:</strong><br>${ message}</p>`;

let fromEmail = RocketChat.settings.get('From_Email').match(/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/i);

Expand All @@ -854,9 +854,9 @@ RocketChat.Livechat = {
}

const to = RocketChat.settings.get('Livechat_offline_email');
const from = `${ data.name } - ${ data.email } <${ fromEmail }>`;
const replyTo = `${ data.name } <${ data.email }>`;
const subject = `Livechat offline message from ${ data.name }: ${ (`${ data.message }`).substring(0, 20) }`;
const from = `${data.name} - ${data.email} <${fromEmail}>`;
const replyTo = `${data.name} <${data.email}>`;
const subject = `Livechat offline message from ${data.name}: ${(`${data.message}`).substring(0, 20)}`;

this.sendEmail(from, to, replyTo, subject, html);

Expand All @@ -874,7 +874,7 @@ RocketChat.Livechat.stream.allowRead((roomId, extraData) => {
const room = RocketChat.models.Rooms.findOneById(roomId);

if (!room) {
console.warn(`Invalid eventName: "${ roomId }"`);
console.warn(`Invalid eventName: "${roomId}"`);
return false;
}

Expand Down

0 comments on commit 41994f1

Please sign in to comment.