3 var _ = require('lodash');
4 var jsmin = require('jsmin').jsmin;
5 var Mustache = require('mustache');
6 var querystring = require('querystring');
7 var path = require('path');
8 var md5 = require('md5');
9 var fs = require('fs');
10 var UAParser = require('ua-parser-js');
11 var uaParser = new UAParser();
12 var languageParser = require('accept-language-parser');
13 var ipaddr = require('ipaddr.js');
14 var geoip = require('geoip-lite');
15 var csv = require('to-csv')
17 var config = require('../../config/environment');
18 var Xchatty = require('../../models').Xchatty;
19 var xchatty_components = require('../../components/xchatty');
21 var sequelize = require('../../models').sequelize;
22 var User = require('../../models').User;
23 var Agent = require('../../models').User;
24 var ChatRoom = require('../../models').ChatRoom;
25 var ChatEnquiry = require('../../models').ChatEnquiry;
26 var ChatVisitor = require('../../models').ChatVisitor;
27 var ChatMessage = require('../../models').ChatMessage;
28 var ChatWebsite = require('../../models').ChatWebsite;
32 // var ip = addr.toIPv4Address().octets.join('.');
34 // Get list of xchattys
35 exports.index = function (req, res, next) {
38 .then(function (xchattys) {
39 return res.status(200).send(xchattys);
41 .catch(function (err) {
46 exports.getJsByWebsite = function (req, res, next) {
48 // TO DO: Find the configuration of the website and replace configuration in the file
50 .findById(req.params.id)
51 .then(function (chatWebsite) {
53 'Content-Type': 'application/javascript',
54 'x-timestamp': Date.now(),
58 var js = xchatty_components.js;
59 /*jshint multistr: true */
61 websiteId: req.params.id,
62 // rootPath: path.join(chatWebsite.remote, 'api', 'xchatty/'),
63 rootPath: chatWebsite.remote + '/api/xchatty/',
65 windowFocused: 'false',
67 processingSignUp: 'false',
68 processingEnquiry: 'false',
69 processingSend: 'false',
70 visitorFullname: '""',
72 timerReadMessages: 'null',
73 timerCheckStatus: 'null',
77 isInitialStatusCheck: 'true',
78 muteNotificationSoundOnce: 'false',
79 assetBase: chatWebsite.remote + '/api/xchatty/assets',
80 hasSessionSaf: 'false',
81 restoreOpenState: 'false',
82 animateHover: chatWebsite.animation,
85 headerShape: chatWebsite.header_shape,
86 HeaderOnline: chatWebsite.header_online,
87 OnlineMessage: chatWebsite.online_message,
88 UsernamePlaceholder: chatWebsite.username_placeholder,
89 EmailPlaceholder: chatWebsite.email_placeholder,
90 StartChatButtonText: chatWebsite.start_chat_button,
91 OfflineMessage: chatWebsite.offline_message,
92 HeaderOffline: chatWebsite.header_offline,
93 EnquiryMessagePlaceholder: chatWebsite.enquiry_message_placeholder,
94 EnquiryButtonText: chatWebsite.enquiry_button,
95 downloadTranscript: chatWebsite.download_transcript
98 js = Mustache.render(js, configJS);
102 .catch(function (err) {
108 exports.getStyleByWebsite = function (req, res, next) {
110 // TO DO: Find the configuration of the website and replace configuration in the file
112 .findById(req.params.id)
113 .then(function (chatWebsite) {
116 'Content-Type': 'text/css',
117 'x-timestamp': Date.now(),
121 var css = xchatty_components.css;
124 // assetBase: path.join(chatWebsite.remote, 'api', 'xchatty',
126 assetBase: chatWebsite.remote + '/api/xchatty/assets',
127 color: chatWebsite.color,
128 colorFocus: chatWebsite.color_focus,
129 colorButton: chatWebsite.color_button
132 css = Mustache.render(css, configCSS);
135 .catch(function (err) {
140 exports.getAssets = function (req, res, next) {
141 res.download(path.join(config.root, 'server', 'components', 'xchatty', 'assets', req.query.resource));
144 exports.getJqueryLibrary = function (req, res, next) {
146 // TODO: Find the configuration of the website and replace configuration in the file
148 'Content-Type': 'application/javascript',
149 'x-timestamp': Date.now(),
153 var jquery = xchatty_components.jquery;
158 exports.getStatus = function (req, res, next) {
160 if (!req.session.xchatty) {
161 req.session.xchatty = {};
163 // Get all users (later agents) online in the interface
171 .then(function (users) {
173 if (req.query.data.open_state)
174 req.session.xchatty.open_state = req.query.data.open_state === 'true' ? true : false;
178 has_session_saf: null,
179 signed_up: req.session.xchatty.room_id ? true : false,
180 fullname: req.session.xchatty.fullname ? req.session.xchatty.fullname : '',
181 email: req.session.xchatty.email ? req.session.xchatty.email : '',
182 avatar: req.session.xchatty.avatar ? req.session.xchatty.avatar : '',
183 open_state: req.session.xchatty.open_state || req.session.xchatty.room_id ? true : false,
184 online: users.length ? true : false
187 if (req.session.xchatty.visitor_id) {
191 ChatVisitorId: req.session.xchatty.visitor_id,
195 .then(function (chatRoom) {
197 req.session.xchatty.room_id = chatRoom.id;
198 jsonResponse.signed_up = true;
200 jsonResponse.signed_up = false;
203 res.send(req.query.callback + '(' + JSON.stringify(jsonResponse) + ')');
205 .catch(function (err) {
209 res.send(req.query.callback + '(' + JSON.stringify(jsonResponse) + ')');
213 .catch(function (err) {
218 exports.getMessages = function (req, res, next) {
220 /*jshint multistr: true */
223 ChatRoomId: req.session.xchatty.room_id
227 attributes: ['id', 'name', 'fullname', 'email']
230 attributes: ['id', 'fullname', 'email']
234 if (req.query.data.is_new_page === 'false') {
235 condition.where.id = {
236 $gt: req.query.data.last_id
242 .then(function (chatMessages) {
245 messages: chatMessages,
247 composing_fullname: null
250 res.send(req.query.callback + '(' + JSON.stringify(json) + ')');
252 .catch(function (err) {
257 exports.sendMessage = function (req, res, next) {
259 /*jshint multistr: true */
262 ChatRoomId: req.session.xchatty.room_id
266 attributes: ['id', 'name', 'fullname', 'email']
269 attributes: ['id', 'fullname', 'email']
273 if (req.query.data.is_new_page === 'false') {
274 condition.where.id = {
275 $gt: req.query.data.last_id
281 body: req.query.data.Message.message,
282 ChatRoomId: req.session.xchatty.room_id,
283 ChatVisitorId: req.session.xchatty.visitor_id
285 .then(function (chatMessage) {
286 console.log('chatMessage', chatMessage);
289 .then(function (chatMessages) {
294 messages: chatMessages
297 res.send(req.query.callback + '(' + JSON.stringify(json) + ')');
299 .catch(function (err) {
303 .catch(function (err) {
309 exports.signoutCustomer = function (req, res, next) {
312 .findById(req.session.xchatty.room_id)
313 .then(function (chatRoom) {
314 chatRoom.updateAttributes({
317 .then(function (chatRoom) {
322 req.session.xchatty = {};
323 res.send(req.query.callback + '(' + JSON.stringify(json) + ')');
325 .catch(function (err) {
329 .catch(function (err) {
334 exports.signupCustomer = function (req, res, next) {
335 var ua = uaParser.setUA(req.headers['user-agent']).getResult();
336 var languages = languageParser.parse(req.headers['accept-language']);
337 // var addr = ipaddr.parse(req.connection.remoteAddress);
339 // var ipv4Addr = "151.0.175.186";
340 // var geo = geoip.lookup(ipv4Addr);
343 fullname: req.query.data.Discussion.fullname,
344 email: req.query.data.Discussion.email,
345 // remote_address: addr,
346 remote_address: req.connection.remoteAddress,
347 user_agent: req.headers['user-agent'],
348 visitor_language: req.headers['accept-language'],
349 referer: req.headers.referer,
351 browser: ua.browser.name + ' ' + ua.browser.version,
352 engine: ua.engine.name + ' ' + ua.engine.version,
353 os: ua.os.name + ' ' + ua.os.version,
354 device: ua.device.model ? ua.device.model + ' ' + ua.device.vendor + ' ' + ua.device.type : null,
355 // country: geo.country,
357 // region: geo.region,
358 // latitude: geo.ll.length ? geo.ll[0].toString() : null,
359 // longitude: geo.ll.length ? geo.ll[1].toString() : null,
360 ChatWebsiteId: req.query.chatWebsiteId
365 .then(function (chatVisitor) {
367 req.session.xchatty.fullname = chatVisitor.fullname;
368 req.session.xchatty.email = chatVisitor.email;
369 req.session.xchatty.avatar = md5(chatVisitor.email).toString('base64');
370 req.session.xchatty.visitor_id = chatVisitor.id;
380 /*jshint multistr: true */
381 res.send(req.query.callback + '(' + JSON.stringify(json) + ')');
383 .catch(function (err) {
388 exports.unservedCustomer = function (req, res, next) {
391 .findById(req.session.xchatty.visitor_id)
392 .then(function (chatVisitor) {
394 chatVisitor.updateAttributes({
396 }).then(function () {
401 req.session.xchatty = {};
402 res.send(req.query.callback + '(' + JSON.stringify(json) + ')');
404 .catch(function (err) {
408 .catch(function (err) {
413 exports.submitEnquiry = function (req, res, next) {
418 return sequelize.transaction().then(function (t) {
422 fullname: req.query.data.Enquiry.fullname,
423 email: req.query.data.Enquiry.email,
424 remote_address: req.connection.remoteAddress,
425 user_agent: req.headers['user-agent'],
426 visitor_language: req.headers['accept-language'],
427 referer: req.headers.referer,
433 .then(function (chatVisitor) {
434 _chatVisitor = chatVisitor;
437 username: req.query.data.Enquiry.fullname,
438 email: chatVisitor.email,
439 text: req.query.data.Enquiry.message,
440 ChatWebsiteId: parseInt(req.query.data.Enquiry.websiteId, 10),
441 ChatVisitorId: _chatVisitor.id
454 res.send(req.query.callback + '(' + JSON.stringify({
459 .catch(function (err) {
466 exports.getTranscript = function (req, res, next) {
467 if (req.session.xchatty && req.session.xchatty.visitor_id && req.session.xchatty
472 ChatRoomId: req.session.xchatty.room_id
475 .then(function (chatMessages) {
477 var chatMessageForCSV = [];
478 chatMessages.forEach(function (chatMessage) {
480 name: chatMessage.fullname,
481 text: chatMessage.body.replace(/(\r\n|\n|\r)/gm, " "),
482 date: chatMessage.createdAt
484 chatMessageForCSV.push(chatMsg);
486 var csv_transcript = csv(chatMessageForCSV);
487 res.type('text/csv').status(200).send(csv_transcript);
489 .catch(function (err) {
495 // Get a single xchatty
496 exports.show = function (req, res, next) {
498 .findById(req.params.id)
499 .then(function (xchatty) {
501 return res.sendStatus(404);
503 return res.send(xchatty);
505 .catch(function (err) {
510 // Creates a new xchatty in the DB.
511 exports.create = function (req, res, next) {
514 .then(function (xchatty) {
515 return res.status(201).send(xchatty);
517 .catch(function (err) {
522 // Updates an existing xchatty in the DB.
523 exports.update = function (req, res, next) {
528 .findById(req.params.id)
529 .then(function (xchatty) {
531 return res.sendStatus(404);
533 var updated = _.merge(xchatty, req.body);
536 return res.status(200).send(xchatty);
538 .catch(function (err) {
542 .catch(function (err) {
547 // Deletes a xchatty from the DB.
548 exports.destroy = function (req, res, next) {
550 .findById(req.params.id)
551 .then(function (xchatty) {
553 return res.sendStatus(404);
557 return res.sendStatus(204);
559 .catch(function (err) {
563 .catch(function (err) {