mirror of
https://github.com/jambonz/jambonz-feature-server.git
synced 2025-12-20 16:50:39 +00:00
snake case REST payloads, support for LCC with child_call_hook, handle 302 on outdial
This commit is contained in:
@@ -7,11 +7,13 @@ const {DbErrorUnprocessableRequest} = require('../utils/errors');
|
||||
/**
|
||||
* validate the call state
|
||||
*/
|
||||
function retrieveCallSession(callSid, opts) {
|
||||
function retrieveCallSession(logger, callSid, opts) {
|
||||
logger.debug(`retrieving session for callSid ${callSid}`);
|
||||
const cs = sessionTracker.get(callSid);
|
||||
if (cs) {
|
||||
const task = cs.currentTask;
|
||||
if (!task || task.name != TaskName.Enqueue) {
|
||||
logger.debug({cs}, 'found call session but not in Enqueue task??');
|
||||
throw new DbErrorUnprocessableRequest(`enqueue api failure: indicated call is not queued: ${task.name}`);
|
||||
}
|
||||
}
|
||||
@@ -19,14 +21,14 @@ function retrieveCallSession(callSid, opts) {
|
||||
}
|
||||
|
||||
/**
|
||||
* notify a waiting session that a conference has started
|
||||
* notify a waiting session that a queue event has occurred
|
||||
*/
|
||||
router.post('/:callSid', async(req, res) => {
|
||||
const logger = req.app.locals.logger;
|
||||
const callSid = req.params.callSid;
|
||||
logger.debug({body: req.body}, 'got enqueue event');
|
||||
logger.debug({callSid, body: req.body}, 'got enqueue event');
|
||||
try {
|
||||
const cs = retrieveCallSession(callSid, req.body);
|
||||
const cs = retrieveCallSession(logger, callSid, req.body);
|
||||
if (!cs) {
|
||||
logger.info(`enqueue: callSid not found ${callSid}`);
|
||||
return res.sendStatus(404);
|
||||
|
||||
43
lib/session/adulting-call-session.js
Normal file
43
lib/session/adulting-call-session.js
Normal file
@@ -0,0 +1,43 @@
|
||||
const CallSession = require('./call-session');
|
||||
|
||||
/**
|
||||
* @classdesc Subclass of CallSession. Represents a CallSession
|
||||
* that was initially a child call leg; i.e. established via a Dial verb.
|
||||
* Now it is all grown up and filling out its own CallSession. Yoo-hoo!
|
||||
* @extends CallSession
|
||||
|
||||
*/
|
||||
class AdultingCallSession extends CallSession {
|
||||
constructor({logger, application, singleDialer, tasks, callInfo}) {
|
||||
super({
|
||||
logger,
|
||||
application,
|
||||
srf: singleDialer.dlg.srf,
|
||||
tasks,
|
||||
callInfo
|
||||
});
|
||||
this.sd = singleDialer;
|
||||
|
||||
this.sd.dlg.on('destroy', () => {
|
||||
this.logger.info('AdultingCallSession: called party hung up');
|
||||
this._callReleased();
|
||||
});
|
||||
this.sd.emit('adulting');
|
||||
}
|
||||
|
||||
get dlg() {
|
||||
return this.sd.dlg;
|
||||
}
|
||||
|
||||
get ep() {
|
||||
return this.sd.ep;
|
||||
}
|
||||
|
||||
get callSid() {
|
||||
return this.callInfo.callSid;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = AdultingCallSession;
|
||||
@@ -45,7 +45,7 @@ class CallSession extends Emitter {
|
||||
this.serviceUrl = srf.locals.serviceUrl;
|
||||
}
|
||||
|
||||
if (!this.isConfirmCallSession && !this.isSmsCallSession) {
|
||||
if (!this.isConfirmCallSession && !this.isSmsCallSession && !this.isAdultingCallSession) {
|
||||
sessionTracker.add(this.callSid, this);
|
||||
}
|
||||
}
|
||||
@@ -161,6 +161,12 @@ class CallSession extends Emitter {
|
||||
return this.application.transferredCall === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns true if this session is a ConfirmCallSession
|
||||
*/
|
||||
get isAdultingCallSession() {
|
||||
return this.constructor.name === 'AdultingCallSession';
|
||||
}
|
||||
/**
|
||||
* returns true if this session is a ConfirmCallSession
|
||||
*/
|
||||
@@ -296,10 +302,47 @@ class CallSession extends Emitter {
|
||||
* @param {object} [opts.call_hook] - new call_status_hook
|
||||
*/
|
||||
async _lccCallHook(opts) {
|
||||
const tasks = await this.requestor.request(opts.call_hook, this.callInfo);
|
||||
if (tasks && tasks.length > 0) {
|
||||
this.logger.info({tasks: listTaskNames(tasks)}, 'CallSession:updateCall new task list');
|
||||
this.replaceApplication(normalizeJambones(this.logger, tasks).map((tdata) => makeTask(this.logger, tdata)));
|
||||
const webhooks = [];
|
||||
let sd;
|
||||
if (opts.call_hook) webhooks.push(this.requestor.request(opts.call_hook, this.callInfo));
|
||||
if (opts.child_call_hook) {
|
||||
/* child call hook only allowed from a connected Dial state */
|
||||
const task = this.currentTask;
|
||||
sd = task.sd;
|
||||
if (task && TaskName.Dial === task.name && sd) {
|
||||
webhooks.push(this.requestor.request(opts.child_call_hook, sd.callInfo));
|
||||
}
|
||||
}
|
||||
const [tasks1, tasks2] = await Promise.all(webhooks);
|
||||
let tasks, childTasks;
|
||||
if (opts.call_hook) {
|
||||
tasks = tasks1;
|
||||
if (opts.child_call_hook) childTasks = tasks2;
|
||||
}
|
||||
else childTasks = tasks1;
|
||||
|
||||
if (childTasks) {
|
||||
const {parentLogger} = this.srf.locals;
|
||||
const childLogger = parentLogger.child({callId: this.callId, callSid: sd.callSid});
|
||||
const t = normalizeJambones(childLogger, childTasks).map((tdata) => makeTask(childLogger, tdata));
|
||||
childLogger.info({tasks: listTaskNames(t)}, 'CallSession:updateCall new task list for child call');
|
||||
const cs = await sd.doAdulting({
|
||||
logger: childLogger,
|
||||
application: this.application,
|
||||
tasks: t
|
||||
});
|
||||
|
||||
/* need to update the callSid of the child with its own (new) AdultingCallSession */
|
||||
sessionTracker.add(cs.callSid, cs);
|
||||
}
|
||||
if (tasks) {
|
||||
const t = normalizeJambones(this.logger, tasks).map((tdata) => makeTask(this.logger, tdata));
|
||||
this.logger.info({tasks: listTaskNames(t)}, 'CallSession:updateCall new task list');
|
||||
this.replaceApplication(t);
|
||||
}
|
||||
else {
|
||||
/* we started a new app on the child leg, but nothing given for parent so hang him up */
|
||||
this.currentTask.kill();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,7 +447,7 @@ class CallSession extends Emitter {
|
||||
if (opts.call_status) {
|
||||
return this._lccCallStatus(opts);
|
||||
}
|
||||
if (opts.call_hook) {
|
||||
if (opts.call_hook || opts.child_call_hook) {
|
||||
return await this._lccCallHook(opts);
|
||||
}
|
||||
if (opts.listen_status) {
|
||||
@@ -489,9 +532,16 @@ class CallSession extends Emitter {
|
||||
const ep = await this.ms.createEndpoint({remoteSdp: this.req.body});
|
||||
ep.cs = this;
|
||||
this.ep = ep;
|
||||
await ep.set('hangup_after_bridge', false);
|
||||
ep.set({
|
||||
hangup_after_bridge: false,
|
||||
park_after_bridge: true
|
||||
}).catch((err) => this.logger.error({err}, 'Error setting park_after_bridge'));
|
||||
|
||||
this.logger.debug('allocated endpoint');
|
||||
this.logger.debug(`allocated endpoint ${this.ep.uuid}`);
|
||||
|
||||
this.ep.on('destroy', () => {
|
||||
this.logger.info(`endpoint was destroyed!! ${this.ep.uuid}`);
|
||||
});
|
||||
|
||||
if (this.direction === CallDirection.Inbound) {
|
||||
if (task.earlyMedia && !this.req.finalResponseSent) {
|
||||
|
||||
@@ -113,6 +113,11 @@ class TaskDial extends Task {
|
||||
}
|
||||
|
||||
get ep() {
|
||||
/**
|
||||
* Note:
|
||||
* this.ep is the B leg-facing endpoint
|
||||
* this.epOther is the A leg-facing endpoint
|
||||
*/
|
||||
if (this.sd) return this.sd.ep;
|
||||
}
|
||||
|
||||
@@ -133,6 +138,8 @@ class TaskDial extends Task {
|
||||
this._installDtmfDetection(cs, this.epOther, this.parentDtmfCollector);
|
||||
await this._attemptCalls(cs);
|
||||
await this.awaitTaskDone();
|
||||
|
||||
this.logger.debug({callSid: this.cs.callSid}, 'Dial:exec task is done, sending actionHook if any');
|
||||
await this.performAction(this.results);
|
||||
this._removeDtmfDetection(cs, this.epOther);
|
||||
this._removeDtmfDetection(cs, this.ep);
|
||||
@@ -146,6 +153,8 @@ class TaskDial extends Task {
|
||||
super.kill(cs);
|
||||
this._removeDtmfDetection(this.cs, this.epOther);
|
||||
this._removeDtmfDetection(this.cs, this.ep);
|
||||
this.logger.debug({callSid: this.cs.callSid}, 'Dial:kill removed dtmf listeners');
|
||||
|
||||
this._killOutdials();
|
||||
if (this.sd) {
|
||||
this.sd.kill();
|
||||
@@ -212,6 +221,7 @@ class TaskDial extends Task {
|
||||
_removeDtmfDetection(cs, ep) {
|
||||
if (ep) {
|
||||
delete ep.dtmfDetector;
|
||||
this.logger.debug(`Dial:_removeDtmfDetection endpoint ${ep.uuid}`);
|
||||
ep.removeAllListeners('dtmf');
|
||||
}
|
||||
}
|
||||
@@ -219,13 +229,18 @@ class TaskDial extends Task {
|
||||
_onDtmf(cs, ep, evt) {
|
||||
if (ep.dtmfDetector) {
|
||||
const match = ep.dtmfDetector.keyPress(evt.dtmf);
|
||||
const requestor = ep.dtmfDetector === this.parentDtmfCollector ?
|
||||
cs.requestor :
|
||||
this.sd.requestor;
|
||||
if (match) {
|
||||
this.logger.debug(`parentCall triggered dtmf match: ${match}`);
|
||||
requestor.request(this.dtmfHook, Object.assign({dtmf: match}, cs.callInfo))
|
||||
.catch((err) => this.logger.info(err, 'Dial:_onDtmf - error'));
|
||||
this.logger.debug({callSid: this.cs.callSid}, `Dial:_onDtmf triggered dtmf match: ${match}`);
|
||||
const requestor = ep.dtmfDetector === this.parentDtmfCollector ?
|
||||
cs.requestor :
|
||||
(this.sd ? this.sd.requestor : null);
|
||||
if (!requestor) {
|
||||
this.logger.info(`Dial:_onDtmf got digits on B leg after adulting: ${evt.dtmf}`);
|
||||
}
|
||||
else {
|
||||
requestor.request(this.dtmfHook, Object.assign({dtmf: match}, cs.callInfo))
|
||||
.catch((err) => this.logger.info(err, 'Dial:_onDtmf - error'));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -351,6 +366,16 @@ class TaskDial extends Task {
|
||||
this.logger.debug('Dial:_attemptCalls - all calls failed after decline, ending task');
|
||||
this.kill(cs);
|
||||
}
|
||||
})
|
||||
.once('adulting', () => {
|
||||
/* child call just adulted and got its own session */
|
||||
this.logger.info('Dial:on_adulting: detaching child call leg');
|
||||
if (this.ep) {
|
||||
this.logger.debug(`Dial:on_adulting: removing dtmf from ${this.ep.uuid}`);
|
||||
this.ep.removeAllListeners('dtmf');
|
||||
}
|
||||
this.sd = null;
|
||||
this.callSid = null;
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.error(err, 'Dial:_attemptCalls');
|
||||
@@ -399,11 +424,14 @@ class TaskDial extends Task {
|
||||
}
|
||||
sessionTracker.add(this.callSid, cs);
|
||||
this.dlg.on('destroy', () => {
|
||||
this.logger.debug('Dial:_selectSingleDial called party hungup, ending dial operation');
|
||||
sessionTracker.remove(this.callSid);
|
||||
if (this.timerMaxCallDuration) clearTimeout(this.timerMaxCallDuration);
|
||||
this.ep.unbridge();
|
||||
this.kill(cs);
|
||||
/* if our child is adulting, he's own his own now.. */
|
||||
if (this.dlg) {
|
||||
this.logger.debug('Dial:_selectSingleDial called party hungup, ending dial operation');
|
||||
sessionTracker.remove(this.callSid);
|
||||
if (this.timerMaxCallDuration) clearTimeout(this.timerMaxCallDuration);
|
||||
this.ep.unbridge();
|
||||
this.kill(cs);
|
||||
}
|
||||
});
|
||||
|
||||
Object.assign(this.results, {
|
||||
|
||||
@@ -275,18 +275,19 @@ class TaskEnqueue extends Task {
|
||||
this.logger.error({err}, `TaskEnqueue:_playHook error retrieving list info for queue ${this.queueName}`);
|
||||
}
|
||||
const json = await cs.application.requestor.request(hook, params);
|
||||
const tasks = normalizeJambones(this.logger, json).map((tdata) => makeTask(this.logger, tdata));
|
||||
|
||||
const allowedTasks = json.filter((task) => allowed.includes(task.verb));
|
||||
if (json.length !== allowedTasks.length) {
|
||||
this.logger.debug({json, allowedTasks}, 'unsupported task');
|
||||
throw new Error(`unsupported verb in dial enqueue waitHook: only ${JSON.stringify(allowed)}`);
|
||||
const allowedTasks = tasks.filter((t) => allowed.includes(t.verb));
|
||||
if (tasks.length !== allowedTasks.length) {
|
||||
this.logger.debug({tasks, allowedTasks}, 'unsupported task');
|
||||
throw new Error(`unsupported verb in enqueue waitHook: only ${JSON.stringify(allowed)}`);
|
||||
}
|
||||
this.logger.debug(`TaskEnqueue:_playHook: executing ${json.length} tasks`);
|
||||
this.logger.debug(`TaskEnqueue:_playHook: executing ${tasks.length} tasks`);
|
||||
|
||||
// check for 'leave' verb and only execute tasks up till then
|
||||
const tasksToRun = [];
|
||||
let leave = false;
|
||||
for (const o of json) {
|
||||
for (const o of tasks) {
|
||||
if (o.verb === TaskName.Leave) {
|
||||
leave = true;
|
||||
this.logger.info('waitHook returned a leave task');
|
||||
@@ -297,14 +298,13 @@ class TaskEnqueue extends Task {
|
||||
|
||||
if (this.killed) return [];
|
||||
else if (tasksToRun.length > 0) {
|
||||
const tasks = normalizeJambones(this.logger, tasksToRun).map((tdata) => makeTask(this.logger, tdata));
|
||||
this._playSession = new ConfirmCallSession({
|
||||
logger: this.logger,
|
||||
application: cs.application,
|
||||
dlg,
|
||||
ep: cs.ep,
|
||||
callInfo: cs.callInfo,
|
||||
tasks
|
||||
tasksToRun
|
||||
});
|
||||
await this._playSession.exec();
|
||||
this._playSession = null;
|
||||
|
||||
@@ -91,6 +91,7 @@ class TaskGather extends Task {
|
||||
kill(cs) {
|
||||
super.kill(cs);
|
||||
this._killAudio();
|
||||
this.ep.removeAllListeners('dtmf');
|
||||
this._resolve('killed');
|
||||
}
|
||||
|
||||
|
||||
@@ -34,11 +34,13 @@ class TaskSay extends Task {
|
||||
})))
|
||||
.filter((fp) => fp && fp.length);
|
||||
|
||||
this.logger.debug({files}, 'synthesized files for tts');
|
||||
this.logger.debug({files, loop: this.loop}, 'synthesized files for tts');
|
||||
if (!this.ep.connected) this.logger.debug('say: endpoint is not connected!');
|
||||
|
||||
while (!this.killed && this.loop-- && this.ep.connected) {
|
||||
let segment = 0;
|
||||
do {
|
||||
this.logger.debug(`playing file ${files[segment]}`);
|
||||
await ep.play(files[segment]);
|
||||
} while (!this.killed && ++segment < files.length);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ const assert = require('assert');
|
||||
const ConfirmCallSession = require('../session/confirm-call-session');
|
||||
const selectSbc = require('./select-sbc');
|
||||
const Registrar = require('@jambonz/mw-registrar');
|
||||
const AdultingCallSession = require('../session/adulting-call-session');
|
||||
const registrar = new Registrar({
|
||||
host: process.env.JAMBONES_REDIS_HOST,
|
||||
port: process.env.JAMBONES_REDIS_PORT || 6379
|
||||
@@ -137,7 +138,7 @@ class SingleDialer extends Emitter {
|
||||
localSdp: this.ep.local.sdp
|
||||
});
|
||||
if (this.target.auth) opts.auth = this.target.auth;
|
||||
this.dlg = await srf.createUAC(uri, opts, {
|
||||
this.dlg = await srf.createUAC(uri, {...opts, followRedirects: true, keepUriOnRedirect: true}, {
|
||||
cbRequest: (err, req) => {
|
||||
if (err) {
|
||||
this.logger.error(err, 'SingleDialer:exec Error creating call');
|
||||
@@ -266,7 +267,7 @@ class SingleDialer extends Emitter {
|
||||
// now execute it in a new ConfirmCallSession
|
||||
this.logger.debug(`SingleDialer:_executeApp: executing ${tasks.length} tasks`);
|
||||
const cs = new ConfirmCallSession({
|
||||
logger: this.logger,
|
||||
logger: this.baseLogger,
|
||||
application: this.application,
|
||||
dlg: this.dlg,
|
||||
ep: this.ep,
|
||||
@@ -284,6 +285,24 @@ class SingleDialer extends Emitter {
|
||||
}
|
||||
}
|
||||
|
||||
async doAdulting({logger, tasks, application}) {
|
||||
this.logger = logger;
|
||||
this.adulting = true;
|
||||
this.emit('adulting');
|
||||
await this.ep.unbridge()
|
||||
.catch((err) => this.logger.info({err}, 'SingleDialer:doAdulting - failed to unbridge ep'));
|
||||
this.ep.play('silence_stream://1000');
|
||||
const cs = new AdultingCallSession({
|
||||
logger: this.logger,
|
||||
singleDialer: this,
|
||||
application,
|
||||
callInfo: this.callInfo,
|
||||
tasks
|
||||
});
|
||||
cs.exec();
|
||||
return cs;
|
||||
}
|
||||
|
||||
_notifyCallStatusChange({callStatus, sipStatus, duration}) {
|
||||
assert((typeof duration === 'number' && callStatus === CallStatus.Completed) ||
|
||||
(!duration && callStatus !== CallStatus.Completed),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const bent = require('bent');
|
||||
const parseUrl = require('parse-url');
|
||||
const assert = require('assert');
|
||||
|
||||
const snakeCaseKeys = require('snakecase-keys');
|
||||
const toBase64 = (str) => Buffer.from(str || '', 'utf8').toString('base64');
|
||||
|
||||
function basicAuth(username, password) {
|
||||
@@ -62,7 +62,7 @@ class Requestor {
|
||||
* @param {object} [params] - request parameters
|
||||
*/
|
||||
async request(hook, params) {
|
||||
params = params || null;
|
||||
const payload = params ? snakeCaseKeys(params, {exclude: ['customerData', 'sip']}) : null;
|
||||
const url = hook.url || hook;
|
||||
const method = hook.method || 'POST';
|
||||
const {username, password} = typeof hook === 'object' ? hook : {};
|
||||
@@ -70,14 +70,14 @@ class Requestor {
|
||||
assert.ok(url, 'Requestor:request url was not provided');
|
||||
assert.ok, (['GET', 'POST'].includes(method), `Requestor:request method must be 'GET' or 'POST' not ${method}`);
|
||||
|
||||
this.logger.debug({hook, params}, `Requestor:request ${method} ${url}`);
|
||||
this.logger.debug({hook, payload}, `Requestor:request ${method} ${url}`);
|
||||
const startAt = process.hrtime();
|
||||
|
||||
let buf;
|
||||
try {
|
||||
buf = isRelativeUrl(url) ?
|
||||
await this.post(url, params, this.authHeader) :
|
||||
await bent(method, 'buffer', 200, 201, 202)(url, params, basicAuth(username, password));
|
||||
await this.post(url, payload, this.authHeader) :
|
||||
await bent(method, 'buffer', 200, 201, 202)(url, payload, basicAuth(username, password));
|
||||
} catch (err) {
|
||||
this.logger.info({baseUrl: this.baseUrl, url, statusCode: err.statusCode},
|
||||
`web callback returned unexpected error code ${err.statusCode}`);
|
||||
|
||||
Reference in New Issue
Block a user