eliecerthoms1

inbound-call-finished.js

Oct 20th, 2023
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { getBaseUrl } from '../../../shared/utils';
  2. import { validateTwilioSignature } from '../../../shared/twilio';
  3. import { createPhoneCallRecording } from '../phone-call-actions';
  4. import * as qs from 'querystring';
  5. import { twiml } from 'twilio';
  6.  
  7. /**
  8.  * Inbound call finished webhook handler.
  9.  *
  10.  * @param {object} event - The cloud function's event data.
  11.  * @param {object} ctx - The cloud function's context api.
  12.  *
  13.  * @returns {Promise} The webhook result.
  14.  */
  15. export default async function(event, ctx) {
  16.   const { callId } = event.pathParameters;
  17.   const body = qs.parse(event.body);
  18.   const url = `${getBaseUrl(ctx)}/webhook/inbound-call/${callId}/finished`;
  19.   const signature = event.headers['X-Twilio-Signature'];
  20.   console.log('call: inbound-call-finished is executing');
  21.  
  22.   if (validateTwilioSignature(signature, url, body) === false) {
  23.     console.log('call: inbound-call-finished Invalid twilio signature [' + signature + ']');
  24.  
  25.     return {
  26.       statusCode: 401,
  27.       body: {
  28.         message: 'Unauthorized request',
  29.       },
  30.     };
  31.   }
  32.  
  33.   if (body.RecordingSid) {
  34.     try {
  35.       console.log('call: inbound-call-finished recording SID:', body.RecordingSid);
  36.  
  37.       await createPhoneCallRecording(
  38.         ctx,
  39.         {
  40.           recordingSid: body.RecordingSid,
  41.           recordingUrl: body.RecordingUrl,
  42.           duration: parseInt(body.RecordingDuration),
  43.           status: 'AVAILABLE',
  44.           inboundCall: { connect: { id: callId } },
  45.         },
  46.         { checkPermissions: false },
  47.       );
  48.     } catch (e) {
  49.       console.log('call: Something happened creating the call recording', JSON.stringify(e));
  50.     }
  51.   }
  52.  
  53.   const response = new twiml.VoiceResponse();
  54.  
  55.   response.hangup();
  56.  
  57.   return {
  58.     headers: { 'Content-Type': 'text/xml' },
  59.     statusCode: 200,
  60.     body: response.toString(),
  61.   };
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment