3 About Using the WebRTC Session Controller JavaScript API

This chapter presents a general overview of the Oracle Communications WebRTC Session Controller JavaScript SDK for the use of web application developers.

Note:

This document assumes that you have experience with developing applications using HTML5 features designed for WebRTC-enabled browsers. Its focus is restricted to how you can use the WebRTC Session Controller JavaScript APIs to manage real-time communication featuring media stream and data transfers.

This chapter covers the following topics:

For information about:

Note:

Creating and implementing the design of the application page, the appearance of its user interface and display elements are beyond the scope of this document.

For more information about the individual WebRTC Session Controller JavaScript API classes, see Oracle Communications WebRTC Session Controller JavaScript API Reference.

About the wsc Namespace

The wsc namespace exposes the WebRTC Session Controller JavaScript SDK. You can access its objects and methods in your applications.

For more information about the wsc namespace, see Oracle Communications WebRTC Session Controller JavaScript API Reference.

About Using the WebRTC Session Controller JavaScript API Library

The WebRTC Session Controller JavaScript SDK can be used to provide real-time communication-related functionality in your applications. For example, you can support audio calls, video calls, data transfers, and message notifications.

About the API to Use for General Tasks

The following WebRTC Session Controller JavaScript APIs are used for general tasks in your application.

In addition, you can verify the media streaming capabilities of the browser. See "Verifying Browser Capabilities".

About the API Used for Call-Related Tasks

The following WebRTC Session Controller JavaScript API classes are used to perform call-related tasks in your application.

About the API Used for Message-Related Tasks

The WebRTC Session Controller JavaScript API classes used to perform message and notification-related tasks are described in "Setting Up Message Alert Notifications".

About Extending WebRTC Session Controller JavaScript API

You can extend your applications by extending WebRTC Session Controller JavaScript API classes. See "Extending Your Applications Using WebRTC Session Controller JavaScript API".

Managing Sessions with wsc.Session

Manage the WebSocket connection between your application and WebRTC Session Controller using the wsc.Session class. It represents a persistent association between your application and WebRTC Session Controller Signaling Engine. All the media streams, data transfers, and message alert notifications in your application take place within the scope of wsc.Session.

When an account holder accesses your application on the web page, create an instance of the Session class before you use any of the other WebRTC Session Controller JavaScript API objects.

You provide the following information when you create a session object:

  • The user name.

  • The WebSocket URI.

  • The callback function in your application to call when the session is created.

  • The callback function in your application to call when there is an error in creating the session.

See "Setting Up the Session Object" for more information.

Your application session object is associated with a unique session identifier. If you are creating the session object for the first time, WebRTC Session Controller Signaling Engine assigns the session identifier. You can use this identifier to refresh the session, for example, when the application page reloads. When the session is successfully created, provide the settings to manage the connection. See "About Monitoring Your Application WebSocket Connection".

For information about the various session states and how your application can manage changes in its session state, see "Handling Session State Changes".

At times, your application must maintain session transfers in a device handover. For example, Alice is on a cellphone call to a sales representative. During the call, Alice continues the call on the softphone on the laptop. See "Handling Session Rehydration When the User Moves to Another Device", for more information.

Authenticating Users with wsc.AuthHandler

Authenticate your application users with the wsc.AuthHandler class. This class enables your application to ensure that the user credentials are appropriate and do not disrupt message flow during the life of the session.

For example, based on the action of your user, your application sends a request to a target uniform resource locator (URL). WebRTC Session Controller Signaling Engine forwards the request to the target URL. The Session Initialization Protocol (SIP) proxy or registrar server checks the user credentials. If the user credential information is inadequate, the SIP server does not allow that request to go further in the target environment. It sends back a challenge to WebRTC Session Controller Signaling Engine asking for more credential information.

The challenge can be from a SIP server, Traversal Using Relays around Network Address Translation (TURN) server, or proxy or registrar server. WebRTC Session Controller Signaling Engine forwards the challenge to the WebRTC Session Controller JavaScript SDK. The WebRTC Session Controller JavaScript SDK calls the refresh event of the wsc.AuthHandler object.

Your application can respond to such a challenge by retrieving the user credentials and returning that information as a JSON object. On receiving this JSON object, WebRTC Session Controller Signaling Engine can then send the response from your application to the SIP proxy or registrar server.

When you create an instance of the wsc.AuthHandler class in your application, set up a callback function to handle the AuthHandler.refresh event. In the following example, an application creates an authentication handler called authHandler and assigns a callback function called refreshAuth to its refresh event:

 // Create the session.
 // Here, userName is null. WebRTC Session Controller can determine it 
 // by the cookie of the request.
 wscSession = new wsc.Session(null, webSocketUri, sessionSuccessHandler, sessionErrorHandler);
 // Register a wsc.AuthHandler with the session,
 // which provides customized authentication info, such as username/password.
 var authHandler = new wsc.AuthHandler(wscSession);
 authHandler.refresh = refreshAuth;

The callback function has two parameters, authType and authHeaders. The authType entry indicates the authentication type as one of the following:

  • wsc.AUTHTYPE.TURN: The type of authentication that allows for the client to authenticate with a TURN server. TURN servers facilitate communication between clients residing behind network address translator (NAT) routers or firewalls.

  • wsc.AUTHTYPE.SERVICE: The type of authentication used when a back-end SIP application, such as the Proxy Registrar, requires user authentication.

To obtain the authentication information from the authHeaders, use the value in authType. Return the authentication information as a JSON object, as shown in Example 4-8, "Template for the refreshAuth Function()".

How Your Application Saves Session Information

By default, the WebRTC Session Controller JavaScript API SDK stores your application data in JSON format in the sessionStorage object associated with the browser. It saves all the session information associated with the following objects in your application session:

  • CallPackage

  • Call

  • MessageAlertPackage

  • Subscription

Note:

If you extend any WebRTC Session Controller JavaScript API class object, save the session identifier (sessionID). Use this value when you create the current session after your application page reloads.

Handling Session State Changes

Session state values are constants, such as CLOSED or CONNECTED. Session states are defined in the wsc.SESSIONSTATE enumerator.

Whenever the state of your application session changes, the WebRTC Session Controller JavaScript SDK calls the Session.onSessionStateChange event handler in your application and provides the new state. Set up a callback function in your application session object, and assign that function to the Session.onSessionStateChange event handler in your application.

In the callback function, check the new session state against the defined constants and set up appropriate actions to respond to the new state. For example, a change in the value of wsc.SESSIONSTATE from RECONNECTING to CONNECTED indicates that the attempt to reconnect succeeded and that the application can proceed. Or, if the state changes from RECONNECTING to FAILED, the attempt to reconnect failed. In each case, take appropriate action in the application logic.

For a more information about the wsc.SESSIONSTATE enumerator, see Oracle Communications WebRTC Session Controller JavaScript API Reference.

Debugging Your Application with wsc.LOGLEVEL

Set up the type of records your application must log with the wsc.LOGLEVEL enumerator object. The supported log levels are:

  • DEBUG (0)

  • INFO (1)

  • WARN (2)

  • ERROR (3)

  • OFF (4)

To set up the log level for debugging, pass the required constant to the setLogLevel method at the start of your JavaScript application:

wsc.setLogLevel(wsc.LOGLEVEL.DEBUG);

Alternatively, you can directly input the associated numeric value, in this case, 0, corresponding to the DEBUG log level:

wsc.setLogLevel(0);

See "Sample Setup of Global Variables and WebSocket URI".

Managing Calls with wsc.CallPackage

Use the wsc.CallPackage class to manage audio communication, video communication, and data transfers in calls. The WebRTC Session Controller JavaScript SDK handles the messaging and call flow for all calls created through the wsc.CallPackage object for an application session.

In the following example code, an application creates an instance of wsc.CallPackage named callPackage for wscSession, the application session with WebRTC Session Controller Signaling Engine.

var callPackage;
...
callPackage = new wsc.CallPackage(wscSession);

After creating an instance of the CallPackage class in your application, assign a callback function to handle each of the following events:

  • An incoming call, using the onIncomingCall event handler.

    In this callback function, implement the logic to process the incoming call. Filter the call to reject blacklisted numbers or respond when the callee accepts or declines the call. For information about how the default CallPackage class can be used in your applications, see "Setting Up Audio Calls in Your Applications".

  • A reconnected call, using the onResurrect event handler.

    In this callback function, implement the logic to handle the call that was dropped momentarily. See "Reconnecting Dropped Calls" for more information.

To create outgoing calls, use the CallPackage object. See "Managing a Call with wsc.Call".

See "Extending and Overriding WebRTC Session Controller JavaScript API Object Methods" for more information about extending the Call and CallPackage API classes.

Managing a Call with wsc.Call

The wsc.Call object represents a single call and is used within a call package. Manage all audio, video streams, or data transfers associated with a single call session with wsc.Call.

Set up the Call object in your application in the following ways:

  • For the caller, create the call object using the CallPackage.createCall method and provide the call configuration.

  • When your application accepts an incoming call, use the incoming call object and the remote call configuration for the resulting call session. The WebRTC Session Controller JavaScript SDK calls the CallPackage.onIncomingCall event handler and provides the incoming call object and its call configuration, as shown in Example 4-13, "Sample onIncomingCall Function".

Manage changes in the state of the call and its associated audio, media, and data channel with the event handlers of the wsc.Call class. Implement the appropriate logic in the callback function you assign for each event. For:

Specifying the Media Stream for Calls in the CallConfig Object

Specify the audio, video, and data channel capability for calls made from your application, with the wsc.CallConfig class.

When you create the wsc.CallConfig object, set up the direction of the audio and video elements in the local media stream. To specify the direction of the local media stream, use the wsc.MEDIADIRECTION enumerator values:

  • wsc.MEDIADIRECTION.SENDRECV which indicates that the local media stream can send and receive the media stream.

  • wsc.MEDIADIRECTION.SENDONLY which indicates that the local media stream can send the media stream.

  • wsc.MEDIADIRECTION.RECVONLY which indicates that the local media stream can receive the media stream.

  • wsc.MEDIADIRECTION.NONE which indicates that media is not supported.

In the following example, an application sets up the local media stream to send and receive audio calls only:

var audioMediaDirection = wsc.MEDIADIRECTION.SENDRECV;
var videoMediaDirection = wsc.MEDIADIRECTION.NONE;

See "Verifying Browser Capabilities" for information about how to verify the browser support for media streams.

Defining Data Transfers with dataChannelConfig Parameter

Set up the configuration for the data transfers in the dataChannelConfig parameter with key-value pairs in JSON format. Input the settings for the media stream and data transfers when you create the call configuration object in your application.

The dataChannelConfig parameter is an array of JavaScript Object Notation (JSON) objects in the format:

{"label":"DataLabel", "ordered": true }

The dataChannelConfig parameter supports the following keys:

  • label

    The key is required. It represents a label that can be used to distinguish this RTCDataChannel object from other RTCDataChannel objects.

  • ordered

    Optional key. By default, initialized to true, to indicate that the RTCDataChannel is ordered.

  • maxPacketLifeTime

    Optional key. The length of the time window (in milliseconds) during which transmissions and retransmissions could occur in unreliable mode. By default, initialized to null.

  • maxRetransmits

    Optional key. The maximum number of retransmissions that are attempted in unreliable mode. By default, initialized to null.

  • protocol

    Optional key. The name of the sub-protocol used with this RTCDataChannel, if any. By default, initialized to an empty string "".

  • negotiated

    Optional key. By default, initialized to false. This value is true if this RTCDataChannel was negotiated by the application.

  • id

    The ID for this RTCDataChannel, set when the RTCDataChannel was created. The ID was either assigned by the user agent at channel creation time or selected by the script.

Set up a call configuration object called callConfig defining the local media stream and data transfers, as shown in this example:

var audioMediaDirection = wsc.MEDIADIRECTION.SENDRECV;
var videoMediaDirection = wsc.MEDIADIRECTION.NONE;
var dtConfigs = new Array();
dtConfigs[0] = {"label":"DataLabel", "ordered": true };
var callConfig = new wsc.CallConfig(audioMediaDirection, videoMediaDirection, dtConfigs);

Handling Changes in Call States

Configure your application to respond to the changes in the state of a call. The fields of the wsc.CALLSTATE enumerator object hold the various states of a call, such as STARTED, RESPONSED, and ENDED. For more information about the wsc.CALLSTATE enumerator, see Oracle Communications WebRTC Session Controller JavaScript API Reference.

Process changes to the current call within the callback function for the Call.onCallStateChange event handler. Use the wsc.Callstate#status class and determine the call state status, the code for the current state, and the reason for the current state.

See "Setting Up the Event Handler for Call State Changes".

Handling Changes in Media Stream States

The media stream associated with your application is made up of two media components. The local component in the browser associates with your application. The remote component relates to the browser associated with the other party.

In your application, handle the changes in the media stream states of the call, whether it is voice or video. The WebRTC Session Controller JavaScript SDK provides the wsc.MEDIASTREAMEVENT enumerator which defines the following three states each for the local and remote streams.

  • Added (LOCAL_STREAM_ADDED or REMOTE_STREAM_ADDED)

  • Removed (LOCAL_STREAM_REMOVED or REMOTE_STREAM_REMOVED)

  • In error (LOCAL_STREAM_ERROR or REMOTE_STREAM_ERROR)

For information about how to use the wsc.MEDIASTREAMEVENT enumerator, see "Setting Up the Event Handler for Call State Changes".

For a more information about the wsc.MEDIASTREAMEVENT enumerator, see Oracle Communications WebRTC Session Controller JavaScript API Reference.

Transferring Data With wsc.DataTransfer

Support text messaging, chat sessions, and file transfers in your application through the corresponding data channels of the data transfer objects. You can use the data channels with or without the audio or video streams.

The wsc.DataTransfer class manages a data channel between two peers. Each data transfer has a label for the data channel. For information about dataChannelConfig, the data channel configuration parameter in the CallConfig object, see "Specifying the Media Stream for Calls in the CallConfig Object".

You can retrieve the following information from the DataTransfer object:

  • The sender of the data transfer as an instance of wsc.DataSender class, by calling the getSender method.

  • The receiver of the data transfer as an instance of wsc.DataReceiver class, by calling the getReceiver method.

  • The state of the data transfer, by calling the getState method.

Manage the open, closed, and error states of a data transfer with the onOpen, onClose, and onError event handlers associated with the DataTransfer object.

See "Setting Up Data Transfers in Your Applications" for more information about how you can create applications that support data transfers.

Sending Data Using wsc.DataSender

The wsc.DataSender object represents the sender of a data transfer.

Send a raw data object in the data channel of a data transfer as a string or a binary large object (BLOB) in the DataTransfer object. Retrieve the identity of the sender by calling the getSender() method of the DataSender object. Set up the data object and send it using the send method of the DataSender object in your application. For more information, see "Sample Send Function".

Receiving Data Using wsc.DataReceiver

The wsc.DataReceiver class represents the receiver of a data transfer.

If your application supports receiving raw data, set up a callback function for the onMessage event handler of wsc.DataReceiver. In that callback function, retrieve and handle the retrieved data as required by your application. For example:

receiver.onMessage = function(evt) {
    var rcvdDataElm = document.getElementById("rcvData");
    rcvdDataElm.value = evt.data;
 ...
}

Here,

  • receiver is the instance of wsc.DataReceiver in the application.

  • evt is the raw data in its entirety such as a text string, a BLOB, or array data.

About the Code Segments Displayed in This Guide

The example code segments in this guide focus on the features of the WebRTC Session Controller JavaScript SDK. They use minimal HTML5 elements for display aspects, such as messages and control buttons. Any description of the display aspects of your applications and their CSS elements are beyond the scope of this guide.

The sample applications described in this guide use the console.log method to display debug messages. To assist you in your application development process, use the JavaScript Console API methods supported in the web browser.

About the Application HTML File

This section describes the following aspects of your application HTML file:

About Web Applications Using WebRTC Session Controller JavaScript API

Audio, media stream, or data transfer (such as chat sessions) in WebRTC applications are associated with a call or a subscription in the application. For web applications using the WebRTC Session Controller JavaScript SDK, the Call object or the Subscription object is the critical element for providing communication functionality.

General Call Logic of Your Applications

The general logic associated with calls in web applications consists of the following:

  • Enabling a caller who is logged in to your application to start a call.

    To do so, ensure that your application does the following:

    • Sets up the logic necessary to obtain information about the recipient of the call (the callee identifier).

    • On receiving the number to call from the user, it performs the actions necessary to establish the call session between the caller and callee.

  • Enabling a callee to accept or decline an audio or video call invitation.

    To do so, ensure that your application does the following:

    • Sets up the necessary elements to respond to the incoming call request and perhaps filters the incoming call.

    • If necessary, your application provides the controls for the callee to accept or decline the audio or video call invitation from the caller.

    • If the callee accepts the call, it completes the steps to establish the call session.

    • If the callee declines the call, it takes appropriate steps.

    • If the caller cancels the call before it is established, it takes appropriate steps.

  • Monitoring the established call session until one of the parties ends the call.

    To do so, ensure that your application does the following:

    • Provides the logic necessary to end the call.

    • Takes appropriate action based on whether the call was ended or a party logged out (thus ending the session).

General Notifications Logic of Your Applications

The general logic associated with message alert notifications in web applications comprises the following:

  • Enabling an account holder who is logged in to subscribe to receiving notifications.

    To do so, ensure that your application does the following:

    • Sets up the elements necessary for the account holder to subscribe for notifications.

    • On receiving the subscription target from the subscriber, it sets up the subscriptions.

  • Enabling the account holder to access and process the received notifications.

    To do so, ensure that your application does the following:

    • Sets up the elements necessary to receive the incoming notification and displays it for the user.

    • Sets up the logic to respond to actions taken by the account holder.

WebRTC Session Controller Support Libraries

WebRTC Session Controller provides a set of libraries that you include in your application to support various WebRTC functions. Table 3-1 lists the provided JavaScript files and details the functions each file supports.

Table 3-1 WebRTC Session Controller JavaScript Files

File name Description

wsc-call.js

Call Package API implementation.

To support audio and video calls, include this file in your application. For more information, see "Setting Up Audio Calls in Your Applications".

wsc-capability.js

Capability exchange API implementation.

To support capability exchange, include this file in your application. For more information, see "Capabilities Exchange".

wsc-chat.js

Message Session Relay Protocol (MSRP) chat API implementation.

To support one-to-one and one-to-many chat functionality, include this file in your application. For more information, see "Creating an RCS Chat Application".

wsc-common.js

Common utilities and functionality required by other files. This file is always required unless you are including wsc.js.

wsc-filetransfer.js

File transfer API implementation.

To support file transfers in your application, include this file. For more information, see "Implementing File Transfer".

wsc-messaging.js

Stand alone messaging API implementation.

To support basic messaging, include this file. For more information, see "Sending a Standalone Message".

wsc-msgalert.js

Message notification API implementation.

To support message alerts, include this file. For more information, see "Setting Up Message Alert Notifications".

wsc.js

A combined file including all the WebRTC Session Controller APIs.


Insert references to the appropriate libraries in the head element of your application HTML file.

Example 3-1 Referencing WebRTC Session Controller JavaScript Libraries

<head>
...
<script type="text/JavaScript" src="wsc_context_root/api/wsc-common.js"></script>
<script type="text/JavaScript" src="wsc_context_root/api/wsc-call.js"></script>
...
</head>

In Example 3-1, wsc_context_root represents the HTTP location where the WebRTC Session Controller is provisioned. The libraries wsc-common.js and wsc-call.js are included to support audio and video calling. You can include other libraries from Table 3-1 depending on the requirements of your application.

Note:

The utilities file, wsc-common.js, is required for all applications. Include this file, unless you are using the composite wsc.js file which includes all the APIs as well as the utility functions.

Note:

To access the entire WebRTC Session Controller JavaScript API, include the composite wsc.js file. To improve application performance, include the files supporting the specific functionality you require only.

Including WebRTC Browser Support

For information on an additional JavaScript library that is needed to provide WebRTC browser support for Internet Explorer and Safari, see "Using the WebRTC Browser Extension."

Verifying Browser Capabilities

At the start of your application logic, check your browser to see if it can access the local media stream, including audio and video media. If your browser does not appear to support the streaming needs of your application, enable your application to perform a graceful exit. If your browser can access the local media and your application obtains the media stream, attach the media stream to the appropriate video/audio HTML5 media element.

In the following example, an application checks its browser to see if it can access the local media. If it cannot, the application calls a local function to perform a graceful exit.

if (!navigator.mozGetUserMedia && !navigator.webkitGetUserMedia) {
      // Cannot access media. Call function to perform a graceful exit.
      reportBrowserIssue();
     };

Below, the same application employs a utility function named attachMediaStream to attach a media stream to a video/audio element, when necessary:

var attachMediaStream = null;
attachMediaStream = function(element, stream) {
    element.src = URL.createObjectURL(stream);
    }

About Monitoring Your Application WebSocket Connection

The state of the application session depends on the state of the WebSocket connection. The WebRTC Session Controller JavaScript SDK monitors this connection between your application and WebRTC Session Controller Signaling Engine.

When you instantiate your session object, configure how the WebRTC Session Controller JavaScript APIs check the WebSocket connection. Monitor the state of the connection, by setting the following values in the Session object:

  • Session.ackInterval, the interval between receiving acknowledgement messages.

  • How often the WebRTC Session Controller JavaScript SDK must ping the WebRTC Session Controller Signaling Engine:

    • Session.busyPingInterval, when there are subsessions inside the session. The default is 3,000 milliseconds (ms).

    • Session.idlePingInterval, when there are no subsessions inside the session. The default is 10,000 ms.

  • Session.reconnectInterval, which specifies the interval between attempts to reconnect to the WebRTC Session Controller Signaling Engine. The default is 2000 ms.

  • Session.retryCount which specifies the timeout retry count. After this count is reached, the WebRTC Session Controller JavaScript SDK reconnects to the WebRTC Session Controller Signaling Engine. The default value is 2.

  • Session.reconnectTime, which specifies the maximum time for the interval during which the WebRTC Session Controller JavaScript SDK attempts to reconnect to the server. If the specified time is reached and the connection still fails, no further attempt is made to reconnect to the WebRTC Session Controller Signaling Engine. Instead, the session failureCallback event handler is called in your application. The default value is 60,000 ms.

    Note:

    Verify that the Session.reconnectTime value does not exceed the value configured for "WebSocket Disconnect Time Limit" in WebRTC Session Controller.

When your application is active, these values are used to check the state of the WebSocket connection.

When there is a device handover, your application suspends the application session. The WebSocket connection closes abnormally. See "Handling Session Rehydration When the User Moves to Another Device".

Managing Interactive Connectivity Establishment Interval

Your application can configure the time period within which the WebRTC Session Controller JavaScript API library uses the Interactive Connectivity Establishment (ICE) protocol to set up the call session. This procedure comes into play when your application is the caller and your application starts the call setup with its Call.start command.

About the Use of ICE and ICE Candidate Trickling

ICE is a technique which determines the best possible pairing of the local IP address and the remote IP address that can be used to establish the call session between the two applications associated with the caller and the callee. Each user agent (caller or callee's browser) has an entity (such as WebRTC Session Controller Signaling Engine) which acts as the ICE agent and collects and shares possible IP addresses. The final pair of IP addresses is elected after gathering and checking possible candidates (IP addresses) and taking into account the security of the end point applications and of the call connection. The media connection is established only after the ICE procedure finds an appropriate pair of IP addresses with which to communicate.

About WebRTC Session Controller Signaling Engine and the ICE Interval

WebRTC Session Controller Signaling Engine enables your applications to limit the time taken by the ICE agent to set up a call session by enabling you to specifying the ICE interval your application allows for this deliberation process.

The default value ICE interval for a call setup is 2000 milliseconds.

Signaling Engine checks the status of the ICE candidate periodically. If new candidates are gathered, the ICE agent will attempt to send this information in JSON format in the START message to the other peer.

Retrieving the Current ICE Interval for the Call

To retrieve the current ICE interval, use the getIceCheckInterval method of your application's call object. The interval is returned in milliseconds.

Setting Up the ICE Interval for the Call

To set the current ICE interval, provide the time interval in milliseconds when you call the setIceCheckInterval method of your application's Call object.

About Handling Events in the Application Environment

Configure your application to handle the following events in your deployment environment:

  • Client rehydration

    At times, the account holder reloads the application page, or the application reloads as a result of the browser. See "Handling Session Rehydration on the Same Client Device".

  • Network switchover

    A network switchover takes place when the IP address of the account holder changes. For example, the associated device switches from a WI-FI network to 4G network. When a network switchover takes place, the WebRTC Session Controller JavaScript SDK reconnects your application session with WebRTC Session Controller Signaling Engine. It then tries to resurrect all the subsessions inside the Session object, such as the call and the subscription.

    For information about handling a call after a network switchover, see "Restoring a Call Session". For information about handling a subscription after a network switchover, see "Restoring a Subscription Session".

  • Clustered server shut down

    In a cluster environment, the server to which your application browser web browser is connected shuts down. In this scenario, the WebRTC Session Controller JavaScript SDK tries to reconnect your application session to the corresponding failover server. If the connection is re-established, the WebRTC Session Controller JavaScript SDK attempts to resurrect all the subsessions inside the Session object.

    For information about handling a call after a server failover, see "Restoring a Call Session". For information about handling a subscription after a server failover, see "Restoring a Subscription Session".

  • Session Hibernation

    When there is a period of inactivity, your applications can go into hibernation and disconnect from the WebRTC Session Controller server. It is awakened when there is a notification, and handles that event. See "Supporting Web Client Notifications in Your Applications".

  • Session Rehydration following a Device Handover

    In a device handover, a customer account is associated with more than one device. The customer starts a call on one device. During the call, the customer switches to another device continue the call. For example, Alice is on a cellphone call to a sales representative. During the call, Alice switches attempts to continue the call on the softphone on the laptop. See "Handling Session Rehydration When the User Moves to Another Device".

Supporting Web Client Notifications in Your Applications

Configure support for notifications in your applications. A client application running on a browser retrieves a registration ID from its notification provider. With this registration, your application users are notified of various events when the application hibernates. The notifications are related to web events, such as a promotion offered by a website to which the account holder has subscribed.

An application session for an account holder (Bob) is in hibernation. Then an event, such as an incoming call for Bob, occurs. The WebRTC Session Controller server sends an HTTP message to the cloud messaging server. The response to this message contains the registration ID for the application and the payload. On being woken up on that browser, your application reconnects with the server. It uses the saved session ID to resurrect the session data, and handles the incoming event.

If no event occurs during the specified hibernation period, there are no notifications to process. The hibernation period expires and the WebRTC Session Controller server cleans up the session.

Such support of web client notifications enables your applications to lower Firewall licensing costs by closing connections associated with hibernating sessions. After storing the session state in passive storage, your application can release server resources such as open files and network connections.

Preliminary configurations and registration actions are necessary to support client notifications in your applications. They provide necessary information about the browser, the APIs, the application, and so on to the WebRTC Session Controller server and the cloud messaging provider.

About the WebRTC Session Controller Notification Service

The WebRTC Session Controller Notification Service manages the external connectivity with the respective notification providers. It implements the Cloud Messaging Provider specific protocol such as GCM, APNS. The WebRTC Session Controller Notification Service ensures that all notification messages are transported to the appropriate notification providers.

Important:

To activate the WebRTC Session Controller Notification Service, ensure that you configure the service using the Configuration tab in the WebRTC Session Controller Administration Console. See the description about "Configuring WebRTC Session Controller Notification Service" in WebRTC Session Control System Administrator's Guide.

The WebRTC Session Controller server constructs a message to trigger the notification provider to deliver a push notification to the web application. It constructs the message using the following:

  • The received message payload from your application.

  • The payload configured in the application settings.

  • The application provider settings you provide WebRTC Session Controller.

About Employing Your Current Notification System

At this point, verify if your current installation has an existing notification server that talks to the Cloud Messaging system and that the installation supports applications for your users through this server. If you currently have such a notification server successfully associated with a cloud messaging system, you can use the pre-existing notification system to send notifications using the REST interface.

How the Notification Process Works

Let us take the WebRTC call as an example. The notification process works in this manner:

  1. Bob, a valid account holder, accesses a web browser, such as Google Chrome or Mozilla Firefox.

  2. The web browser registers with the notification service. The response from the browser contains the device token. It is the registration ID from the notification provider such as Google Cloud Messaging system or Apple Push Notification Service. This registration ID identifies browser instance.

  3. Bob logs in to your application on the web browser. In this scenario, your audio call application features on that web browser.

  4. The WebRTC Session Controller client SDK connects with the WebRTC Session Controller server and a session is created.

    A WebSocket connection is opened.

  5. When there is inactivity on the part of the account holder (Bob), your application goes into the background. Your application sends a message to the WebRTC Session Controller server informing the server of its intent to hibernate and specifies a time duration for the hibernation.

    The WebSocket connection closes.

  6. During the hibernation period, an event occurs. For example, Alice calls Bob, a call that is targeted to the audio call feature on your application.

  7. WebRTC Session Controller server receives this call request from Alice. It checks the session state and determines that the request came during the hibernation period. The WebRTC Session Controller server uses its notification service to send a notification to the notification provider.

  8. The notification provider delivers the notification to your audio call application on the web browser.

  9. On receiving this notification:

    1. Your application uses WebRTC Session Controller JavaScript APIs to issue a request to rehydrate the session and reconnect with the WebRTC Session Controller server.

    2. The call starts. Your application user interface logic informs Bob appropriately. In this example, the soft phone rings on the browser.

  10. Bob accepts the call.

  11. Your application logic manages the call to its completion.

Note:

If the time set for the hibernation period completes with no event, the WebRTC Session Controller server closes the session. The Session ID and its data are destroyed.

In this scenario, your application cannot use the session ID to restore the data. It must create a session.

Handling Multiple Sessions

If you have defined multiple applications in WebRTC Session Controller, then it is likely that customers access more than one such WebRTC Session Controller application. As a result, multiple WebRTC Session Controller-associated sessions in the device can be active.

Where more than one session data is involved, all the associated session data is stored appropriately. Your application instances can retrieve all the data.

The Process Workflow for Your Web Application

The process workflow to support notifications in your WebRTC application are:

  1. The prerequisites to using the notification service are complete. See "About the General Requirements to Provide Notifications".

  2. An account holder accesses your application on the web browser. Your application on the browser sends the registration_Id (also called the deviceToken) to the Client SDK. The Client SDK then sends it to the WebRTC Session Controller server and saves it locally.

  3. To wake up a hibernating session, the WebRTC Session Controller server sends a message with the registration_id to the notification provider.

  4. The notification provider delivers this notification to the web browser.

  5. Your application on the browser is awakened. It re-establishes communication with the WebRTC Session Controller server and handles the event.

Before You Proceed

The WSC Android SDK API, hibernate(), enables your applications to handle notifications related to session hibernation. For information about the supported WebRTC Session Controller Web APIs, see Oracle Communications WebRTC Session Controller JavaScript API Reference.

Please review the following sections before you implement web client notifications in your application:

About the General Requirements to Provide Notifications

Complete the following tasks as required for your application. Some are performed outside of your application:

Register with the Cloud Messaging System

Register your WSC installation with the appropriate system:

  • Google API Console:

    Create a project and obtain the following:

    1. Project ID

    2. API Key

    For information about how to complete this task, refer to the Google Developers Console Help documentation.

  • Apple Push Notification Service

    Set up the following:

    1. SSL certificate to communicate with the APN service.

    2. Provisioning profile for the application.

    For information about completing these tasks, refer to the Local and Remote Notification Programming Guide in the iOS Developer Library at

    https://developer.apple.com/library/ios/navigation/.

For information about how to complete this task, refer to the Google Developers Console Help documentation.

Enable Your Applications to Use WebRTC Session Controller Notification Service

This step is performed in the WebRTC Session Controller Administration Console.

Access the Notification Service tab in the WebRTC Session Controller Administration Console and configure the use of WebRTC Session Controller Notification Service. For each application, enter the application setting such as the application ID, API Key, the cloud provider for the API service. For more information about completing this task, see "Creating Applications for the Notification Service" in WebRTC Session Controller System Administrator's Guide.

Obtain the Registration ID to Allow Push Notifications

This step is performed within your WebRTC application.

Your application registers for push notifications from a notification provider (such as Google Cloud Messaging system or Apple Push Notification Service) and receives a registrationId. To register for the notification, use the Push API or Notification API, as appropriate.

  • Google

    For information about how to complete this task for the Chrome browser, see the discussion about Push Notifications on the Open Web in the Google Developers documentation.

  • Mozilla

    For information about how to complete this task for the Firefox browser, see the discussion about Push API in the Mozilla Developer Network documentation.

General Tasks to Implement Session Rehydration

The WebRTC Session Controller Web SDK requires a session ID to support the rehydration of a session. To implement session rehydration in your application:

  • Persist Session IDs

    To provide your customers with uninterrupted quality in service, persist the session ID value in your applications. To do so, use the various standard storage mechanisms offered by the browser platform. See "Store the Session ID".

  • Use the appropriate Session ID

    Provide the same session ID that the client last successfully connected with when it hibernated.

  • Set up the logic to trigger hydration for more than one session object.

    This scenario occurs when you have multiple applications defined in WSC. Your customer creates a session with each one of WSC applications in their application. In such a scenario, the client application uses as many session objects.

Handling Hibernation Requests from the Server

When your application receives a request to hibernate from WebRTC Session Controller, provide the necessary logic to handle the user interface and other elements in your application.

See "Responding to Hibernation Requests from the Server" for information on how to set up the callbacks to the specific WebRTC Session Controller JavaScript SDK event handlers.

Tasks that Use WebRTC Session Controller Web SDK APIs

The following tasks use WebRTC Session Controller Web SDK APIs:

For information about the supported WebRTC Session Controller Web SDK APIs, see Oracle Communications WebRTC Session Controller JavaScript API Reference.

Provide the Device Token and Application Information when Creating the Session Object

When you create the Session object, provide the device token you received from the notification provider. In the following syntax used to create the session object, the extPayloads parameter is used as the extensions payload for push notification service:

new Session(userName, webSocketUri, successCallback, failureCallback, extHeaders, extPayloads)

Example 3-2 Providing a Device Token and Application Information when Creating a Session

...
var sessionId = null;
...
var mediaOptions = {};
...
// Set up mediaOptions
...
wscSession = new wsc.Session(null, wsUri, sessionSuccessHandler, sessionFailureHandler, null,
                             {'X-MediaOptions': mediaOptions}, 
                             {"capability": {"appid": "oracle.wsc.samples.web",
                                             "appversion": "0.1"}, "devicetoken": "appDeviceToken"});

In Example 3-2, the sample code excerpt creates an instance of the Session class object called wscSession, with:

  • username, the first parameter has a value null. This code obtains the user name from the authentication handler for the session.

  • wsURI as its WebSocket connection.

  • sessionSuccessHandler as the callback function for a successful creation of the session.

  • sessionFailureHandler as the callback function for a successful creation of the session.

  • null for the sessionId parameter when you create the session. The Web client SDK assigns the session ID.

  • The extHeaders in the JSON object using mediaOptions to specify the media options for Temasys Plug-in.

  • The extPayloads in the JSON object that contains application information in capability, and the device token in appDeviceToken.

    Web client SDK adds the contents of extPayloads to the payload it sends to the WebRTC Session Controller server.

See Example 4-3 for a complete example of registering an authentication handler for the session and configuring other attributes of the newly created session.

Store the Session ID

The getSessionId() method of wsc.Session object returns the session identifier as a String object. Retrieve the session ID and store it in your application, for example in the sessionSuccessHandler, the callback function for a successful creation of the session.

Tip:

You can create an extensible session using the ExtensibleSession class. Its saveToStorage method uses the HTML sessionStorage object stores data for one session. (If the browser tab closes, the data is lost.)

Example 3-3 Storing the userName and sessionId

function sessionSuccessHandler() {
    console.log(" In sessionSuccesshandler.");

   ...
    // Store user name in sessionStorage.
    userName = wscSession.getUserName();
    sessionStorage.setItem("userName", userName);
  
    // Store sessionId in sessionStorage.
    sessionStorage.setItem("sessionId", wscSession.getSessionId());
   ...
}

See Example 4-3 for the example function.

To persist the session ID, use the various standard storage mechanisms offered by the browser platform.

Your application uses this session ID to immediately present "Bob" (the user) with the last current state of Bob's session with your application. For more information, see the description of wsc.Session and wsc.ExtensibleSession in Oracle Communications WebRTC Session Controller JavaScript API Reference.

Implement Session Hibernation and Handle its Scenarios

When your web application is in the background, your application must send a request back to WebRTC Session Controller stating that it wants to hibernate the session. Use the appropriate method to release shared resources, invalidate timers. Store the state information necessary to restore your application to its current state, in case it is terminated at a later time.

The WebRTC Session Controller Web Client SDK provides the following method in the wsc.Session object.

hibernate(timeToLiveInSecs, onSuccess, onError)

Where:

  • timeToLiveInSecs, the time (in seconds) for which the session is alive. After this time, the session cannot be hibernated.

    For timeToLiveInSecs, provide the maximum period for which the client session is to be kept alive on the server. All notifications received within this period are sent to the client device.

    The WebRTC Session Controller server maintains a maximum interval depending on the policy set for each type of client device. If your application sets an interval greater than this period, the server uses the policy-supported maximum interval.

  • onSuccess, the callback for a successful hibernation. Set up a function for this callback and provide the logic your application requires.

  • onFailure, the callback for an error in hibernating the session. Set up a function for this callback and provide the logic your application requires.

The WebRTC Session Controller server identifies the client device (going into hibernation) by the deviceToken you provided when building the session object. When the hibernate method completes, the wscConst.SessionState for the session is HIBERNATED. The session with the WebRTC Session Controller server closes. Your application can take no action, such as making a call request, until the session is resurrected.

For information about hibernate method, see the description about WSCSession in Oracle Communications WebRTC Session Controller JavaScript API Reference.

Send Notifications to the Callee when Callee Client Session is in Hibernated State

If the callee client session is in a hibernated state, any incoming event for that client session requires some time for the call setup so that the callee can accept the call. In your web application, add the logic to handle push notification event when the callee session is in a hibernated state.

In Example 3-4, the application uses the JavaScript addEventListener method to attach an function as the event handler to the specified element, 'push' for the push event.

Example 3-4 Setting up a Function to handle a Push Notification

self.addEventListener('push', function(event) {
      console.log('Push Event Received');
 
  //Set up a notification to indicate a push event received with the msg payload
  var title = 'Push notification: Someone is calling you';
  var body = 'Please click this notification to rehydrate web if you accept the call.';
  var icon = 'imagelocation.format';
  var tag = 'ImageNametoUseAsTag';
 
 // Chain the waitUntil method to the event to ensure the code inside waitUntil() occurs.
  event.waitUntil(
    self.registration.showNotification(title, {
      body: body,
      icon: icon,
      tag: tag
     })
   );
 });

Rehydrate the Session with the Session ID

To rehydrate an existing session, use the stored session ID that you stored earlier.

Example 3-5 Rehydrating the Session

// If sessionId is stored in SessionStorage, set up the rehydration process.
  if (sessionStorage.getItem("sessionId")) {
// SessionId is stored in SessionStorage. Reconnect and handle the call event.
    connect(sessionStorage.getItem("sessionId"), sessionStorage.getItem("userName"));
    ...
  } else {
// Cannot resurrect session. Take appropriate action.
    ...
  }

The connect function used by the sample excerpt above is set up as:

function connect(sessionId, username) {
    var wsUri = protocol.replace(/^http/, 'ws') + '//' + address + requestUri;
    var mediaOptions = {};
 
    if (tenant) {
// Update the wsUri with the tenant profile key.
      wsUri += '?tenant_profile_key=' + tenant;
    }
// Retrieve the Flash settings.
    if (typeof wsc_flash != 'undefined') {
      mediaOptions = getMediaOptions();
    }
    if (sessionId) {
// Session exists.
      wscSession = new wsc.Session(username, wsUri, onSuccess, onFailed, sessionId, {'X-MediaOptions': mediaOptions});
      wscSession.isRefresh = true;
    } else {
// Create aplug-in session. Session ID is assigned on successful creation.
      wscSession = new wsc.Session(username, wsUri, onSuccess, onFailed, undefined, {'X-MediaOptions': mediaOptions});
    }
 
    var authHandler = new wsc.AuthHandler(wscSession);
    authHandler.refresh = function(authType, authHeaders) {
      var authInfo = null;
      if(authType == wsc.AUTHTYPE.SERVICE) {
        authInfo = getServiceAuth(authHeaders);
      } else if (authType==wsc.AUTHTYPE.TURN) {
        console.log("Turn server auth challenge");
      }
      return authInfo;
    };
  }

Your application can repopulate the data associated with the session by doing the following:

Responding to Hibernation Requests from the Server

When the server has to force your application to hibernate, it calls the onHibernationRequest event handler in the Session interface.

To handle the user interface and other elements in your application, provide the necessary logic in your implementation of the onHibernationRequest callback.

Example 3-6 Handling Server-originated Hibernation Requests

...
 wscSession.onHibernationRequest = function(wscSession) {
   wscSession.handleHibernateRequest(response_code, reason);
 }  
 ...
 

Managing the Sessions in Your Application

When you use the WebRTC Session Controller JavaScript SDK in your application, your application can create an instance of the Session object and its subsessions, such as a call session or a subscription session. This section describes how the WebRTC Session Controller JavaScript SDK manages the session and subsession information.

Note:

Any discussion on the management of arbitrary session or subsession data is beyond the scope of this document.

About Session Rehydration Scenarios

Many types of events occur during the life cycle of an application session. Set up your application to manage the session data appropriately. The rehydration scenarios associated with your application Session can be:

Handling Session Rehydration on the Same Client Device

A network switchover, or a clustered server shut down affects an application session. Configure the logic in your application to recover from the event. Present the account holder with the current state of the session and its sub sessions on the same device.

How WebRTC Session Controller Restores Application Data on the Same Device

When there is a client rehydration, a network switchover, or a clustered server shut down, the WebRTC Session Controller JavaScript SDK attempts to restore your application. To do so, it uses the sessionId as the key and loads the saved session data from the sessionStorage object associated with the browser. It then sends a reconnect message to the WebRTC Session controller Signaling Engine.

If the reconnection request receives a success response from WebRTC Session Controller Signaling Engine, your application session state goes from wsc.SESSIONSTATE.RECONNECTING to wsc.SESSIONSTATE.CONNECTED. Monitor this change in the callback function you assign to the Session.onSessionStateChange event handler.

When the session regains its wsc.SESSIONSTATE.CONNECTED state, the WebRTC Session Controller JavaScript SDK provides the following to your application:

If the WebRTC Session Controller JavaScript SDK fails to load data, it calls the failureCallback function associated with the session creation step.

Recreating the Session When the Application Page Reloads

Ensure that you save the session identifier for the created session in your application. To recreate the Session object when your application page reloads, use that session identifier for the previously created session.

In Example 3-7, an application checks the isPageReload variable. If the page has been reloaded, the application attempts to create the current session by providing the sessionId it had previously stored. Otherwise, it creates a new session.

In this application:

  • userName is the user name.

  • webSocketUri is the WebSocket connection defined earlier. See "Sample Setup of Global Variables and WebSocket URI".

  • successCallback is the function to call if the session object was created successfully.

  • failureCallback is the function to call if the session object was not created.

  • sessionId is the Session ID stored by the application.

Example 3-7 Recreating the Session Using SessionId Example

var isPageReload = false;
var sessionId = null;
...
...
// Create the session. If the page is reloaded, recreate the current session.
if (isPageReload) {
    // Aplication page reload scenario. Input the saved sessionId.
    wseSession = new wse.Session(userName, webSocketUri, successCallback, failureCallback, sessionId);
    } else {
    // This is a new session. Save sessionId if you have extended any API.
        wseSession = new wse.Session( userName, webSocketUri, successCallback, failureCallback);
        }
...

In addition, this application uses the following functions:

  • The onPageLoad function sets the isPageLoad variable to true if the application page is the result of a page reload.

    function onPageLoad() {
        if (getSavedPageInfo()) {
            isPageReload = true;
            register();
           }
        }
    
  • The savePageInfo function saves the sessionId in the HTML sessionStorage object.

    function savePageInfo() {
        sessionStorage.setItem("sessionId", wseSession.getSessionId());
        }
    
  • The getSavedPageInfo function attempts to retrieve the sessionId from the HTML sessionStorage object.

    function getSavedPageInfo() {
        sessionId = sessionStorage.getItem("sessionId");
        if (sessionId != null) {
            return true;
        }
        return null;
        }
    
  • The successCallback function is called when the session is created successfully is not shown here. This function calls the savePageInfo function.

After recreating the session, your application can repopulate the data by doing the following:

Restoring CallPackage Data After Pages Reload

To restore the call package data after your application pages successfully reload, set up appropriate actions within the callback function assigned to the CallPackage.onRehydration event handler. This callback function has one parameter, rehydratedData, which contains the data about the call stored in the sessionStorage object of the web browser. Within the callback function, define the actions to handle the recovered call. See "Restoring a Call Session".

When you extend the CallPackage object in your application, you can override its onRehydration event handler. See "Extending Objects Using the wsc.extend Method" for more information.

Restoring Extended MessageAlertPackage Data After Pages Reload

To handle the subscription session data after your application pages successfully reload, set up appropriate actions within the callback function assigned to the MessageAlertPackage.onRehydration event handler. This callback function has one parameter, rehydratedData which contains the data about the subscription stored in the sessionStorage object of the web browser. Within the callback function, define the actions with respect to the recovered subscription. See "Restoring a Subscription Session".

When you extend the MesageAlertPackage object, you can override its onRehydration event handler and use this function to refresh the current subscription with the recovered data. For more information, see "Extending Objects Using the wsc.extend Method".

Restoring a Call Session

If a call is recovered following a page reload, a network switchover, or a server failover, the WebRTC Session Controller JavaScript SDK calls the CallPackage.onResurrect event handler in your application. The resurrected call is provided as the parameter to the callback function. To perform the actions required on the rehydrated call and resume the rehydrated call, use the callback function. See "Resuming Your Application Operation".

In Example 3-8, an application sets up callHandler as an instance of the CallPackage class object and assigns onResurrect as the callback function for its CallPackage.onResurrect event handler. The onResurrect callback function uses the rehydratedCall object.

Example 3-8 Sample onResurrect Function for a CallPackage

callHandler = new wsc.CallPackage(wscSession);
if(callHandler){
  callHandler.onResurrect = onResurrect;
}
...
function onResurrect(rehydratedCall) {
  // set callback for call state changed
  rehydratedCall.onCallStateChange = function(newState) {
    ...
  }
  // set callback for media state changed
  rehydratedCall.onMediaStreamEvent= function(mediaStreamEvent, stream) {
    ...
  }
  // resume the call with setting related callback functions.
  rehydratedCall.resume(onResumeCallSuccess, doCallError);
}

Restoring a Subscription Session

When a subscription is recovered following a page reload, a network switchover, or a server failover, the WebRTC Session Controller JavaScript SDK calls the MessageAlertPackage.onResurrect event handler. The rehydrated subscription is provided as the parameter to the callback function. To perform the required action, use the corresponding callback function. See "Resuming Your Application Operation".

In Example 3-9, an application sets up subscribeHandler as an instance of the MessageAlertPackage class object and assigns onResurrect as the callback function for its MessageAlertPackage.onResurrect event handler. The onResurrect callback function uses the rehydratedSubscription object to restore the current Subscription object.

Example 3-9 Sample onResurrect Function for a MessageAlertPackage

subscribeHandler = new wsc.MessageAlertPackage(wscSession);
if (subscribeHandler) {
    subscribeHandler.onResurrect = onResurrect;
}
...
function onResurrect(rehydratedSubscription) {
    // reset related callback functions
    subscription = rehydratedSubscription;
    subscription.onNotification = onNotification;
    subscription.onEnd = onEnd;
    // initialize other information about page ...
}

Resuming Your Application Operation

To resume your application operation following a page reload, a network switchover, or a server failover:

  • For calls: Resume the current call by invoking its resume method. See "Reconnecting Dropped Calls".

  • For subscriptions: Call the isValid method for the subscription and take further action. If the account holder prefers to end the subscription, use the end method to do so. See "Restoring a Subscription Session".

    Important:

    If you create a custom package, be sure to implement the appropriate logic to resume its call or subscription operation.

Handling Session Rehydration When the User Moves to Another Device

At times, actions taken by customers in the personal, local, or wide area network result in the application session shifting from one device to another. This happens when a customer using your application on one device (a cellphone) moves to your application on another device (a laptop softphone that uses the same account authenticated by WebRTC Session Controller). For example, your customer Alice, accesses a web browser from a cellphone to talk about a purchase selection with Bob, a customer support representative. While Alice is on the call, she switches over to a laptop to look at the purchase selection in greater detail.

You can use the WebRTC Session Controller to configure applications that support handovers of session information between devices successfully. Your application then manages the rehydration of the session and all its data on the target device (in this example, the laptop). All handovers of application sessions from the client device take place seamlessly and maintain the quality of service.

This section described how your application can work to present the customer with the session state recreated on another device.

Note:

In a device-handover scenario, WebRTC Session Controller manages the data associated with the subsessions of your application session. It keeps their states intact through the handovers that occur during the life of an application session.

The focus of the handover logic in your application is the Session within which a call, a message, or a video session is alive.

About the Supported Operating Systems

You can design your applications using WebRTC Session Controller JavaScript API such that you support handover to your applications programmed for Android, and the iOS systems.

Note:

For such a handover to be successful, all the following are necessary:
  • WebRTC Session Controller authenticates the user name and account.

  • The various operating systems support your application.

  • Your application is active on the various devices belonging to a user.

This chapter deals with setting up your WebRTC application to support handing using the WSC JavaScript SDK. For information about supporting handovers to:

Configuring WebRTC Session Controller to Support Transfer of Session Data

In a device handover, the same WebSocket sessionID is used to transfer an application session state that is active in the current client device (for example, DeviceA-1, a cellphone belonging to Alice) and present that state on the subsequent device (DeviceA-4, her laptop).

When one client uses another client's websocket sessionID to connect with WebRTC Session Controller, the server checks the value in the system property, allowSessionTransfer. The default value of allowSessionTransfer is false. This value causes WebRTC Session Controller to consider the request as a hacking attack and reject the request.

In order to allow the same account holder or tenant to connect with the WebRTC Session Controller server using the same WebSocket session ID, set the startup command option allowSessionTransfer to true. For more information about how to do so, see "Supporting Session Rehydration for Device Handover Scenarios" in WebRTC Session Controller System Administrator's Guide.

About the WebSocket Disconnection

When the device handover takes place, the WebSocket connection immediately closes.

The WSC signaling engine keeps the session alive for a time period specified as WebSocket Disconnect Time Limit in the WebRTC Session Controller Administration Console.

Note:

If the target device fails to pick up the session within the WebSocket Disconnect Time Limit period, the device handover fails.

About the Normalized Session Data User to Support Handovers

WebRTC Session Controller supports a normalized uniform session data format to transfer the session state information between the following systems.

  • Web

  • Android

  • iOS

Example 3-10 shows the session state information sent in a sample handover request by Web SDK.

Example 3-10 Session State Data in a Sample Handover Request

{
   "sessionId":"pQAAAU+78M8vPdzNtkVUbg4nrgwAAAAD_182",
   "userName":"alice@example.com",
   "unACKedMsgQueue":{
      "lowerSeq":3,
      "upperSeq":3,
      "msgQueue":{
         "array":[
            {
               "control":{
                  "type":"message",
                  "package_type":"call",
                  "session_id":"pQAAAU+78M8vPdzNtkVUbg4nrgwAAAAD_182",
                  "subsession_id":"0a74f9cf-dd75-4bdd-8fe6-3b4886b9c365",
                  "sequence":3,
                  "correlation_id":"c2",
                  "version":"1.0"
               },
               "header":{
                  "action":"complete"
               },
               "payload":{
               }
            }
         ],
         "offset":0
      }
   },
   "lastOutboundSeq":3,
   "lastInboundSeq":3,
   "lastUnHandledInboundReq":null,
   "subSessionsMap":{
      "mapSize":4,
      "entry":{
         "call":{
            "mapSize":1,
            "entry":{
               "0a74f9cf-dd75-4bdd-8fe6-3b4886b9c365":{
                  "caller":"alice@example.com",
                  "callee":"bob@example.com",
                  "callConfig":{
                     "audioConfig":"SENDRECV",
                     "videoConfig":"SENDRECV",
                     "dataChannelConfig":null
                  },
                  "callState":{
                     "state":"ESTABLISHED",
                     "status":{
                        "code":null,
                        "reason":"sent complete"
                     }
                  },
                  "earlyMediaState":null,
                  "subSessionId":"0a74f9cf-dd75-4bdd-8fe6-3b4886b9c365",
                  "remoteMedias":[
                     {
                        "type":"audio",
                        "mode":"sendrecv",
                        "port":"53261"
                     },
                     {
                        "type":"video",
                        "mode":"sendrecv",
                        "port":"53261"
                     }
                  ],
                  "offerAnswerManager":{
                     "trickledCandidatesMap":{
                        "mapSize":0,
                        "entry":{
                        }
                     },
                     "masterState":"Ack sent",
                     "slaveState":"Initial state"
                  }
               }
            }
         },
         "flash":{
            "mapSize":0,
            "entry":{
            }
         },
         "chat":{
            "mapSize":0,
            "entry":{
            }
         },
         "file_transfer":{
            "mapSize":0,
            "entry":{
            }
         }
      }
   },
   "packagesMap":{
      "mapSize":5,
      "entry":{
         "register":{
            "packageType":"register"         },         "call":{            "packageType":"call",            "trickleIceMode":"off"         },         "flash":{            "packageType":"flash",            "trickleIceMode":"off"         },         "chat":{            "packageType":"chat"         },         "file_transfer":{            "packageType":"file_transfer"         }      }   }}

About the Handover Scenario on the Original Device

When the original device (Device A-1) detects a handover, the following events occur:

  1. On the original device:

    1. Your application on DeviceA-1 suspends the active session on the WebRTC Session Controller server. The Web Client SDK API returns the session data to your application. The application session on the original device closes.

      See "Suspending the Session on the Original Device".

    2. Your application transfers the session data (stateInfo) for use by the application on the device Device A-4.

      Your application on the original device (Device A-1) sends the session state information in a handover request to the Application Service (your application, a web application, or a RESTful service).

      You can configure how your application performs this task in the way that suits your environment. For example, your application can push the stateInfo to other device or allow the other device to pull the stateInfo.

      See "Sending the Handover Request with Your Session Data".

    The WSC Signaling engine keeps this session alive for a time period specified as WebSocket Disconnect Time Limit in the WebRTC Session Controller Administration Console.

  2. On the device receiving the handover:

    The subsequent device (Device A-4 in our example), pulls the device handover data actively. Your application on Device A-4 is awakened. See "Recreating the Application Session for the Handover Recipient".

Completing the Tasks to Support Session Rehydration in Another Supported Device

This section describes the tasks to complete in your application to hand over a session to and to receive a session handed over from another device. To support session transfers and rehydration with the transferred session state information to another device, complete the following tasks:

Suspending the Session on the Original Device

In order to implement a handover, your application on the original device DeviceA-1 suspends the active session on the WebRTC Session Controller server. One scenario would be to set up a handover function and suspend the session within its logic.

Note:

The logic surrounding the detection of the actual device handover is beyond the scope of this document.

The WSC JavaScript API method to suspend a session is suspend(). This method does both of the following:

  • It returns the session data in JSON format.

  • It calls the onSessionStateChange event for wsc.Session in your application.

In your application logic that handles the user interface related to the handover, invoke the WSC JavaScript API method Session.suspend().

Example 3-11 Suspending a Session

...
// Handover detected
function handover() {
...
    var sessionData = JSON.parse(wscSession.suspend());
...
}

In Example 3-11, the sample code excerpt parses the JSON string object into JSON format.

Sending the Handover Request with Your Session Data

When the suspend() method completes, the session state is SUSPENDED. In the event handler for the onSessionStateChange event for wsc.Session, set up the information to transfer to the Application service. Convert the session data that is now in JSON format into a JSON string object by calling the JSON.stringify() method. Include this JSON string object and any other relevant information in the data you send with the handover request to the application service.

In the following code excerpt shown in Example 3-12, the application normalizes the session data it received from the suspension. It then sends the session data along with other relevant information to the target device using the jQuery $.post() method.

Example 3-12 Posting the Session Data from the Initial Device (Example)

// The handover REST service is deployed on the host server 
...
  var restServerBaseUrl = protocol + '//' + address + "/handoverservice/v1";
  var addSessionDataUrl = restServerBaseUrl + "/add/";
...
    $.post(addSessionDataUrl + webId, JSON.stringify(sessionData), function(){}, "text")
      .done(function() {
        console.log("Send session data to REST server successfully.");
      })
      .fail(function(evt) {
        console.warn("Failed to send session data to REST server with error", evt);
      });
...
  });
 

In Example 3-12:

  • The wsc.Session.suspend method returns the session data parsed in JSON format.

  • The user name webId was authenticated earlier in the sample code.

  • The $.post() method sends the data to the RESTful service on the host server. The function(){} indicates that the application does not run any other function.

Recreating the Application Session for the Handover Recipient

When the subsequent device also supports Web Client SDK, WebRTC Session Controller manages the interim actions such as reconnecting with the WebRTC Session Controller server, sending the invite requests, and resuming the call (in our example case).

The handover ends with the successful continuation of the ongoing session for the customer. Verify that your application state is fully maintained by addressing the effect of device handovers on all other application and user interface logic that does not involve WebRTC Session Controller APIs.

This chapter dealt with setting up your WebRTC application to support handovers using the WebRTC Session Controller JavaScript SDK. For information about supporting handovers in:

Configuring Screen Sharing

You can set up your WebRTC-enabled application to support the sharing of a screen between a caller and a callee in a call session. You can share the screen between any two browsers.

About the Requirements

Verify that the following requirements for screen sharing are satisfied and available in your environment:

  • WebRTC Session Controller

  • The browser-specific plug-in using the browser-provided APIs for WebRTC.

How the Screen Sharing Process Works

When you have configured your WebRTC-enabled application for screen sharing your environment:

  1. A caller establishes a WebRTC-enabled application session on one browser.

    Two Chrome browsers are involved. Both are video-enabled and compliant with the necessary elements.

    A caller (Alice) accesses your application on her browser in which your application is installed. Your application on her browser gets an alert based on the plug-in user interface you created.

  2. Alice sets up a call with a callee (Bob) and Bob accepts the call.

    Bob accepts the call on the call session user interface of your application on the browser. The call session is established.

    The browser for both parties displays your application screen-sharing user interface element where the customer can make some selections.

  3. Screen Sharing request from one of the parties in the call.

    One of the parties, Alice, or Bob, clicks the screen-sharing user interface element to request screen sharing.

    WebRTC Session Controller SDK sends an alert to the plug-in informing it about the start of the screen-sharing session.

    WebRTC Session Controller JavaScript SDK provides mediaOptions, an object which specifies the types of media to request and the requirements for each type.

    A message goes out to the other party's browser plug-in.

  4. The receiver of the screen share request is alerted.

    The other party, Alice, or Bob, accepts or rejects the screen sharing request.

  5. If the request to share the screen is accepted:

    1. The screen sharing begins.

    2. Screen Sharing ends or is canceled by one or the other parties in the call. Shared screens video element is null and the shared screens close. The call continues.

    3. The call ends. Shared screens video element is null and the shared screens close.

  6. If the request to share the screen is rejected:

    The shared screen video element is null. Based on the user interface setup, the requester is prompted to close the video streaming in the user interface element. If the call session has not ended, the audio call continues.

Verifying Browser Capabilities

When the customer accesses a browser in which your application is installed, WebRTC Controller JavaScript SDK verifies that your application extension is installed.

Providing the Required User Interfaces and Event handlers

Set up your screen-sharing plug-in user interface to support the actions a customer may want to take, such as:

  • Request to share the screen.

  • Accept screen-sharing request.

  • Decline a screen-sharing request.

  • Cancel a screen-sharing request.

  • End a screen-sharing session.

Verifying the Availability of the Plug-in Interface

When the user accesses the browser where your application is installed, your application gets an alert that you configured on the plug-in user interface. Set up the logic to respond to this event.

In the excerpt in Example 3-13, WebRTC Controller JavaScript SDK gives the example application a "ping" to say that the extension is installed. In the code excerpt, extensionInstalled is set to true when the ping is received.

Example 3-13 Verifying the Availability of the Extension

// content-script sends a 'OCWSC_PING' msg if extension is installed
    if (event.data.type && (event.data.type === 'OCWSC_PING')) {
        extensionInstalled = true;
    }
 
    if(!extensionInstalled) {
        alert("Screen sharing plug-in is not installed");
    }

Providing the logic to Initiate a Screen Sharing Session

To start screen sharing with the other party in the call, the customer makes the appropriate selection based on the design of your plug-in user interface. Set up the logic to respond to this event to send the request as a message to your plug-in on the other browser.

Set up mediaOptions, an object which specifies the types of media to request and the requirements for each type. You can obtain the MediaStreamConstraints object using the getUserMedia method:

getUserMedia(constraints, successCallback, errorCallback);

For example, your application can request the audio and camera capabilities it requires. In Example 3-14 the code specifies 1280by720 for the camera resolution.

Example 3-14 Setting up the Media Options

mediaOptions = {
    audio: false,
    video: {
        mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: streamId,
            maxWidth: 1280,
            maxHeight: 720
        },
        optional: []
    }
};