eliecerthoms1

(task) distribute-inbound-call.js

Oct 20th, 2023
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {
  2.   fetchUserIdsToCall,
  3.   createParticipant,
  4.   updateInboundPhoneCall,
  5. } from '../phone-call-actions';
  6. import { twilio } from '../../../shared/twilio';
  7. import { getAgencySIDFromAgencyID } from '../../../shared/users/users-actions';
  8. import { getBaseUrl } from '../../../shared/utils';
  9. import * as qs from 'querystring';
  10.  
  11. /**
  12.  * Task handler that fetches the available users
  13.  * in an agency and calls them.
  14.  *
  15.  * @param {object} event - The cloud function's event.
  16.  * @param {object} ctx - The cloud function's context api.
  17.  *
  18.  * @returns {Promise<void>} The event object.
  19.  */
  20. export default async function(event, ctx) {
  21.   console.log('call: triggered distribute-inbound-call');
  22.   const body = qs.parse(event.body);
  23.   console.log('call: distribute-inbound-call body', JSON.stringify(body));
  24.  
  25.   let agencySID;
  26.  
  27.   try {
  28.     agencySID = await getAgencySIDFromAgencyID(ctx, { id: event.data.agencyId });
  29.   } catch (error) {
  30.     console.log('call: distribute-inbound-call error getting agency', JSON.stringify(error));
  31.     return {
  32.       statusCode: 400,
  33.       body: {
  34.         message: error.message,
  35.       },
  36.     };
  37.   }
  38.  
  39.   let twilioClient = await twilio(agencySID);
  40.   const {
  41.     callSid, // The original inbound call sid
  42.     callId, // The id of the call stored on 8base
  43.     from, // The phone number that made the call
  44.     agencyId, // The id of the agency receiving the call
  45.     campaign, // The campaign object related to the agency phone number, if any
  46.   } = event.data;
  47.  
  48.   let users = [];
  49.   let conferences = [];
  50.  
  51.   let promise = twilioClient.conferences.list({ friendlyName: callSid, limit: 1 });
  52.  
  53.   try {
  54.     users = await fetchUserIdsToCall(agencyId, campaign?.id, ctx, { checkPermissions: false });
  55.   } catch (e) {
  56.     console.log('call: distribute-inbound-call Could not fetch users to call:', e.message);
  57.   }
  58.  
  59.   try {
  60.     conferences = await promise;
  61.   } catch (e) {
  62.     console.log('call: distribute-inbound-call Could not fetch conference:', e.message);
  63.  
  64.     return event;
  65.   }
  66.  
  67.   const [conference] = conferences;
  68.  
  69.   console.log('call: distribute-inbound-call users', users);
  70.  
  71.   if (users.length === 0) {
  72.     /**
  73.      * Announce on the conference
  74.      * that there are not agents available
  75.      * an then hangup.
  76.      */
  77.     return event;
  78.   }
  79.  
  80.   console.log('call: distribute-inbound-call conference', conference.sid);
  81.  
  82.   promise = updateInboundPhoneCall(
  83.     { callSid },
  84.     {
  85.       conferenceSid: conference.sid,
  86.     },
  87.     ctx,
  88.     { checkPermissions: false },
  89.   );
  90.  
  91.   const promises = Promise.all(
  92.     users.map(async (user) => {
  93.       const participant = await createParticipant(
  94.         {
  95.           user: user,
  96.           inboundCall: callId,
  97.           isInitialParticipant: true,
  98.         },
  99.         ctx,
  100.         { checkPermissions: false },
  101.       );
  102.  
  103.       return twilioClient.conferences(conference.sid).participants.create({
  104.         beep: true,
  105.         earlyMedia: false,
  106.         from: from,
  107.         to: `client:${user}?${qs.stringify({ id: participant.id })}`,
  108.         statusCallback: `${getBaseUrl(ctx)}/webhook/participant/${participant.id}/status`,
  109.         statusCallbackMethod: 'POST',
  110.         statusCallbackEvent: ['ringing', 'answered', 'completed'],
  111.       });
  112.     }),
  113.   );
  114.  
  115.   try {
  116.     let awaitedPromises = await promises;
  117.     console.log('call: distribute-inbound-call awaitedPromises', JSON.stringify(awaitedPromises));
  118.   } catch (e) {
  119.     console.log('call: distribute-inbound-call Could not dispatch all calls:', e.message);
  120.   }
  121.  
  122.   try {
  123.     let awaitedPromise = await promise;
  124.     console.log('call: distribute-inbound-call awaitedPromise', JSON.stringify(awaitedPromise));
  125.   } catch (e) {
  126.     console.log('call: distribute-inbound-call Could not set conference id on call:', e.message);
  127.   }
  128.  
  129.   return event;
  130. }
  131.  
Advertisement
Add Comment
Please, Sign In to add comment