-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathapp.js
341 lines (303 loc) · 9.34 KB
/
app.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
var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var path = require('path');
var q = require('q');
var bluebird = require('bluebird');
var config = require( path.join(__dirname, 'app', 'config') );
var app = express();
app.set('views', path.join(__dirname, 'app', 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static( path.join(__dirname, 'app', 'public')));
var port = process.env.PORT || 5000; // set our port
var twilio = require('twilio');
var client = twilio(config.twilio.sid, config.twilio.token);
var flybase = require('flybase');
var callsRef = flybase.init(config.flybase.app_name, "calls", config.flybase.api_key);
var agentsRef = flybase.init(config.flybase.app_name, "agents", config.flybase.api_key);
var queueid = '';
var good2go = false;
// backend routes =========================================================
client.queues.list(function(err, data) {
var to_go = data.queues.length;
data.queues.forEach(function(queue) {
if( queue.friendlyName === config.twilio.queueName ){
queueid = queue.sid;
console.log( "Queueid = #" + queueid + " for #" + config.twilio.queueName );
good2go = true;
}
to_go--;
if( to_go == 0 ){
if( queueid === '' ){
client.queues.create({
friendlyName: config.twilio.queueName
}, function(err, queue) {
queueid = queue.sid;
});
}
}
});
});
// listen for events via Flybase...
// if an agent gets disconnected then we log them off...
agentsRef.on('agent-removed', function (data) {
var data = JSON.parse( data );
console.log( data.username + " has left the building");
update_agent(data.username,{
status: 'LoggedOut'
});
});
// return number of agents with status set to Ready
agentsRef.on('get-ready-agents', function (data) {
var adNag = function() {
agentsRef.where({"status": 'Ready'}).on('value',function( rec ){
console.log( rec.count() + ' agents are Ready' );
if( rec.count() ){
agentsRef.trigger('agents-ready', rec.count() );
}else{
agentsRef.trigger('agents-ready', "0" );
}
});
};
setTimeout(adNag, 1500);
});
// listen for outgoing calls
app.post('/dial', function (req, res) {
var phonenumber = req.param('PhoneNumber');
var dial_id = config.twilio.fromNumber;
if( typeof req.param('CallerID') !== 'undefined' ){
var dial_id = req.param('CallerID');
}
var twiml = new twilio.TwimlResponse();
twiml.dial(phonenumber, {
callerId:dial_id
});
console.log("Response text for /dial post = #", twiml.toString());
res.writeHead(200, {
'Content-Type':'text/xml'
});
res.end( twiml.toString() );
});
// listen for incoming calls
app.post('/voice', function (req, res) {
var queuename = config.twilio.queueName;
var sid = req.param('CallSid');
var callerid = req.param('Caller');
var addtoq = 0;
var dialqueue = '';
var client_name = '';
// search for agent who has been set to `Ready` for the longest time and connect them to the caller...
getlongestidle(true, function( bestclient ){
if( bestclient ){
console.log("Routing incoming voice call to best agent = #", bestclient);
var client_name = bestclient;
}else{
console.log( 'no agent was found, adding caller to #', config.twilio.queueName );
var dialqueue = queuename;
addtoq = 1;
}
var twiml = new twilio.TwimlResponse();
if( addtoq ){
twiml.say("Please wait for the next available agent",{
voice:'woman'
}).enqueue(config.twilio.queueName);
}else{
twiml.dial({
'timeout':'10',
'action':'/handledialcallstatus',
'callerId':callerid
}, function(node) {
this.client( client_name );
});
update_call(sid, {
'sid': sid,
'agent': client_name,
'status': 'ringing'
});
}
console.log("Response text for /voice post = #", twiml.toString());
res.writeHead(200, {
'Content-Type':'text/xml'
});
res.end( twiml.toString() );
});
});
app.post('/handledialcallstatus', function (req, res) {
var sid = req.param('CallSid');
var twiml = new twilio.TwimlResponse();
if( req.param('DialCallStatus') == 'no-answer' ){
callsRef.where({"sid": sid}).on('value',function( rec ){
if( rec.count() !== null ){
var sidinfo = rec.first().value();
if( sidinfo ){
var agent = sidinfo.agent;
update_agent(agent, {
'status': 'missed'
});
}
// Change agent status for agents that missed calls
}
// redirect and try to get new agent...
twiml.redirect('/voice');
});
}else{
twiml.hangup();
}
console.log("Response text for /handledialcallstatus post = #", twiml.toString());
res.writeHead(200, {
'Content-Type':'text/xml'
});
res.end( twiml.toString() );
});
// assign a twilio call token to the agent
app.get('/token', function(req, res) {
var client_name = "anonymous";
if( typeof req.param("client") !== "undefined" ){
client_name = req.param("client");
}
var capability = new twilio.Capability( config.twilio.sid, config.twilio.token );
capability.allowClientIncoming( client_name );
capability.allowClientOutgoing( config.twilio.appid );
var token = capability.generate();
res.end(token);
});
// return flybase info to the softphone...
app.get('/getconfig', function(req, res) {
res.json({
app_name: config.flybase.app_name,
api_key: config.flybase.api_key
});
});
// return a phone number
app.get('/getcallerid', function(req, res) {
var client_name = "anonymous";
if( typeof req.param("from") !== "undefined" ){
client_name = req.param("from");
}
res.end( config.twilio.fromNumber );
});
app.post('/track', function(req, res) {
});
app.get('/', function(req, res) {
var client_name = "anonymous";
if( typeof req.param("client") !== "undefined" ){
client_name = req.param("client");
}
res.render('index', {
client_name: client_name,
anycallerid: 'none'
});
});
var server = app.listen(port, function() {
console.log('Listening on port %d', server.address().port);
});
// various functions =========================================================
// find the caller who's been `Ready` the longest
function getlongestidle( callrouting, callback ){
if( callrouting ){
agentsRef.where({"status": "DeQueing"}).orderBy( {"readytime":-1} ).on('value').then(function( data ){
var agent = data.first().value();
callback( agent.client );
},function(err){
agentsRef.where({"status": "Ready"}).orderBy( {"readytime":-1} ).on('value').then(function( data ){
var agent = data.first().value();
callback( agent.client );
},function(err){
callback( false );
});
});
}else{
agentsRef.where({"status": "Ready"}).orderBy( {"readytime":-1} ).on('value').then(function( data ){
var agent = data.first().value();
callback( agent.client );
},function(err){
callback( false );
});
}
}
// check if user exists and if they do then we update, otherwise we insert...
function update_agent(client, data, cb){
var d = new Date();
var date = d.toLocaleString();
var callback = cb || null;
agentsRef.where({"client": client}).once('value').then( function( rec ){
var agent = rec.first().value();
for( var i in data ){
agent[i] = data[i];
}
agentsRef.push(agent, function(resp) {
console.log( "agent updated" );
if( callback !== null ){
callback();
}
});
},function(err){
data.client = client;
agentsRef.push(data, function(resp) {
console.log( "agent inserted" );
if( callback !== null ){
callback();
}
});
});
}
function update_call(sid, data){
var d = new Date();
var date = d.toLocaleString();
callsRef.where({"sid": sid}).on('value').then( function( rec ){
var call = rec.first().value();
for( var i in data ){
call[i] = data[i];
}
callsRef.push(call, function(resp) {
console.log( "call updated" );
});
},function(err){
data.sid = sid;
callsRef.push(data, function(resp) {
console.log( "call inserted" );
});
});
}
// call queue handling =========================================================
var qsum = 0;
var checkQueue = function() {
qsum += 1;
var qsize = 0;
var readyagents = 0;
var qname = config.twilio.queueName;
client.queues(queueid).get(function(err, queue) {
qsize = queue.currentSize;
console.log( 'There are #' + qsize + ' callers in the queue (' + queueid + ')' );
if( qsize > 0 ){
agentsRef.where({"status": "Ready"}).orderBy( {"readytime":-1} ).on('value').then(function( agents ){
var readyagents = agents.count();
var bestclient = agents.first().value();
console.log("Found best client - routing to #" + bestclient.client + " - setting agent to DeQueuing status so they aren't sent another call from the queue");
update_agent(bestclient.client, {status: "DeQueing" }, function(){
console.log('redirecting call now!');
client.queues(queueid).members("Front").update({
url: config.twilio.dqueueurl,
method: "POST"
}, function(err, member) {
// console.log(member.position);
});
});
},function(err){
console.log("No Ready agents during queue poll #" + qsum);
});
agentsRef.trigger('agents-ready', readyagents );
agentsRef.trigger('in-queue', qsize );
// restart the check checking
setTimeout(checkQueue, 3000);
}else{
// restart the check checking
console.log("No callers found during queue poll #" + qsum);
setTimeout(checkQueue, 3000);
}
});
};
setTimeout(checkQueue, 1500);