OpenTok server-side libraries reference

OpenTok server-side libraries reference

The OpenTok server-side libraries include code for your web server. Use these libraries to obtain OpenTok session IDs and to obtain validation tokens for individual users. There are versions of the OpenTok server-side libraries for Java, PHP, Python, and Ruby.

You can get the OpenTok server-side libraries at https://github.com/opentok.

OpenTokSDK object

Each of the server-side libraries defines an OpenTokSDK class:

  • The Java version defines the class in the com.opentok.api package.
  • The PHP version defines the class in the OpenTokSDK.php file.
  • The Python version defines the class in OpenTokSDK.py file.
  • The Ruby version defines the class in the OpenTokSDK.rb file (in the lib/OpenTok directory).

You need to instantiate an OpenTokSDK object before calling any of its methods.

To create a new OpenTokSDK object, call the OpenTokSDK constructor with the API key and the API secret TokBox issued you. (You can request an API key here.) Do not reveal your API secret string. You use it with the OpenTokSDK constructor (only on your web server) to create OpenTok sessions.

Be sure to include the entire OpenTok library (for a specific language) on your web server. In addition to the file defining the OpenTokSDK class, some of the libraries include other required files. For example, the PHP server-side library includes a SessionPropertyConstants.php file, and the Java server-side library includes a SessionProperties.java file (among others).

create_session() method

The create_session() method of the OpenTokSDK object to create a new OpenTok session and obtain a session ID.

The create_session() method has the following parameters:

location (String) — An IP address that TokBox will use to situate the session in its global network. Ideally, this IP address should be representative of the geographical locations of the participants in the session. If you have access to the IP address of the first participant in the session, use that address.

properties (Object) — Optional. An object used to define peer-to-peer preferences for the session. The properties option includes the following property:

  • p2p.preference (String) — Whether the session's streams will be transmitted directly between peers. You can set the following possible values:
    • "disabled" (the default) — The session's streams will all be relayed using the OpenTok servers. More than two clients can connect to the session.
    • "enabled" — The session will attempt to transmit streams directly between clients. If peer-to-peer streaming fails (either when streams are initially published or during the course of a session), the session falls back to using the OpenTok servers for relaying streams. (Peer-to-peer streaming uses UDP, which may be blocked by a firewall.) For a session created with peer-to-peer streaming enabled, only two clients can connect to the session at a time. If an additional client attempts to connect, the TB object on the client dispatches an exception event.

    By removing the server, peer-to-peer streaming decreases latency and improves quality.

    This feature is currently in beta. It was added in OpenTok v0.91.29.

Note that the properties object previously included settings for multiplexing and server-side echo suppression. However, these features were deleted in OpenTok v0.91.48. (Server-side echo suppression was replaced with the acoustic echo cancellation feature added in OpenTok v0.91.18.)

The create_session method that generates a Session object. This object includes a sessionID property, which is the session ID for the new session. For example, when using the OpenTok JavaScript library, use this session ID in JavaScript on the page that you serve to the client. The JavaScript will use this value when calling the connect() method of the Session object (to connect a user to an OpenTok session).

OpenTok sessions do not expire. However, authentication tokens do expire (see the next section on the generate_token() method.) Also note that sessions cannot explicitly be destroyed.

Note: In OpenTok v0.91.29, the length of the session ID string increased. A session ID string can be up to 255 characters long.

Calling the create_session() method results in an OpenTokException in the event of an error. Check the error message for details.

Here is a simple example in PHP:

<?php
    require_once 'SDK/API_Config.php';
    require_once 'SDK/OpenTokSDK.php';
    require_once 'SDK/SessionPropertyConstants.php';

    $apiObj = new OpenTokSDK(API_Config::API_KEY, API_Config::API_SECRET);

    if($_REQUEST['sessionId']) {
        $sessionId = $_REQUEST['sessionId'];
    } else {
        $session = $apiObj->create_session($_SERVER["REMOTE_ADDR"]);
        $sessionId = $session->getSessionId();
    }
?>

(Switch to Java documentation / Python documentation / Ruby documentation.)

This code checks to see if the session ID is already defined (for example, as a sessionId variable in the query string). Otherwise, it creates a new session, situating it in the TokBox global network near the IP as specified by $_SERVER["REMOTE_ADDR"].

In the HTML page, you then can embed PHP that references the API key, the session ID, and the generated token string, as in the following:

var apiKey = <?php print API_Config::API_KEY?>;
var sessionId = '<?php print $sessionId; ?>';
var token = '<?php print $apiObj->generate_token($sessionId); ?>';

(See the following section for information on the generate_token() method.)

You can share the URL for the session with others:

<p>Share this URL: <?php echo "http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]."?sessionId=".$sessionId; ?></p>

If you are using the OpenTokActionScript library, in the SWF-embedding code of the HTML page, you can reference the API key, the generated session ID, and the generated token string as Flash variables (FlashVars). The following shows how to use PHP to pass values as Flash variables:

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="770" height="500" id="MyApp">
    <param name="movie" value="MyApp.swf">
    <param name="quality" value="high">
    <param name="bgcolor" value="#ffffff">
    <param name=FlashVars value="apiKey=<?php print API_Config::API_KEY?>&sessionId=<?php print $sessionId; ?>'&token=<?php print $apiObj->generate_token($sessionId); ?>">

    <param name="allowScriptAccess" value="sameDomain">
    <param name="allowFullScreen" value="true">
    <!--[if !IE]>-->
    <object type="application/x-shockwave-flash" data="MyApp.swf" width="770" height="500">
        <param name="quality" value="high">
        <param name="bgcolor" value="#ffffff">
        <param name=FlashVars value="apiKey=<?php print API_Config::API_KEY?>&sessionId=<?php print $sessionId; ?>'&token=<?php print $apiObj->generate_token($sessionId); ?>">
		<param name="allowScriptAccess" value="sameDomain">
        <param name="allowFullScreen" value="true">
        <!--<![endif]-->
        <!--[if gte IE 6]>-->
        <p>
            Either scripts and active content are not permitted to run or Adobe Flash Player version 10.0.0 or greater is not installed.
        </p><!--<![endif]-->
        <a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player"></a> <!--[if !IE]>-->
    </object> <!--<![endif]-->
</object>

For this example, the ActionScript code in the SWF file would reference the apiKey, sessionId, and token properties passed in as Flash variables.

Here is an advanced example in PHP that creates a new session with peer-to-peer streaming enabled:

<?php
    require_once 'SDK/API_Config.php';
    require_once 'SDK/OpenTokSDK.php';
    require_once 'SDK/SessionPropertyConstants.php';

    $apiObj = new OpenTokSDK(API_Config::API_KEY, API_Config::API_SECRET);

    $session = $apiObj->create_session($_SERVER["REMOTE_ADDR"], 
        array(SessionPropertyConstants::P2P_PREFERENCE=>"enabled"));
    echo $session->getSessionId();
?>

The client-side code can call the getGroupProperties() method of a Group object to get the properties of a group. (In the current version, there is one group per session, and the session properties apply to that group.) For more information, see the documentation for the OpenTok JavaScript library Group class.

Here is a simple example in Java:

The following Java code example shows how to create a session and how to create a session using a location hint and optional properties:

import com.opentok.api.API_Config;
import com.opentok.api.OpenTokSDK;
import com.opentok.api.constants.SessionProperties;
import com.opentok.exception.OpenTokException;

class Test {
    public static void main(String argv[]) throws OpenTokException {
        // Set the following constants with the API key and API secret
        // that you receive when you sign up to use the OpenTok API:
        OpenTokSDK sdk = new OpenTokSDK(API_Config.API_KEY, API_Config.API_SECRET);

        //Generate a basic session
        String sessionId = sdk.create_session().session_id;
        System.out.println(sessionId);

        //Generate Session Properties for a session
        SessionProperties sp = new SessionProperties();
        sp.p2p_preference = "enabled";

        //Generate a session with a location hint and session properties
        String sessionId = sdk.create_session("192.0.43.10", sp).sessionId;
        System.out.println(session_id);
    }
}

(Switch to PHP documentation / Python documentation / Ruby documentation.)

Here is a simple example in Python:

import OpenTokSDK

api_key = "your_API_key"        # Replace with your OpenTok API key.
api_secret = "your_API_secret"  # Replace with your OpenTok API secret.
session_address = "192.0.43.10" # Replace with the representative URL of your session.

opentok_sdk = OpenTokSDK.OpenTokSDK(api_key, api_secret)

session_properties = {OpenTokSDK.SessionProperties.p2p_preference: "disabled"}

session = opentok_sdk.create_session(session_address, session_properties)

print session.session_id

(Switch to Java documentation / PHP documentation / Ruby documentation.)

Here is a simple example in Ruby:

class SampleController < ApplicationController
    def action
        api_key = "your_API_key"        # Replace with your OpenTok API key.
        api_secret = "your_API_secret"  # Replace with your OpenTok API secret.

        opentok = OpenTok::OpenTokSDK.new api_key, api_secret 
        session_properties = {OpenTok::SessionPropertyConstants::P2P_PREFERENCE => "disabled"}
        session = opentok.create_session request.remote_addr, session_properties
    end
end

(Switch to Java documentation / PHP documentation / Python documentation.)

generate_token() method

In order to authenticate a user connecting to a OpenTok session, a user must pass an authentication token along with the API key.

The method takes has the following parameters:

session_id (String) — The session ID corresponding to the session to which the user will connect.

role (String) — Optional. Added in OpenTok v0.91.5. Each role defines a set of permissions granted to the token. Valid values are defined in the RoleConstants class in the server-side SDKs:

  • SUBSCRIBER — A subscriber can only subscribe to streams.
  • PUBLISHER — A publisher can publish streams, subscribe to streams, and signal. (This is the default value if you do not specify a value for the role parameter.)
  • MODERATOR — In addition to the privileges granted to a publisher, a moderator can call the forceUnpublish() and forceDisconnect() method of the Session object.

If you are using a version of OpenTok prior v0.91.5, do not pass a value for the role parameter (or pass a null value).

expire_time (int) — Optional. The time when the token will expire, defined as an integer value for a Unix timestamp (in seconds). If you do not specify this value, tokens expire in 24 hours after being created. The expiration_time value, if specified, must be within seven days of the creation time.

connection_data (String) — Optional. A string containing metadata describing the connection. For example, you can pass the user ID, name, or other data describing the connection. The length of the string is limited to 1000 characters.

Note: In the staging environment, when using a test token string (such as 'devtoken'), pass the data string to the connect() method of the Session object in the client-side code. (See the connect() method in the Session class documentation.)

Added in OpenTok v0.91.20.

Calling the generate_token() method returns a string. This string is the token string.

The following PHP code example shows how to obtain a token:

<?PHP

require_once 'OpenTokSDK.php';

$a = new OpenTokSDK(API_Config::API_KEY,API_Config::API_SECRET);
print $a->generate_token('your_session_ID'); // Replace with the correct session ID
print "\n";

The following PHP code example shows how to obtain a token that has a role of "publisher" and that has a connection metadata string:

<?PHP

require_once 'OpenTokSDK.php';

$a = new OpenTokSDK(API_Config::API_KEY,API_Config::API_SECRET);
$connectionMetaData = "username=Bob,userLevel=4"; // Replace with meaningful metadata for the connection.
print $a->generate_token('your_session_ID', RoleConstants::PUBLISHER, null, $connectionMetaData); // Replace with the correct session ID
print "\n";

(Switch to Java documentation / Python documentation / Ruby documentation.)

You use server-side PHP code to include the token ID in the served web page.

The following Java code example shows how to obtain a token:

import com.opentok.api.API_Config;
import com.opentok.api.OpenTokSDK;
import com.opentok.exception.OpenTokException;

class Test {
	public static void main(String argv[]) throws OpenTokException {
		// Set the following constants with the API key and API secret
        // that you receive when you sign up to use the OpenTok API:
		OpenTokSDK sdk = new OpenTokSDK(API_Config.API_KEY, API_Config.API_SECRET);

		//Generate a basic session. Or you could use an existing session ID.
		String sessionId = System.out.println(sdk.create_session().session_id);

		String token = sdk.generate_token(sessionId);
		System.out.println(token);
	}
}

The following Java code example shows how to obtain a token that has a role of "publisher" and that has a connection metadata string:

import com.opentok.api.API_Config;
import com.opentok.api.OpenTokSDK;
import com.opentok.api.constants.RoleConstants;
import com.opentok.exception.OpenTokException;

class Test {
	public static void main(String argv[]) throws OpenTokException {
		// Set the following constants with the API key and API secret
        // that you receive when you sign up to use the OpenTok API:
		OpenTokSDK sdk = new OpenTokSDK(API_Config.API_KEY, API_Config.API_SECRET);

		//Generate a basic session. Or you could use an existing session ID.
		String sessionId = System.out.println(sdk.create_session().session_id);

		// Replace with meaningful metadata for the connection.
		String connectionMetadata = "username=Bob,userLevel=4";

		// Generate a token. Use the RoleConstants value appropriate for the user.
		String token = sdk.generate_token(sessionId, RoleConstants.PUBLISHER, null, connectionMetadata);
		System.out.println(token);
	}
}

(Switch to PHP documentation / Python documentation / Ruby documentation.)

The following Python code example shows how to obtain a token:

import OpenTokSDK

api_key = "your_API_key"        # Replace with your OpenTok API key.
api_secret = "your_API_secret"  # Replace with your OpenTok API secret.
session_address = "192.0.43.10" # Replace with the representative URL of your session.

opentok_sdk = OpenTokSDK.OpenTokSDK(api_key, api_secret)
session = opentok_sdk.create_session(session_address)
token = opentok_sdk.generate_token(session.session_id)
print token

The following Python code example shows how to obtain a token that has a role of "publisher" and that has a connection metadata string:

import OpenTokSDK

api_key = "your_API_key"        # Replace with your OpenTok API key.
api_secret = "your_API_secret"  # Replace with your OpenTok API secret.
session_address = "192.0.43.10" # Replace with the representative URL of your session.

opentok_sdk = OpenTokSDK.OpenTokSDK(api_key, api_secret)
role_constants = OpenTokSDK.RoleConstants

session = opentok_sdk.create_session(session_address)
connectionMetadata = "username=Bob,userLevel=4"
token = opentok_sdk.generate_token(session.session_id, role_constants.PUBLISHER, None, connectionMetadata)
print token

(Switch to Java documentation / PHP documentation / Ruby documentation.)

The following Ruby code example shows how to obtain a token:

class SampleController < ApplicationController
    def action
        api_key = "your_API_key"        # Replace with your OpenTok API key.
        api_secret = "your_API_secret"  # Replace with your OpenTok API secret.

        opentok = OpenTok::OpenTokSDK.new api_key, api_secret 
        session = opentok.create_session request.remote_addr 

        token = opentok.generate_token :session_id => @session
    end
end

The following Ruby code example shows how to obtain a token that has a role of "publisher" and that has a connection metadata string:

class SampleController < ApplicationController
    def action
        api_key = "your_API_key"        # Replace with your OpenTok API key.
        api_secret = "your_API_secret"  # Replace with your OpenTok API secret.

        opentok = OpenTok::OpenTokSDK.new api_key, api_secret
        session = opentok.create_session request.remote_addr

        token = opentok.generate_token :session_id => session, :role => OpenTok::RoleConstants::PUBLISHER, :connection_data => "username=Bob,level=4"
    end
end

(Switch to Java documentation / PHP documentation / Python documentation.)

Before you launch your site, you can use the the staging environment without generating authentication tokens:

  • You can use the generic string 'devtoken' or 'moderator_token' in place of a proper server-generated token. (The 'moderator_token' string was added in OpenTok v0.91.5.) You can also use a server-generated token. You will receive errors if the token is invalid for the session.
  • Load the OpenTok JavaScript library from the following URL: <script src="http://staging.tokbox.com/v0.91/js/TB.min.js"></script>.

Important: Use the staging environment for testing only. The OpenTok staging server is not intended for production environments.

When you launch your site, you will need to switch to the production server:

  • Register your app with Tokbox. See the Launch page.
  • Use the OpenTokSDK.generate_token() method to obtain a unique token string for each user.
  • Switch your app to use the production server:

    Load the OpenTok JavaScript library from the following URL: <script src="http://static.opentok.com/v0.91/js/TB.min.js"></script>.

    ActionScript developers: Compile your app using the production version of the opentok.swc file. See the ActionScript 3 Code Resources page.

    iOS developers: Set the environment by using the [OTSession initWithSessionId:delegate:environment:] message.

  • Set the the API_URL constant in the server-side library to "https://api.opentok.com/hl".

POSTing directly to the OpenTok API to obtain session IDs

In the production environment, you can obtain a new session by submitting a POST request to the following URL:

https://api.opentok.com/hl/session/create

In production, API calls must be authenticated using a custom HTTP header: X-TB-PARTNER-AUTH. Send your API key and partner secret concatenated with a colon:

X-TB-PARTNER-AUTH: <api_key>:<partner_secret>

In other words, the POST request will have the following form:

POST /hl/session/create HTTP/1.1
host: api.opentok.com
X-TB-PARTNER-AUTH: api_key/partner_secret

To call the function from the command line, you could issue a command like the following:

export TB_url=https://api.opentok.com/hl/session/create
curl -d "api_key=api_key&location=IP_ADDRESS"  -H "X-TB-PARTNER-AUTH: API_KEY:API_SECRET" $TB_url

(Replace the API_KEY and API_SECRET with the API key and partner secret provided to you when you registered to use the OpenTok API. Replace IP_ADDRESS with an IP address that is representative of the geographical location for the session.)

In the sandbox environment, you can obtain a new session by browsing to a form at the following URL, or by submitting a POST request:

https://staging.tokbox.com/hl/session/create

For the sandbox environment, you do not need to authenticate to obtain new session IDs.

The response is XML data of the following form:

<Sessions>
  <Session>
    <session_id>SESSION_IDlt;/session_id>
    <partner_id>API_KEY</partner_id>
    <create_dt>DATE</create_dt>
    <session_status></session_status>
  </Session>
</Sessions>

Downloading archive videos

You can download videos in archives that were created using your API key.

  1. Create a token that has been assigned the role of moderator. See the generate_token() method.
  2. Call the get_archive_manifest() method of the OpenTokSDK object in the OpenTok server-side SDK. This method takes two parameters. The first parameter is the archive ID of the archive that contains the video (a String). The second parameter is the token (a String)

    The method returns an OpenTokArchive object. The resources property of this object is an array of OpenTokArchiveVideoResource objects. Each OpenTokArchiveVideoResource object represents a video in the archive.

  3. Call the getId() method of an OpenTokArchiveVideoResource object to get the video ID (a String).
  4. Call the downloadArchiveURL() method of the OpenTokArchive object. This method takes one argument: the video ID. The method returns a download URL for the video. OpenTok archive video files are FLV files.

You can also download archive videos using a RESTful web service:

  1. Create a token that has been assigned the role of moderator. See the generate_token() method.
  2. Download the archive manifest file by calling one of the following URLs:

    https://staging.tokbox.com/hl/archive/getmanifest/archive_ID (for archives created in staging)

    https://api.opentok.com/hl/archive/getmanifest/archive_ID (for archives created in production)

    Where archive_ID is the archive ID of the archive you are interested in. Include the token string as an x-tb-token-auth variable in the HTTP header data. (You should save a record of the archive ID when you create an archive using the OpenTok JavaScript API. For example, the Session object or dispatches an archiveCreated event when an archive is created. For stand-alone archives, the Recorder object dispatches an archiveSaved event when the archive is saved. See the Session.createArchive() method and the Recorder class.)

    The result of the RESTful API call is an archive manifest file. This is an XML file that describes the videos included in the archive. (A per-session archive may include multiple videos, whereas a per-stream and individual archives each include only one video.) The videos are defined in video sub-elements of the resources element. For example, the following manifest XML defines an archive that includes one video, which has the ID "125f0b49-e452-4b61-ade5-2f4589ade4cb" and the stream name "Bob":

    <manifest version="0.1" archiveid="340ded4d-a587-4ca0-b92a-ef86b6997fc7" title="archive1318034901141">
        <resources>
            <video id="125f0b49-e452-4b61-ade5-2f4589ade4cb" length="8687" name="Bob" />
        </resources>
        <timeline>
            <event type=”PLAY” id="125f0b49-e452-4b61-ade5-2f4589ade4cb" offset="0" />
        </timeline>
    </manifest>
    
  3. Note: For archives created prior to OpenTok v0.91.48, the stream name in the archive manifest is always set to an empty string.

  4. Download the video file by calling one of the following URLs:

    https://staging.tokbox.com/hl/archive/url/archive_ID/video_id (for archives created in staging)

    https://api.opentok.com/hl/archive/url/archive_ID/video_id (for archives created in production)

    Where archive_ID is the archive ID of the archive, and video_id is the video ID (which you obtained from the archive manifest XML data). Include the token string as an x-tb-token-auth variable in the HTTP header data.

    Note: You can use different tokens to download the archive manifest and to download the FLV file. However each token must be created with the API key that was used to create the archive, and each token must include the moderator role.

    The result of the RESTful API call is the video file. OpenTok archive video files are FLV files.

Deleting archives

You can delete archives that were created using your API key. The archive video delete feature is implemented as a RESTful web service.

To delete an OpenTok archive:

  1. Create a token that has been assigned the role of moderator. See the generate_token() method.
  2. Call one of the following URLs:

    https://staging.tokbox.com/hl/archive/delete/archive_ID (for archives created in staging)

    https://api.opentok.com/hl/archive/delete/archive_ID (for archives created in production)

    Where archive_ID is the archive ID of the archive you want to delete. Include the token string as an x-tb-token-auth variable in the HTTP header data. (You should save a record of the archive ID when you create an archive using the OpenTok JavaScript API. For example, the Session object or dispatches an archiveCreated event when an archive is created. For stand-alone archives, the Recorder object dispatches an archiveSaved event when the archive is saved. See the Session.createArchive() method and the Recorder class.)

    The HTTP response status code for the call will be one of the following:

    HTTP response status code Description
    200 Success, the archive is deleted.
    404 Archive not found, returned in the following cases:
    • The archive does not exist. (Perhaps it was already deleted, or it was never created.)
    • The archive exists, but it is associated with a different API key.
    • The archive exists, but you are using a token that has not been assigned a moderator role.
    500 Error on the TokBox server. Perhaps the service is unavailable.

    IRC Live Chat

    Have a quick question? Chat with other developers.  Join chat

    TokBox staff may not be online right now. To reach them during off-hours, visit the forums.