I am trying to integrate my Rails app with a 3rd party API (Twilio). The user initiates a call by pressing a button on their browser, they follow the call logic on the telephone, and then when the call terminates, I want the browser to be redirected to a different page.
However, I am having difficulty dealing with responses for the two different user agents (the browser and the Twilio API).
The call is initiated using the following controller action (and as the request comes from the browser, the render action works without a problem):
def set_up
@client = Twilio::REST::Client.new ACCOUNT_SID, AUTH_TOKEN
data = {
from: FROM,
to: params[:number],
url: candidate_begin_url(@candidate),
method: 'get',
timeout: 10
}
@client.account.calls.create data
render 'candidates/interview_in_progress'
end
At the end of the call, once the user is ready to terminate, the Twilio API makes a GET request to the following controller. The intention is for two things to happen:
- The controller should respond to the Twilio API with XML instructions to
hang up the call -
The controller should redirect the user’s browser to a
new urldef finalize_call response = Twilio::TwiML::Response.new do |r| r.Hangup end.text respond_to do |format| format.html { redirect_to candidate_complete_voice_interview_path(@candidate) } format.xml { render xml: response } end end
However it seems that because the request comes from the Twilio API user agent, I am unable to perform any actions with the browser. So while in the log I see the new page has been rendered with status 200 OK, there is no change in the browser.
My question is, how can I instruct the browser to redirect following a request from a different user agent, in this case the API?
When a user visits your site, your site creates a session for that user. When Twilio sends a request directly to your site, a separate session is created. These two sessions are completely independent. So when Twilio sends a GET request to your server, your server responds by rendering the requested page and sending it back to Twilio.
Your server cannot send push updates, it has to receive a request and send a response. So any website you see that appears to auto update is generally doing some sort of javascript polling, where the browser sends a periodic request (ajax) to the server to check if there are any changes.
Before diving down that path though, I would ask if you can’t just have some sort of notice on your site that says “When you finish your call, please click here”. Otherwise you will have to store the response from Twilio in the db (or somewhere), and then have the user’s browser send an ajax request ever x seconds to see if a response has arrived.