Suggestions

close search

Add Messaging, Voice, and Authentication to your apps with Nexmo APIs

Visit Nexmo

OpenTok

Constructor

new OpenTok(apiKey, apiSecret)

Contains methods for creating OpenTok sessions, generating tokens, and working with archives.

To create a new OpenTok object, call the OpenTok constructor with your OpenTok API key and the API secret for your TokBox account. Do not publicly share your API secret. You will use it with the OpenTok constructor (only on your web server) to create OpenTok sessions.

Be sure to include the entire OpenTok Node.js SDK on your web server.

Parameters:
Name Type Description
apiKey String Your OpenTok API key. (See your TokBox account page.)
apiSecret String Your OpenTok API secret. (See your TokBox account page.)

Methods

Name Description
createSession(options, callback) Creates a new OpenTok session.
deleteArchive(archiveId, callback) Deletes an OpenTok archive.
dial(sessionId, token, sipUri, options) Dials a SIP gateway to input an audio-only stream into your OpenTok Session.
forceDisconnect(sessionId, connectionId, callback) Disconnects a participant from an OpenTok session.
generateToken(sessionId, options) Creates a token for connecting to an OpenTok session.
getArchive(archiveId, callback) Gets an Archive object for the given archive ID.
getBroadcast(broadcastId, callback) Returns information about a live streaming broadcast.
getStream(sessionId, options, callback) Gets info about a stream.
listArchives(options, callback) Retrieves a List of Archive objects, representing archives that are both completed and in-progress, for your API key.
listStreams(sessionId, callback) Retrieves a List of Stream objects, representing current streams in a session.
setArchiveLayout(archiveId, type, stylesheet, callback) Sets the layout type for a composed archive.
setBroadcastLayout(broadcastId, type, stylesheet, callback) Sets (or updates) the layout of the broadcast.
setStreamClassLists(sessionId, classListArray, callback) Sets the layout class list for streams in a session.
signal(sessionId, connectionId, payload, callback) Sends a signal to all the connections in a session or to a specific one.
startArchive(sessionId, options, callback) Starts archiving an OpenTok session.
startBroadcast(sessionId, options, callback) Starts a stopArchive(archiveId, callback) Stops an OpenTok archive that is being recorded.
stopBroadcast(broadcastId, callback) Stops a live streaming broadcast.

createSession(options, callback)

Creates a new OpenTok session. The session is passed as Session object into the callback function. The sessionId property is the session ID, which uniquely identifies the session. On error, an Error object is passed into the callback function.

For example, when using the OpenTok.js library, use the session ID when calling the OT.initSession() method (to initialize an OpenTok session).

OpenTok sessions do not expire. However, authentication tokens do expire (see the generateToken(String, TokenOptions) method). Also note that sessions cannot explicitly be destroyed.

A session ID string can be up to 255 characters long. You can also create a session using the OpenTok REST API or by logging in to your TokBox account.

Parameters:
Name Type Description
options Object This object defines options for the session, including the following properties (both of which are optional):
  • location (String) — An IP address that the OpenTok servers will use to situate the session in the global OpenTok network. If you do not set a location hint, the OpenTok servers will be based on the first client connecting to the session.
  • mediaMode (String) — Determines whether the session will transmit streams using the OpenTok Media Router ("routed") or not ("relayed"). By default, the setting is "relayed".

    With the mediaMode parameter set to "relayed", the session will attempt to transmit streams directly between clients. If clients cannot connect due to firewall restrictions, the session uses the OpenTok TURN server to relay audio-video streams.

    The OpenTok Media Router provides the following benefits:

  • archiveMode (String) — Whether the session is automatically archived ("always") or not ("manual"). By default, the setting is "manual", and you must call the StartArchive() method of the OpenTok object to start archiving. To archive the session (either automatically or not), you must set the mediaMode parameter to "routed".
    • The OpenTok Media Router can decrease bandwidth usage in multiparty sessions. (When the mediaMode parameter is set to "relayed", each client must send a separate audio-video stream to each client subscribing to it.)
    • The OpenTok Media Router can improve the quality of the user experience through audio fallback and video recovery. With these features, if a client's connectivity degrades to a degree that it does not support video for a stream it's subscribing to, the video is dropped on that client (without affecting other clients), and the client receives audio only. If the client's connectivity improves, the video returns.
    • The OpenTok Media Router supports the archiving feature, which lets you record, save, and retrieve OpenTok sessions.
callback function The function that is called when the operation completes. This function is passed two arguments:
  • error — On failiure, this parameter is set to an Error object. Check the error message for details. On success, this is set to null.
  • session — On sucess, this parameter is set to a Session object. The sessionId property of this object is session ID of the session. On error, this parameter is not set.

deleteArchive(archiveId, callback)

Deletes an OpenTok archive.

You can only delete an archive which has a status of "available" or "uploaded". Deleting an archive removes its record from the list of archives. For an "available" archive, it also removes the archive file, making it unavailable for download.

Parameters:
Name Type Description
archiveId String The archive ID of the archive you want to delete.
callback function The function to call upon completing the operation. On successfully deleting the archive, the function is called with no arguments passed in. On failure, an error object is passed into the function.

dial(sessionId, token, sipUri, options)

Dials a SIP gateway to input an audio-only stream into your OpenTok Session. Part of the SIP feature.
Parameters:
Name Type Description
sessionId The session ID corresponding to the session to which the user will connect.
token The token for the session ID with which the SIP user will use to connect.
sipUri The sip URI the SIP Interconnect feature will dial.
options Object An optional options object with the following properties:

  • headers (Object) — Custom headers to be added to the SIP INVITE request iniated from OpenTok to the third-party SIP platform. All headers must start with the "X-" prefix, or a Bad Request (400) will be thrown.
  • auth (Object) — The credentials to be used for HTTP Digest authentication in case this is required by the third-party SIP platform.
    • "username" -- The username to be used in the SIP INVITE.
    • "password" -- The password to be used in the SIP INVITE.
  • secure (Boolean) — Whether the SIP media streams should be transmitted encrypted or not.

Returns:
A SipInterconnect object with the following properties:
  • id -- The unique conference ID of the SIP call
  • connectionId -- The connection ID of the audio-only stream representing the SIP call
  • streamId -- The stream ID of the audio-only stream representing the SIP call

forceDisconnect(sessionId, connectionId, callback)

Disconnects a participant from an OpenTok session. This is the server-side equivalent to the forceDisconnect() method in OpenTok.js
Parameters:
Name Type Description
sessionId The session ID for the OpenTok session that the client you want to disconnect is connected to.
connectionId The connection ID of the client you want to disconnect.
callback function The function to call upon completing the operation. Two arguments are passed to the function:
  • error — An error object (if the call to the method fails).

generateToken(sessionId, options)

Creates a token for connecting to an OpenTok session. In order to authenticate a user connecting to an OpenTok session, the client passes a token when connecting to the session.

For testing, you can also generate a token by logging into your TokBox account.

Parameters:
Name Type Description
sessionId The session ID corresponding to the session to which the user will connect.
options An object that defines options for the token (each of which is optional):
  • role (String) — The role for the token. Each role defines a set of permissions granted to the token:
    • '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 role.)
    • 'moderator' — In addition to the privileges granted to a publisher, in clients using the OpenTok.js library, a moderator can call the forceUnpublish() and forceDisconnect() method of the Session object.
  • expireTime (Number) — The expiration time for the token, in seconds since the UNIX epoch. The maximum expiration time is 30 days after the creation time. If a fractional number is specified, then it is rounded down to the nearest whole number. The default expiration time of 24 hours after the token creation time.
  • data (String) — A string containing connection metadata describing the end-user.For example, you can pass the user ID, name, or other data describing the end-user. The length of the string is limited to 1000 characters. This data cannot be updated once it is set.
  • initialLayoutClassList (Array) — An array of class names (strings) to be used as the initial layout classes for streams published by the client. Layout classes are used in customizing the layout of videos in live streaming broadcasts and composed archives.
Returns:
The token string.

getArchive(archiveId, callback)

Gets an Archive object for the given archive ID.
Parameters:
Name Type Description
archiveId String The archive ID.
callback function The function to call upon completing the operation. Two arguments are passed to the function:
  • error — An error object (if the call to the method fails).
  • archive — The Archive object.

getBroadcast(broadcastId, callback)

Returns information about a live streaming broadcast.
Parameters:
Name Type Description
broadcastId String The ID of the broadcast.
callback function A callback method that takes two parameters: error, which is set to an Error object on error, and broadcast, which is set to a Broadcast object on success.

getStream(sessionId, options, callback)

Gets info about a stream. The stream must be an active stream in an OpenTok session.
Parameters:
Name Type Description
sessionId String The session ID of the OpenTok session containing the stream.
options String The stream ID.
callback function The function to call upon completing the operation. Two arguments are passed to the function:
  • error — An error object (if the call to the method fails). This is set to null if there is no error. Calling this method results in an error if you pass in an invalid stream ID or an invalid session ID.
  • stream — The Stream object. This object includes properties defining the stream. This is undefined if there is an error.

listArchives(options, callback)

Retrieves a List of Archive objects, representing archives that are both completed and in-progress, for your API key.
Parameters:
Name Type Description
options Object An options parameter with three properties:
  • count — The maximum number of archives to return. The default number of archives returned is 50 (or fewer, if there are fewer than 50 archives). The method returns a maximum of 1000 archives.
  • offset — The offset for the first archive to list (starting with the first archive recorded as offset 0). 1 is the offset of the archive that started prior to the most recent archive. This property is optional; the default is 0.
  • sessionId — Specify the id of a session in order to retrieve archives specifically for that session. This property is optional. When no sessionId is specified, then the method will return archives from any session created with your API key.

If you don't pass in an options argument, the method returns up to 1000 archives starting with the first archive recorded.

callback function The function to call upon completing the operation. Two arguments are passed to the function:
  • error — An error object (if the call to the method fails).
  • archives — An array of Archive objects.

listStreams(sessionId, callback)

Retrieves a List of Stream objects, representing current streams in a session.
Parameters:
Name Type Description
sessionId String The session ID of the OpenTok session containing the streams.
callback function The function to call upon completing the operation. Two arguments are passed to the function:
  • error — An error object (if the call to the method fails). This is set to null if there is no error. Calling this method results in an error if you pass in an invalid session ID.
  • streams — An array of Stream objects. Each Stream object includes properties defining the stream. This is undefined if there is an error.

setArchiveLayout(archiveId, type, stylesheet, callback)

Sets the layout type for a composed archive. For a description of layout types, see Customizing the video layout for composed archives.
Parameters:
Name Type Description
archiveId String The archive ID.
type String The layout type. Set this to "bestFit", "pip", "verticalPresentation", "horizontalPresentation", "focus", or "custom". For a description of these layout types, see Customizing the video layout for composed archives.
stylesheet String (Optional) The stylesheet for a custom layout. Set this parameter if you set type to "custom". Otherwise, leave it undefined or set to null.
callback function The function to call upon completing the operation. Upon error, an error object is passed into the function. Upon success, the function is called with no error object passed in.

setBroadcastLayout(broadcastId, type, stylesheet, callback)

Sets (or updates) the layout of the broadcast. See Configuring video layout for OpenTok live streaming broadcasts.
Parameters:
Name Type Description
broadcastId String The ID of the broadcast.
type String The layout type. Set this to "bestFit", "pip", "verticalPresentation", "horizontalPresentation", "focus", or "custom". For a description of these layout types, see Configuring layout for OpenTok live streaming broadcasts.
stylesheet String (Optional) The stylesheet for a custom layout. Set this parameter if you set type to "custom". Otherwise, leave it undefined or set to null.
callback function The function to call upon completing the operation. Upon error, an Error object is passed into the function. Upon success, the function is called with no Error object passed in.

setStreamClassLists(sessionId, classListArray, callback)

Sets the layout class list for streams in a session. Layout classes are used in the layout for composed archives and live streaming broadcasts. For more information, see Customizing the video layout for composed archives and Configuring video layout for OpenTok live streaming broadcasts.

You can set the initial layout class list for streams published by a client when you generate used by the client. See the OpenTok.generateToken() method.

Parameters:
Name Type Description
sessionId String The session ID of the session the streams belong to.
classListArray Array (Optional) An array defining the class lists to apply to streams. Each element in the array is an object with two properties: id and layoutClassList. The id property is the stream ID (a String), and the layoutClassList is an array of class names (Strings) to apply to the stream. Set layoutClassList to an empty array to clear the layout class list for a stream. For example, this streamClassArray array sets the layout class list for three streams:

const classListArray = [ { id: '7b09ec3c-26f9-43d7-8197-f608f13d4fb6', layoutClassList: ['focus'] }, { id: '567bc941-6ea0-4c69-97fc-70a740b68976', layoutClassList: ['top'] }, { id: '307dc941-0450-4c09-975c-705740d08970', layoutClassList: ['bottom'] } ];

callback function The function to call upon completing the operation. Upon error, an error object is passed into the function. Upon success, the function is called with no error object passed in.

signal(sessionId, connectionId, payload, callback)

Sends a signal to all the connections in a session or to a specific one.

Clients must be actively connected to the OpenTok session for you to successfully send a signal to them.

Parameters:
Name Type Description
sessionId The session ID of the OpenTok session where you want to send the signal.
connectionId The connection ID of a client connected to the session. Leave this empty if you want to send a signal to all connections in the session.
payload An object with optional signal type and signal data fields. For more information on signaling and the signal payload, see the OpenTok signaling programming guide.
callback function The callback function invoked when the call to the method succeeds or fails. If the call fails, an error object is passed into the callback function.

startArchive(sessionId, options, callback)

Starts archiving an OpenTok session.

Clients must be actively connected to the OpenTok session for you to successfully start recording an archive.

You can only record one archive at a time for a given session. You can only record archives of sessions that uses the OpenTok Media Router (sessions with the media mode set to routed); you cannot archive sessions with the media mode set to relayed.

Parameters:
Name Type Description
sessionId The session ID of the OpenTok session to archive.
options Object An optional options object with the following properties (each of which is optional):

  • name (String) — the name of the archive, which you can use to identify the archive. The name is set as a property of the Archive object, and it is a property of archive-related events in the OpenTok client libraries.
  • hasAudio (Boolean) — Whether the archive will include an audio track (true) or not (false). The default value is true (an audio track is included). If you set both hasAudio and hasVideo to false, the call to the startArchive() method results in an error.
  • hasVideo (Boolean) — Whether the archive will include a video track (true) or (not false). The default value is true (a video track is included). If you set both hasAudio and hasVideo to false, the call to the startArchive() method results in an error.
  • outputMode (String) — Whether all streams in the archive are recorded to a single file ("composed", the default) or to individual files ("individual").
  • layout (Object) — An object defining the initial layout options for a composed archive. This object has two properties, type and stylesheet, which are both strings. Set type to "bestFit", "pip", "verticalPresentation", "horizontalPresentation", or "custom". Set the stylesheet property if type is set to "custom", and set it to the stylesheet defining the custom layout. For example, set the layout object to { type: "pip" } to set the initial layout of the archive to picture-in-picture. For details, see Customizing the video layout for composed archives.
  • resolution (String) — For a composed archive, set this to the resolution of the archive. Valid values are "1280x720" or "640x480" (the default).
For more information on archiving and the archive file formats, see the OpenTok archiving programming guide.

callback function The function to call upon completing the operation. Two arguments are passed to the function:
  • error — An error object (if the call to the method fails).
  • archive — The Archive object. This object includes properties defining the archive, including the archive ID.

startBroadcast(sessionId, options, callback)

Parameters:
Name Type Description
sessionId String The ID of the session to broadcast.
options Object An object with the following form:
{
   outputs: {
     hls: {},
     rtmp: [{
       id: "foo",
       serverUrl: "rtmp://myfooserver/myfooapp",
       streamName: "myfoostream"
     },
     {
       id: "bar",
       serverUrl: "rtmp://mybarserver/mybarapp",
       streamName: "mybarstream"
     }]
   },
   maxDuration: 5400,
   resolution: "640x480"
   layout: {
     type: "custom",
     stylesheet: "the layout stylesheet (only used with type == custom)"
   },
 }

The options object includes the following properties:

  • outputs (required) — This object defines the types of broadcast streams you want to start. You can include HLS, RTMP, or both as broadcast streams. If you include RTMP streaming, you can specify up to five target RTMP streams (or just one).

    For each RTMP stream, specify serverUrl (the RTMP server URL), streamName (the stream name, such as the YouTube Live stream name or the Facebook stream key), and (optionally) id (a unique ID for the stream). If you specify an ID, it will be included as the id property of the Broadcast object passed into the callback methods of the startBroadcast() method and the OpenTok.getBroadcast() method. OpenTok streams the session to each RTMP URL you specify. Note that OpenTok live streaming does not support RTMPS.

    For HLS, include a single hls property of the outputs object. Set this property to an empty object {} (as in the example above). The HLS URL is included as the broadcastUrls.hls property of the Broadcast object passed into the callback methods of the startBroadcast() method and the OpenTok.getBroadcast() method.

  • maxDuration (optional) — The maximum duration for the broadcast, in seconds. The broadcast will automatically stop when the maximum duration is reached. You can set the maximum duration to a value from 60 (60 seconds) to 36000 (10 hours). The default maximum duration is 2 hours (7200 seconds).
  • resolution (optional) — The resolution of the broadcast: either "640x480" (SD, the default) or "1280x720" (HD).
  • layout (optional) — Specify this to assign the initial layout type for the broadcast. Valid values for the layout property are "bestFit" (best fit), "custom" (custom), "horizontalPresentation" (horizontal presentation), "pip" (picture-in-picture), and "verticalPresentation" (vertical presentation)). If you specify a "custom" layout type, set the stylesheet property of the layout object to the stylesheet. (For other layout types, do not set a stylesheet property.) If you do not specify an initial layout type, the broadcast stream uses the Best Fit layout type. For more information, see Configuring video layout for OpenTok live streaming broadcasts.

callback function A callback method that takes two parameters: error, which is set to an Error object on error, and broadcast, which is set to a Broadcast object on success.

stopArchive(archiveId, callback)

Stops an OpenTok archive that is being recorded.

Archives automatically stop recording after 120 minutes or when all clients have disconnected from the session being archived.

You cannot stop an archive that is not being recorded.

Parameters:
Name Type Description
archiveId String The archive ID of the archive you want to stop recording.
callback function The function to call upon completing the operation. Two arguments are passed to the function:
  • error — An error object (if the call to the method fails).
  • archive — The Archive object.
Returns:
The Archive object corresponding to the archive being STOPPED.

stopBroadcast(broadcastId, callback)

Stops a live streaming broadcast.
Parameters:
Name Type Description
broadcastId String The ID of the broadcast.
callback function A callback method that takes two parameters: error, which is set to an Error object on error, and broadcast, which is set to a Broadcast object on success.