Class: Twilio::Rails::Phone::CreateOperation

Inherits:
ApplicationOperation show all
Defined in:
app/operations/twilio/rails/phone/create_operation.rb

Instance Method Summary collapse

Instance Method Details

#executeObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/operations/twilio/rails/phone/create_operation.rb', line 9

def execute
  phone_call = ::Twilio::Rails.config.phone_call_class.new(
    sid: params["CallSid"],
    direction: params["direction"].presence || "inbound",
    call_status: params["CallStatus"],
    tree_name: tree.name,
    number: params["Called"].presence || params["To"].presence,
    from_number: params["Caller"].presence || params["From"].presence,
    from_city: params["CallerCity"].presence || params["FromCity"].presence,
    from_province: params["CallerState"].presence || params["FromState"].presence,
    from_country: params["CallerCountry"].presence || params["FromCountry"].presence,
  )

  phone_caller = Twilio::Rails::FindOrCreatePhoneCallerOperation.call(phone_number: phone_call.from_number)

  if !phone_caller
    error_message = if !Twilio::Rails::Formatter.valid_north_american_phone_number?(phone_call.from_number)
      "The phone number is invalid."
    else
      "The phone caller could not be persisted or retrieved."
    end

    raise Twilio::Rails::Phone::Error, "Failed to handle incoming Twilio phone call. #{ error_message } phone_number=#{ phone_call.from_number } call_sid=#{ params["CallSid"] }"
  end

  phone_call.phone_caller = phone_caller
  phone_call.save!

  phone_call
rescue => e
  Twilio::Rails.notify_exception(e,
    message: "Failed to handle incoming Twilio phone call.",
    context: { params: params, tree: tree },
    exception_binding: binding
  )
  raise
end