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.
Each of the server-side libraries defines an OpenTokSDK class:
<dependency>
<groupId>com.opentok.api</groupId>
<artifactId>opentok-java-sdk</artifactId>
<version>[0.91.54,)</version>
</dependency>
gem 'opentok'.For additional information on each server-side library, see the appropriate project at https://github.com/opentok/.
(Switch to PHP documentation / Python documentation / Ruby documentation.)
(Switch to Java documentation / Python documentation / Ruby documentation.)
(Switch to Java documentation / PHP documentation / Ruby documentation.)
(Switch to Java documentation / PHP documentation / Python documentation.)
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 get an API key when you sign up for an OpenTok account.) 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 API_Config.php file, and the Java server-side library includes a API_Config.java file (among others).
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.
In general, you should not pass in a location hint; if no location hint is passed in, the session uses a media server based on the
location of the first client connecting to the session. Pass a location hint in only if you know the general geographic region (and a
representative IP address) and you think the first client connecting may not be in that region.
In general, you should pass in a null value as the location hint; if a null value
is passed in, the session uses a media server based on the location of the first client connecting to the session. Pass a
location hint in only if you know the general geographic region (and a representative IP address) and you think the first client
connecting may not be in that region.
properties (Object) Optional. An object used to define
peer-to-peer preferences for the session. The properties option includes the following
property:
By removing the server, peer-to-peer streaming decreases latency and improves quality.
For more information, see Peer-to-Peer Streaming.
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';
$apiObj = new OpenTokSDK(API_Config::API_KEY, API_Config::API_SECRET);
if($_REQUEST['sessionId']) {
$sessionId = $_REQUEST['sessionId'];
} else {
$session = $apiObj->create_session();
$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.
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 OpenTok ActionScript 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 urlencode($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 urlencode($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. Use the ActionScript
unescape() function to decode the token string. (The example above encodes the token string
when inserting it into the FlashVars value of the param tag. This encoding is necessary because the token string may contain
characters, such as "=", that need to be encoded for use in the FlashVars string.)
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';
$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();
?>
Here is a simple example in Java:
The following Java code example shows how to create a session and how to create a peer-to-peer session:
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().getSessionId();
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).getSessionId();
System.out.println(sessionId);
}
}
(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.
opentok_sdk = OpenTokSDK.OpenTokSDK(api_key, api_secret)
session_properties = {OpenTokSDK.SessionProperties.p2p_preference: "disabled"}
session = opentok_sdk.create_session(None, 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.)
You can also create a session using the OpenTok REST API; see Creating session IDs. For testing, you can also use the Dashboard page.
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. 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.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 30 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.
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().getSessionId());
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().getSessionId());
// 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.)
You can download videos in archives that were created using your API key.
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.
getId() method of an OpenTokArchiveVideoResource object to get the video ID (a String).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. See the OpenTok REST API Reference.