Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { twilio, validateTwilioSignature } from '../../../shared/twilio';
- import { getBaseUrl, handleTryCatch } from '../../../shared/utils';
- import * as qs from 'querystring';
- import { fetchInboundCall, getCallDropResponse } from '../phone-call-actions';
- import rqstbin from '../../../shared/rqstbin';
- import { twiml } from 'twilio';
- /**
- * Inbound call drop handler.
- *
- * @param {object} event - The cloud function's event data.
- * @param {object} ctx - The cloud function's context api.
- *
- * @returns {Promise} The webhook response.
- */
- export default async function(event, ctx) {
- const { call, conference } = event.pathParameters;
- const body = qs.parse(event.body);
- const url = `${getBaseUrl(ctx)}/webhook/calls/inbound-drop/${call}/${conference}`;
- const signature = event.headers['X-Twilio-Signature'];
- const headers = { 'Content-Type': 'text/xml' };
- let twilioClient = await twilio(body.AccountSid);
- if (validateTwilioSignature(signature, url, body) === false) {
- console.log('Invalid twilio signature [' + signature + ']');
- return {
- statusCode: 401,
- body: JSON.stringify({
- message: 'Unauthorized request',
- }),
- };
- } else {
- rqstbin({ signature: 'validated', from: 'inbound-call-drop' });
- }
- const [phoneCall, error] = await handleTryCatch(
- fetchInboundCall(call, ctx, { checkPermissions: false }),
- );
- console.log('phoneCall', phoneCall);
- const allowVoicemail = Boolean(phoneCall?.agency?.phoneCallSettings?.voicemail);
- const voicemailUrl = phoneCall?.agency?.voicemailUrl;
- if (error) {
- console.log('call: error updating call data');
- const response = new twiml.VoiceResponse();
- response.say('Sorry we can not retrieve the phone call data.');
- return {
- statusCode: 200,
- body: response.toString(),
- };
- }
- //console.log(getCallDropResponse(ctx, call, voicemail));
- const [updatedCall, updateCallError] = await handleTryCatch(async () => {
- const participants = await twilioClient.conferences(conference).participants.list();
- if (participants.length < 2) {
- return twilioClient.calls(phoneCall.callSid).update({
- twiml: getCallDropResponse(ctx, call, allowVoicemail, voicemailUrl),
- });
- }
- });
- if (updateCallError) {
- console.log('call: error updating call data');
- return {
- statusCode: 200,
- body:
- '<Response><Say>Sorry, we are experiencing technical difficulties. Please try again later.</Say></Response>',
- };
- }
- console.log(JSON.stringify(updatedCall, null, 2));
- return {
- headers,
- statusCode: 200,
- body: '<Response />',
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment