michaelrkn / vpb-preview-dialer

0 stars 0 forks source link

Failed/busy calls #8

Open djake opened 4 years ago

michaelrkn commented 4 years ago

twilio.js doesn't provide the disconnect reason when a call is terminated. Unless a call is answered, we currently treat all disconnections as "Not home", but this mischaracterizes failed and busy calls.

Twilio support has indicated that twilio.js may in the future provide a way to get the disconnect reason. Until then, they provided this suggestion for using Twilio Sync to send the disconnect reason to the frontend:

First, set up a Function to receive statusCallbacks. Inside the Function, I'd create/update a map resource in Sync, using the Call SID as a key: https://www.twilio.com/docs/sync/api/map-item-resource#create-a-mapitem-resource. From the client end, you can subscribe to updates on a map: https://www.twilio.com/docs/sync/maps#subscribing-to-a-map.

exports.handler = function(context, event, callback) {
  var mapSid = "...." //this should be a hardcoded map sid
  var serviceSid = "...." //this should be a hardcoded service sid
  client = context.getTwilioClient();

  client.sync.services(serviceSid)
    .syncMaps(mapSid)
    .syncMapItems(event.CallSid)
    .fetch()
    .then(map_item => {
      if (map_item) { //there was an item with that call sid as the key
        client.sync.services(serviceSid)
          .syncMaps(mapSid)
          .syncMapItems(event.CallSid)
          .update({
            data: {
              status: event.CallStatus
            }
          })
          .then(callback); //this just ends the Function
      } else { //there wasn't an existing item, so we make one
        client.sync.services(serviceSid)
          .syncMaps(mapSid)
          .syncMapItems
          .create({
            key: event.CallSid,
            data: {
              status: event.CallStatus
            }
          })
          .then(callback);
      }
    });
};