Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { getBaseUrl } from '../../../shared/utils';
- import { validateTwilioSignature } from '../../../shared/twilio';
- import { parsePhoneNumber } from '../../phone-numbers/phone-numbers-utils';
- import {
- createInboundPhoneCall,
- getCallDropResponse,
- fetchInboundCallInfo,
- } from '../phone-call-actions';
- import { twiml } from 'twilio';
- import * as qs from 'querystring';
- /**
- * Inbound calls webhook handler.
- *
- * @param {object} event - 8base event.
- * @param {object} ctx - 8base context.
- *
- * @returns {Promise} The webhook result.
- */
- export default async function(event, ctx) {
- console.log('call: Beginning inbound-call-start');
- console.log('call: inbound-call-start Running Inbound Calls Webhook...');
- const { agency } = event.pathParameters;
- const body = qs.parse(event.body);
- const signature = event.headers['X-Twilio-Signature'];
- const url = `${getBaseUrl(ctx)}/webhook/calls/inbound/${agency}`;
- const headers = { 'Content-Type': 'text/xml' };
- const options = { checkPermissions: false };
- const response = new twiml.VoiceResponse();
- if (validateTwilioSignature(signature, url, body) === false) {
- console.log('call: inbound-call-start Invalid twilio signature [' + signature + ']');
- return {
- statusCode: 401,
- body: JSON.stringify({
- message: 'Unauthorized request',
- }),
- };
- }
- const from = parsePhoneNumber(body.From);
- const to = parsePhoneNumber(body.To);
- let responses = [];
- let call = null;
- try {
- /*responses = await Promise.all([
- fetchLeadPhoneFromNumber(from.number, agency, ctx, options),
- fetchAgencyPhoneFromNumber(to.number, agency, ctx, options),
- fetchActiveUsers(ctx, options, agency),
- ]);*/
- responses = await fetchInboundCallInfo(from.number, to.number, agency, ctx, options);
- console.log('call: inbound-call-start RESPONSES: After', JSON.stringify(responses));
- } catch (e) {
- console.log('call: inbound-call-start Could not fetch all resources:', e.message);
- const response = new twiml.VoiceResponse();
- response.say(`Could not fetch agency phone number: ${e.message}`);
- return {
- statusCode: 200,
- body: response.toString(),
- };
- }
- console.log('call: inbound-call-start After Promise.all', new Date().toLocaleString());
- const [leadPhone, agencyPhone, activeUsers] = responses;
- console.log('call: inbound-call-start agencyPhone', agencyPhone);
- const record = agencyPhone?.agency?.phoneCallSettings?.recordCalls ? true : false;
- const allowVoicemail = Boolean(agencyPhone?.agency?.phoneCallSettings?.voicemail);
- const voicemailUrl = agencyPhone?.agency?.voicemailUrl;
- if (!agencyPhone) {
- console.log('call: inbound-call-start Unassigned phone number:', body.To);
- response.say('This phone number is no longer available', {
- voice: 'woman',
- });
- return {
- headers,
- statusCode: 200,
- body: response.toString(),
- };
- }
- const avialable = activeUsers.count > 0;
- console.log('call: inbound-call-start Available Users', avialable);
- try {
- call = await createInboundPhoneCall(
- {
- from: body.From,
- to: agencyPhone.id,
- agency: agency,
- callSid: body.CallSid,
- lead: leadPhone ? leadPhone.lead.id : undefined,
- status: avialable ? undefined : 'no-answer',
- },
- ctx,
- options,
- );
- console.log('call: inbound-call-start created inbound phone call', JSON.stringify(call));
- } catch (e) {
- console.log('call: inbound-call-start Could not create call object:', e.message);
- const response = new twiml.VoiceResponse();
- response.say(`Could not create call object: ${e.message}`);
- return {
- statusCode: 200,
- body: response.toString(),
- };
- }
- if (!avialable) {
- console.log('call: inbound-call-start No users available');
- return {
- headers,
- statusCode: 200,
- body: getCallDropResponse(ctx, call.id, allowVoicemail, voicemailUrl),
- };
- }
- response
- .dial({
- action: `${getBaseUrl(ctx)}/webhook/inbound-call/${call.id}/finished`,
- answerOnBridge: true,
- record: record,
- trim: true,
- })
- .conference(
- {
- beep: true,
- startConferenceOnEnter: false,
- endConferenceOnExit: true,
- waitUrl: `${getBaseUrl(ctx)}/webhook/inbound-wait-conference-action/${call.id}`,
- waitMethod: 'POST',
- statusCallbackMethod: 'POST',
- statusCallback: `${getBaseUrl(ctx)}/webhook/inbound-call/${body.CallSid}/conference/event`,
- statusCallbackEvent: 'start end join leave',
- },
- body.CallSid,
- );
- console.log('call: inbound-call-start twiml:', response.toString());
- return {
- headers,
- statusCode: 200,
- body: response.toString(),
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment