Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { twilio, validateTwilioSignature } from '../../../shared/twilio';
- import { getBaseUrl } from '../../../shared/utils';
- import { fetchInboundCallBySid, fetchParticipantByCallSid } from '../phone-call-actions';
- import { TWILIO_CONFERENCE_STATUS_EVENTS } from '../phone-calls-model';
- import * as qs from 'querystring';
- import { twiml } from 'twilio';
- /**
- * @param {object} event - 8base event.
- * @param {object} ctx - 8base context.
- */
- export default async function(event, ctx) {
- console.log('call: inbound-conference-event Running Inbound Calls conference status Webhook...');
- const { callSid } = event.pathParameters;
- const body = qs.parse(event.body);
- const url = `${getBaseUrl(ctx)}/webhook/inbound-call/${callSid}/conference/event`;
- const signature = event.headers['X-Twilio-Signature'];
- const options = { checkPermissions: false };
- //rqstbin({from: "inbound-conference-event", msg: "got here!"})
- let twilioClient = await twilio(body.AccountSid);
- if (validateTwilioSignature(signature, url, body) === false) {
- console.log('call: inbound-conference-event twilio signature failure [' + signature + ']');
- return {
- statusCode: 401,
- body: JSON.stringify({
- message: 'Unauthorized request',
- }),
- };
- }
- console.log(`call: inbound-conference-event Conference ${callSid}:`, body.StatusCallbackEvent);
- if (body.StatusCallbackEvent === TWILIO_CONFERENCE_STATUS_EVENTS.PARTICIPANT_JOIN) {
- console.log('call: inbound-conference-event PARTICIPANT JOIN body;', JSON.stringify(body));
- /**
- * If the participant that is joining the conference is the same that
- * started the call (customer), then call the agents in the company.
- */
- if (body.CallSid === callSid) {
- let call = null;
- try {
- call = await fetchInboundCallBySid(callSid, ctx, options);
- console.log(
- 'call: inbound-conference-event fetched inbound call by SID',
- JSON.stringify(call),
- );
- } catch (e) {
- console.log('call: inbound-conference-event Could not fetch inbound call:', e.message);
- const response = new twiml.VoiceResponse();
- response.say(`Could not fetch inbound call: ${e.message}`);
- return {
- statusCode: 200,
- body: response.toString(),
- };
- }
- try {
- console.log('call: inbound-conference-event will invoke: distribute-inbound-call ');
- await ctx.invokeFunction(
- 'distribute-inbound-call',
- {
- data: {
- callSid: callSid,
- callId: call.id,
- from: `+${call.to.number.code}${call.to.number.number}`,
- agencyId: call.agency.id,
- campaign: call.to.campaign,
- },
- },
- { waitForResponse: false },
- );
- } catch (e) {
- console.log(
- 'call: inbound-conference-event error invoking distribute-inbound-call',
- JSON.stringify(e),
- );
- const response = new twiml.VoiceResponse();
- response.say(`Could contact with any agent: ${e.message}`);
- return {
- statusCode: 200,
- body: response.toString(),
- };
- }
- /**
- * If the participant that is joining the call is one of the
- * initially called agents, then hang up all the other calls.
- */
- } else {
- let call = null;
- let participants = null;
- let conference = null;
- try {
- conference = await twilioClient.conferences(body.ConferenceSid).fetch();
- console.log(
- 'call: inbound-conference-event fetched twilio conference:',
- JSON.stringify(conference),
- );
- } catch (e) {
- console.log('call: inbound-conference-event Could not fetch twilio conference:', e.message);
- }
- try {
- call = await fetchParticipantByCallSid(body.CallSid, ctx, { checkPermissions: false });
- console.log(
- 'call: inbound-conference-event fetched participant by callSID',
- JSON.stringify(call),
- );
- } catch (e) {
- console.log(
- 'call: inbound-conference-event error fetching participant by call sid',
- JSON.stringify(e),
- );
- const response = new twiml.VoiceResponse();
- response.say(`Could not fetch the phone call participant: ${e.message}`);
- return {
- statusCode: 200,
- body: response.toString(),
- };
- }
- if (conference && conference.status !== 'completed') {
- try {
- console.log('call: inbound-conference-event participant BODY', JSON.stringify(body));
- participants = await twilioClient.conferences(body.ConferenceSid).participants.list();
- console.log('call: inbound-conference-event participants list', participants);
- } catch (error) {
- console.log(
- 'call: inbound-conference-event Could not fetch the participants list',
- JSON.stringify(error),
- );
- }
- }
- if (call.isInitialParticipant) {
- console.log(
- 'call: inbound-conference-event, is initial participant, will invoke: hangup-initial-calls ',
- );
- try {
- await ctx.invokeFunction(
- 'hangup-initial-calls',
- {
- data: {
- callSid: callSid,
- participantCallSid: body.CallSid,
- },
- },
- { waitForResponse: false },
- );
- console.log('call: inbound-conference-event hung up call');
- } catch (e) {
- console.log(
- 'call: inbound-conference-event error hanging up initial calls',
- JSON.stringify(e),
- );
- const response = new twiml.VoiceResponse();
- response.say(`Could not hang up other calls: ${e.message}`);
- return {
- statusCode: 200,
- body: response.toString(),
- };
- }
- }
- }
- }
- /**
- * If a participant leaves the conference we check at least if
- * 2 others are connected, if not then the call ends.
- */
- if (body.StatusCallbackEvent === TWILIO_CONFERENCE_STATUS_EVENTS.PARTICIPANT_LEAVE) {
- console.log('call: inbound-conference-event PARTICIPANT LEAVE body;', JSON.stringify(body));
- let conference = null;
- try {
- conference = await twilioClient.conferences(body.ConferenceSid).fetch();
- console.log(
- 'call: inbound-conference-event fetched twilio conference:',
- JSON.stringify(conference),
- );
- } catch (e) {
- console.log('call: inbound-conference-event Could not fetch twilio conference:', e.message);
- }
- if (conference && conference.status !== 'completed') {
- let participants = [];
- try {
- participants = await twilioClient.conferences(body.ConferenceSid).participants.list();
- console.log(
- 'call: inbound-conference-event fetched twilio participants:',
- JSON.stringify(participants),
- );
- } catch (e) {
- console.log('call: inbound-conference-event Could not fetch call participants', e.message);
- const response = new twiml.VoiceResponse();
- response.say(`Could not fetch call participants: ${e.message}`);
- return {
- statusCode: 200,
- body: response.toString(),
- };
- }
- if (participants.length < 2) {
- try {
- await twilioClient.conferences(body.ConferenceSid).update({ status: 'completed' });
- console.log('call: inbound-conference-event set conference as completed');
- } catch (e) {
- console.log('call: inbound-conference-event Could not end conference:', e.message);
- const response = new twiml.VoiceResponse();
- response.say(`Could not end conference: ${e.message}`);
- return {
- statusCode: 200,
- body: response.toString(),
- };
- }
- }
- }
- }
- return {
- statusCode: 200,
- body: JSON.stringify({
- message: 'Conference status updated successfully',
- }),
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment