Browser Calls with Java and Spark

This Spark web application shows how you can use Twilio Client to make browser-to-phone and browser-to-browser calls.

Browser Calls home
page

This application powers the support site for the Birchwood Bicycle Polo Co., which sells equipment to those who play "the sport of kings." It has three main features:

  • Unsatisfied customers can submit support tickets with their phone number and their problem.
  • Support agents can call customers' phones from their browser to follow up on support tickets.
  • Customers can also use their browser to speak with support agents live when available.

In this tutorial, we'll point out the key bits of code that make this application work. Check out the project README on GitHub to see how to run the code yourself.

Learn how Zendesk uses Twilio Client to make phone support available in 40+ countries.

Submit a support ticket

The home page of our app displays a form for customers to submit support tickets. We use Mustache Template Engine to power the page, and this controller to create the ticket.

Loading Code Samples...
Language
package com.twilio.browsercalls.controllers;

import com.twilio.browsercalls.lib.FieldsValidator;
import com.twilio.browsercalls.models.Ticket;
import com.twilio.browsercalls.models.TicketService;
import spark.ModelAndView;
import spark.Request;
import spark.TemplateViewRoute;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TicketController {
  TicketService ticketService;

  public TicketController(TicketService ticketService) {
    this.ticketService = ticketService;
  }

  public TemplateViewRoute create = (request, response) -> {
    return new ModelAndView(createTicket(request), "home.mustache");
  };

  public Map createTicket(Request request) {
    FieldsValidator validator =
        new FieldsValidator(new String[] {"name", "phone_number", "description"});

    Map map = new HashMap();

    /** Validates that the required parameters are sent on the request. */
    if (validator.valid(request)) {
      String name = request.queryParams("name");
      String phoneNumber = request.queryParams("phone_number");
      String description = request.queryParams("description");
      Date date = new Date();

      Ticket ticket = new Ticket(name, phoneNumber, description, date);
      ticketService.create(ticket);
      map.put("message", true);
      map.put("notice", "Ticket created successfully");

      return map;
    } else {
      map.put("error", true);
      map.put("errors", validator.errors());
      return map;
    }
  }
}
src/main/java/com/twilio/browsercalls/controllers/TicketController.java
Create a Ticket

src/main/java/com/twilio/browsercalls/controllers/TicketController.java

Let's look at the model.

The Support Ticket Model

A support ticket has just a few fields - a name for the end user, a description of the trouble they're having, and a phone number we can use to call them back.

Loading Code Samples...
Language
package com.twilio.browsercalls.models;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "tickets")
public class Ticket {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long id;

  @Column(name = "name")
  private String name;

  @Column(name = "phone_number")
  private String phoneNumber;

  @Column(name = "description")
  private String description;

  @Column(name = "date")
  private Date date;

  public Ticket() {}

  public Ticket(String name, String phoneNumber, String description, Date date) {
    this.name = name;
    this.phoneNumber = phoneNumber;
    this.description = description;
    this.date = date;
  }

  Long getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPhoneNumber() {
    return phoneNumber;
  }

  public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }
}
src/main/java/com/twilio/browsercalls/models/Ticket.java
Support Ticket Model

src/main/java/com/twilio/browsercalls/models/Ticket.java

Now we can create a ticket. Next up, let's work on the dashboard for the support agent.

The support dashboard

When a support agent visits /dashboard, they see all the support tickets which have been submitted.

Browser Calls support dashboard

Each ticket also has a "Call Customer" button which invokes a JavaScript function we wrote named callCustomer(). That function kicks off a Twilio Client call to the phone number passed as its sole parameter.

Loading Code Samples...
Language
{{! index.mustache }}
{{<base}}
{{$header}}
{{<header}}
{{$title}}Support Dashboard{{/title}}
{{/header}}
{{/header}}

{{$content}}
<div class="container">

    <h2>Support Tickets</h2>

    <p class="lead">
        This is the list of most recent support tickets. Click the "Call customer" button to start a
        phone call from your browser.
    </p>

    <div class="row">

        <div class="col-md-4 col-md-push-8">
            <div class="panel panel-primary client-controls">
                <div class="panel-heading">
                    <h3 class="panel-title">Make a call</h3>
                </div>
                <div class="panel-body">
                    <p><strong>Status</strong></p>

                    <div class="well well-sm" id="call-status">
                        Connecting to Twilio...
                    </div>

                    <button class="btn btn-lg btn-success answer-button" disabled>Answer call
                    </button>
                    <button class="btn btn-lg btn-danger hangup-button" disabled onclick="hangUp()">
                        Hang up
                    </button>
                </div>
            </div>
        </div>

        <div class="col-md-8 col-md-pull-4">
            {{#tickets}}
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Ticket {{id}}
                            <small class="pull-right">{{date}}</small>
                        </h3>
                    </div>

                    <div class="panel-body">

                        <div class="pull-right">
                            <button onclick="callCustomer('{{phoneNumber}}')" type="button"
                                    class="btn btn-primary btn-lg call-customer-button">
                                <span class="glyphicon glyphicon-earphone"
                                      aria-hidden="true"></span>
                                Call customer
                            </button>
                        </div>

                        <p><strong>Name:</strong> {{name}}</p>

                        <p><strong>Phone number:</strong> {{phoneNumber}}</p>

                        <p><strong>Description:</strong></p>
                        {{description}}

                    </div>
                </div>
            {{/tickets}}
            {{^tickets}}
                <div class="panel panel-default">
                    <div class="well">
                        There are no support tickets available.
                    </div>
                </div>
            {{/tickets}}
        </div>

    </div>
</div>
{{/content}}
{{/base}}
src/main/resources/templates/dashboard.mustache
Support Agent's Dashboard

src/main/resources/templates/dashboard.mustache

Great, now we have an interface good enough for our support agents. Next up, in order to let our agents make calls to their customers through the browser, we need to provide them a capability token.

Generate a capability token

We use the Twilio Java helper library to generate and configure our capability tokens. To allow our support agents to call the phone numbers on our tickets, we use an OutgoingClientScope.

That method requires an identifier for a TwiML Application. Twilio will send a POST request to our backend every time a user makes a Twilio Client call — the TwiML Application tells Twilio which URL to send that request to.

Loading Code Samples...
Language
package com.twilio.browsercalls.lib;

import java.util.List;

import com.google.common.collect.Lists;
import com.twilio.browsercalls.exceptions.UndefinedEnvironmentVariableException;
import com.twilio.jwt.client.ClientCapability;
import com.twilio.jwt.client.IncomingClientScope;
import com.twilio.jwt.client.OutgoingClientScope;
import com.twilio.jwt.client.Scope;

/**
 * Class that generates a Twilio capability token based on the page that is requesting it.
 */
public class CapabilityTokenGenerator {
  private ClientCapability.Builder capabilityBuilder;
  private AppSetup appSetup;
  private String role;

  public CapabilityTokenGenerator(String role, ClientCapability.Builder capabilityBuilder,
      AppSetup setup) {
    this.role = role;
    appSetup = setup;
    this.capabilityBuilder = capabilityBuilder;
  }

  public CapabilityTokenGenerator(String role) {
    this.role = role;
    appSetup = new AppSetup();
    try {
      /**
       * To find TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN visit https://www.twilio.com/console
       */
      this.capabilityBuilder =
          new ClientCapability.Builder(appSetup.getAccountSid(), appSetup.getAuthToken());
    } catch (UndefinedEnvironmentVariableException e) {
      e.getLocalizedMessage();
    }
  }

  public String generate() {
    /**
     * Sets the role depending on the page that requests que token. If the token is requested from
     * the /dashboard page, the role will be support_agent.
     */
    String appSid = null;
    try {
      appSid = appSetup.getApplicationSid();
    } catch (UndefinedEnvironmentVariableException e) {
      System.out.println(e.getLocalizedMessage());
    }
    OutgoingClientScope outgoingScope = new OutgoingClientScope.Builder(appSid).build();
    IncomingClientScope incomingScope = new IncomingClientScope(role);

    List<Scope> scopes = Lists.newArrayList(outgoingScope, incomingScope);

    String token = capabilityBuilder.scopes(scopes).build().toJwt();

    return token;
  }
}
src/main/java/com/twilio/browsercalls/lib/CapabilityTokenGenerator.java
Generate a capability token

src/main/java/com/twilio/browsercalls/lib/CapabilityTokenGenerator.java

Once we are equipped with our Capability Token, the next step is to set up the Twilio Device Client in the browser.

Set up a Twilio Device Client

To use the Twilio Device Client in a web browser we use the twilio.js library.

We start by retrieving a capability token from the view we defined in the previous step with a POST request through AJAX. Then we enable the Twilio Device Client for this page by passing our token to Twilio.Device.setup().

After that the Twilio.Device.ready() callback will let us know when the browser is ready to make and receive calls.

Loading Code Samples...
Language
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
src/main/resources/public/js/browser-calls.js
Set up a Twilio Device

src/main/resources/public/js/browser-calls.js

Now that we have almost everything in place, it's time to see the core of this tutorial. Let's look at how we can let our agents start a call from their browsers.

Calling a Customer (browser-to-phone)

When our support agents click on the Call Customer button on a support ticket, the function highlighted on the code snippet will initiate the call.

We use Twilio.Device.connect() to begin a new outgoing call. Our backend will tell Twilio how to handle this call, so we include a phoneNumber parameter that we'll use on our call view.

Loading Code Samples...
Language
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
src/main/resources/public/js/browser-calls.js
Call a Customer

src/main/resources/public/js/browser-calls.js

Great! Now our agents are able to make calls to their customers. Next up, let's look at how to connect that call to a phone number.

Connect the call to a phone number

Whenever one of our users makes a call, Twilio will send a POST request to the URL we set on our TwiML Application - in this case, /call/connect.

We use TwiML to respond to the request and tell Twilio how to handle the call. Twilio will pass along the phoneNumber parameter from the previous step in its request, which we will then Dial in our TwiML.

Loading Code Samples...
Language
package com.twilio.browsercalls.controllers;

import com.twilio.browsercalls.exceptions.UndefinedEnvironmentVariableException;
import com.twilio.browsercalls.lib.AppSetup;
import com.twilio.twiml.*;
import com.twilio.twiml.Number;

import spark.Request;
import spark.Route;

@SuppressWarnings({"rawtypes", "unchecked"})
public class CallController {
  AppSetup appSetup;
  public Route connect = (request, response) -> {
    response.type("application/xml");

    return getXMLResponse(request);
  };

  public CallController() {
    this.appSetup = new AppSetup();
  }

  public CallController(AppSetup appSetup) {
    this.appSetup = appSetup;
  }

  public String getXMLResponse(Request request) {
    String twilioPhoneNumber = null;
    try {
      twilioPhoneNumber = appSetup.getTwilioPhoneNumber();
    } catch (UndefinedEnvironmentVariableException e) {
      return e.getLocalizedMessage();
    }
    String phoneNumber = request.queryParams("phoneNumber");

    Dial.Builder dialBuilder = new Dial.Builder();

    /**
     * If the phoneNumber parameter is sent on the request, it means you are calling a customer. If
     * not, you will make a call to the support agent
     */
    if (phoneNumber != null) {
      Number number = new Number.Builder(phoneNumber).build();
      dialBuilder = dialBuilder.number(number).callerId(twilioPhoneNumber);
    } else {
      Client client = new Client.Builder("support_agent").build();
      dialBuilder = dialBuilder.client(client);
    }

    Dial dial = dialBuilder.build();
    VoiceResponse twimlResponse = new VoiceResponse.Builder().dial(dial).build();

    try {
      return twimlResponse.toXml();
    } catch (TwiMLException e) {
      return e.getLocalizedMessage();
    }
  }
}
src/main/java/com/twilio/browsercalls/controllers/CallController.java
Connect the call to a phone number

src/main/java/com/twilio/browsercalls/controllers/CallController.java

After our call view responds, Twilio completes the connection between our support agent's browser and the customer's phone. Let's go back to the browser and see how this is handled.

The call is live

We use the Twilio.Device.connect() callback to update some UI elements to notify our users that they are in a call. This function receives a Connection object, which offers some additional details about the call.

Loading Code Samples...
Language
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
src/main/resources/public/js/browser-calls.js
Indicate a live call

src/main/resources/public/js/browser-calls.js

And that's all for our browser-to-phone example. Next up, we will go even further and show a browser-to-browser example.

Call a support agent (browser-to-browser)

Support tickets are useful, but sometimes a customer needs help right now. With just a little more work we let customers speak with a support agent live via a browser-to-browser call.

Browser Calls call support

When a customer clicks the Call support button on the home page we again use Twilio.Device.connect() to initiate the call. This time we don't pass any additional parameters — our backend will route this call to our support agent.

Loading Code Samples...
Language
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
src/main/resources/public/js/browser-calls.js
Call a Support Agent

src/main/resources/public/js/browser-calls.js

Setting up the browser-to-browser call was rather simple right? Now let's look at how our backend will route this call to our support agent.

Connect the call to the support agent's client

To allow our support agents to accept incoming calls we use an IncomingClientScope when generating their capability token, passing support_agent as the client's name.

When Twilio sends a POST request to our /call/connect endpoint, we can connect the call to our support agent by responding with a <Client> TwiML noun and the support_agent name.

Loading Code Samples...
Language
package com.twilio.browsercalls.controllers;

import com.twilio.browsercalls.lib.CapabilityTokenGenerator;
import org.json.simple.JSONObject;
import spark.Route;
import spark.Request;

public class TokenController {
  public Route getToken = (request, response) -> {
    response.type("application/json");

    return getTokenAsJSON(request);
  };

  public String getTokenAsJSON(Request request) {
    /**
     * Generates a token with specific capabilities depending on the page that is requesting
     * the page.
     */
    String page = request.queryParams("page");
    String role = page.equals("/dashboard") ? "support_agent" : "customer";
    CapabilityTokenGenerator generator = new CapabilityTokenGenerator(role);
    String token = generator.generate();

    JSONObject obj = new JSONObject();
    obj.put("token", token);

    return obj.toJSONString();
  }
}
What does this thing do?
Connect Incoming Calls

What does this thing do?

That's how we prepare everything for accepting incoming calls. Now we should go back in the browser and see how to handle the connection this time.

Answer the call

When our support agent's client receives an incoming call, it will trigger the function we defined on the Twilio.Device.incoming() callback.

The incoming connection will be in a pending state until we invoke its .accept() method, which we do in a function bound to the Answer Call button.

We also set a .accept() callback to update the UI once the call is live.

Loading Code Samples...
Language
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
src/main/resources/public/js/browser-calls.js
Answer the call

src/main/resources/public/js/browser-calls.js

Great! Now we know how to work on both cases: browser-to-phone and browser-to-browser calls! Next up, we will see what happens when they decide to hang up the call.

Hang up the Call

In order to finish a call we invoke Twilio.Device.disconnectAll(), which we wired to the Hang up button in our UI.

We also pass a callback function to Twilio.Device.disconnect() above, to reset some UI elements.

Loading Code Samples...
Language
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
src/main/resources/public/js/browser-calls.js
Hang up the Call

src/main/resources/public/js/browser-calls.js

That's it! Our Spark application now powers browser-to-phone and browser-to-browser calls using Twilio Client.

Where to next?

If you're a Java developer working with Twilio, you might also enjoy these tutorials:

Appointment Reminders

Schedule appointment reminders to be sent via sms

SMS and MMS Notifications

Alert all administrators via SMS when a server outage occurs.

Did this help?

Thanks for checking this tutorial out! If you have any feedback to share with us please contact us on Twitter, we'd love to hear it.

Mario Celi
Jose Oliveros
David Prothero
Andrew Baker
Agustin Camino

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
package com.twilio.browsercalls.controllers;

import com.twilio.browsercalls.lib.FieldsValidator;
import com.twilio.browsercalls.models.Ticket;
import com.twilio.browsercalls.models.TicketService;
import spark.ModelAndView;
import spark.Request;
import spark.TemplateViewRoute;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TicketController {
  TicketService ticketService;

  public TicketController(TicketService ticketService) {
    this.ticketService = ticketService;
  }

  public TemplateViewRoute create = (request, response) -> {
    return new ModelAndView(createTicket(request), "home.mustache");
  };

  public Map createTicket(Request request) {
    FieldsValidator validator =
        new FieldsValidator(new String[] {"name", "phone_number", "description"});

    Map map = new HashMap();

    /** Validates that the required parameters are sent on the request. */
    if (validator.valid(request)) {
      String name = request.queryParams("name");
      String phoneNumber = request.queryParams("phone_number");
      String description = request.queryParams("description");
      Date date = new Date();

      Ticket ticket = new Ticket(name, phoneNumber, description, date);
      ticketService.create(ticket);
      map.put("message", true);
      map.put("notice", "Ticket created successfully");

      return map;
    } else {
      map.put("error", true);
      map.put("errors", validator.errors());
      return map;
    }
  }
}
package com.twilio.browsercalls.models;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "tickets")
public class Ticket {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long id;

  @Column(name = "name")
  private String name;

  @Column(name = "phone_number")
  private String phoneNumber;

  @Column(name = "description")
  private String description;

  @Column(name = "date")
  private Date date;

  public Ticket() {}

  public Ticket(String name, String phoneNumber, String description, Date date) {
    this.name = name;
    this.phoneNumber = phoneNumber;
    this.description = description;
    this.date = date;
  }

  Long getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPhoneNumber() {
    return phoneNumber;
  }

  public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }
}
{{! index.mustache }}
{{<base}}
{{$header}}
{{<header}}
{{$title}}Support Dashboard{{/title}}
{{/header}}
{{/header}}

{{$content}}
<div class="container">

    <h2>Support Tickets</h2>

    <p class="lead">
        This is the list of most recent support tickets. Click the "Call customer" button to start a
        phone call from your browser.
    </p>

    <div class="row">

        <div class="col-md-4 col-md-push-8">
            <div class="panel panel-primary client-controls">
                <div class="panel-heading">
                    <h3 class="panel-title">Make a call</h3>
                </div>
                <div class="panel-body">
                    <p><strong>Status</strong></p>

                    <div class="well well-sm" id="call-status">
                        Connecting to Twilio...
                    </div>

                    <button class="btn btn-lg btn-success answer-button" disabled>Answer call
                    </button>
                    <button class="btn btn-lg btn-danger hangup-button" disabled onclick="hangUp()">
                        Hang up
                    </button>
                </div>
            </div>
        </div>

        <div class="col-md-8 col-md-pull-4">
            {{#tickets}}
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Ticket {{id}}
                            <small class="pull-right">{{date}}</small>
                        </h3>
                    </div>

                    <div class="panel-body">

                        <div class="pull-right">
                            <button onclick="callCustomer('{{phoneNumber}}')" type="button"
                                    class="btn btn-primary btn-lg call-customer-button">
                                <span class="glyphicon glyphicon-earphone"
                                      aria-hidden="true"></span>
                                Call customer
                            </button>
                        </div>

                        <p><strong>Name:</strong> {{name}}</p>

                        <p><strong>Phone number:</strong> {{phoneNumber}}</p>

                        <p><strong>Description:</strong></p>
                        {{description}}

                    </div>
                </div>
            {{/tickets}}
            {{^tickets}}
                <div class="panel panel-default">
                    <div class="well">
                        There are no support tickets available.
                    </div>
                </div>
            {{/tickets}}
        </div>

    </div>
</div>
{{/content}}
{{/base}}
package com.twilio.browsercalls.lib;

import java.util.List;

import com.google.common.collect.Lists;
import com.twilio.browsercalls.exceptions.UndefinedEnvironmentVariableException;
import com.twilio.jwt.client.ClientCapability;
import com.twilio.jwt.client.IncomingClientScope;
import com.twilio.jwt.client.OutgoingClientScope;
import com.twilio.jwt.client.Scope;

/**
 * Class that generates a Twilio capability token based on the page that is requesting it.
 */
public class CapabilityTokenGenerator {
  private ClientCapability.Builder capabilityBuilder;
  private AppSetup appSetup;
  private String role;

  public CapabilityTokenGenerator(String role, ClientCapability.Builder capabilityBuilder,
      AppSetup setup) {
    this.role = role;
    appSetup = setup;
    this.capabilityBuilder = capabilityBuilder;
  }

  public CapabilityTokenGenerator(String role) {
    this.role = role;
    appSetup = new AppSetup();
    try {
      /**
       * To find TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN visit https://www.twilio.com/console
       */
      this.capabilityBuilder =
          new ClientCapability.Builder(appSetup.getAccountSid(), appSetup.getAuthToken());
    } catch (UndefinedEnvironmentVariableException e) {
      e.getLocalizedMessage();
    }
  }

  public String generate() {
    /**
     * Sets the role depending on the page that requests que token. If the token is requested from
     * the /dashboard page, the role will be support_agent.
     */
    String appSid = null;
    try {
      appSid = appSetup.getApplicationSid();
    } catch (UndefinedEnvironmentVariableException e) {
      System.out.println(e.getLocalizedMessage());
    }
    OutgoingClientScope outgoingScope = new OutgoingClientScope.Builder(appSid).build();
    IncomingClientScope incomingScope = new IncomingClientScope(role);

    List<Scope> scopes = Lists.newArrayList(outgoingScope, incomingScope);

    String token = capabilityBuilder.scopes(scopes).build().toJwt();

    return token;
  }
}
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
package com.twilio.browsercalls.controllers;

import com.twilio.browsercalls.exceptions.UndefinedEnvironmentVariableException;
import com.twilio.browsercalls.lib.AppSetup;
import com.twilio.twiml.*;
import com.twilio.twiml.Number;

import spark.Request;
import spark.Route;

@SuppressWarnings({"rawtypes", "unchecked"})
public class CallController {
  AppSetup appSetup;
  public Route connect = (request, response) -> {
    response.type("application/xml");

    return getXMLResponse(request);
  };

  public CallController() {
    this.appSetup = new AppSetup();
  }

  public CallController(AppSetup appSetup) {
    this.appSetup = appSetup;
  }

  public String getXMLResponse(Request request) {
    String twilioPhoneNumber = null;
    try {
      twilioPhoneNumber = appSetup.getTwilioPhoneNumber();
    } catch (UndefinedEnvironmentVariableException e) {
      return e.getLocalizedMessage();
    }
    String phoneNumber = request.queryParams("phoneNumber");

    Dial.Builder dialBuilder = new Dial.Builder();

    /**
     * If the phoneNumber parameter is sent on the request, it means you are calling a customer. If
     * not, you will make a call to the support agent
     */
    if (phoneNumber != null) {
      Number number = new Number.Builder(phoneNumber).build();
      dialBuilder = dialBuilder.number(number).callerId(twilioPhoneNumber);
    } else {
      Client client = new Client.Builder("support_agent").build();
      dialBuilder = dialBuilder.client(client);
    }

    Dial dial = dialBuilder.build();
    VoiceResponse twimlResponse = new VoiceResponse.Builder().dial(dial).build();

    try {
      return twimlResponse.toXml();
    } catch (TwiMLException e) {
      return e.getLocalizedMessage();
    }
  }
}
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
package com.twilio.browsercalls.controllers;

import com.twilio.browsercalls.lib.CapabilityTokenGenerator;
import org.json.simple.JSONObject;
import spark.Route;
import spark.Request;

public class TokenController {
  public Route getToken = (request, response) -> {
    response.type("application/json");

    return getTokenAsJSON(request);
  };

  public String getTokenAsJSON(Request request) {
    /**
     * Generates a token with specific capabilities depending on the page that is requesting
     * the page.
     */
    String page = request.queryParams("page");
    String role = page.equals("/dashboard") ? "support_agent" : "customer";
    CapabilityTokenGenerator generator = new CapabilityTokenGenerator(role);
    String token = generator.generate();

    JSONObject obj = new JSONObject();
    obj.put("token", token);

    return obj.toJSONString();
  }
}
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}
/**
 * Twilio Client configuration for the browser-calls-rails
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus;
var answerButton;
var callSupportButton;
var hangUpButton;
var callCustomerButtons;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
  callStatus.text(status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
  callStatus = $("#call-status");
  answerButton = $(".answer-button");
  callSupportButton = $(".call-support-button");
  hangUpButton = $(".hangup-button");
  callCustomerButtons = $(".call-customer-button");

  $.post("/token/generate", {page: window.location.pathname}, function(data) {
    // Set up the Twilio Client Device with the token
    Twilio.Device.setup(data.token);
  });
});

/* Callback to let us know Twilio Client is ready */
Twilio.Device.ready(function (device) {
  updateCallStatus("Ready");
});

/* Report any errors to the call status display */
Twilio.Device.error(function (error) {
  updateCallStatus("ERROR: " + error.message);
});

/* Callback for when Twilio Client initiates a new connection */
Twilio.Device.connect(function (connection) {
  // Enable the hang up button and disable the call buttons
  hangUpButton.prop("disabled", false);
  callCustomerButtons.prop("disabled", true);
  callSupportButton.prop("disabled", true);
  answerButton.prop("disabled", true);

  // If phoneNumber is part of the connection, this is a call from a
  // support agent to a customer's phone
  if ("phoneNumber" in connection.message) {
    updateCallStatus("In call with " + connection.message.phoneNumber);
  } else {
    // This is a call from a website user to a support agent
    updateCallStatus("In call with support");
  }
});

/* Callback for when a call ends */
Twilio.Device.disconnect(function(connection) {
  // Disable the hangup button and enable the call buttons
  hangUpButton.prop("disabled", true);
  callCustomerButtons.prop("disabled", false);
  callSupportButton.prop("disabled", false);

  updateCallStatus("Ready");
});

/* Callback for when Twilio Client receives a new incoming call */
Twilio.Device.incoming(function(connection) {
  updateCallStatus("Incoming support call");

  // Set a callback to be executed when the connection is accepted
  connection.accept(function() {
    updateCallStatus("In call with customer");
  });

  // Set a callback on the answer button and enable it
  answerButton.click(function() {
    connection.accept();
  });
  answerButton.prop("disabled", false);
});

/* Call a customer from a support ticket */
function callCustomer(phoneNumber) {
  updateCallStatus("Calling " + phoneNumber + "...");

  Twilio.Device.connect({
    phoneNumber: phoneNumber
  });
}

/* Call the support_agent from the home page */
function callSupport() {
  updateCallStatus("Calling support...");

  // Our backend will assume that no params means a call to support_agent
  Twilio.Device.connect();
}

/* End a call */
function hangUp() {
  Twilio.Device.disconnectAll();
}