• This repository has been archived on 25/Nov/2022
  • Stars
    star
    107
  • Rank 323,587 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 8 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React components for OpenTok.js

⚠️ This repository is now deprecated ⚠️



Please consider using OpenTok Web Components instead.



An example React project can be found here








opentok-react

npm version Build Status

React components for OpenTok.js

Contents

Pre-Requisites

  1. NodeJS
  2. Register a TokBox account: https://tokbox.com/account/user/signup

Install

Add opentok-react as a dependency of your application:

yarn add opentok-react

Or if you're still using npm:

npm install --save opentok-react

Then include opentok.js before your application:

<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>

Alternatively, wrap your top-level component using OpenTok with the preloadScript HOC. The HOC will take care of loading opentok.js for you before rendering.

Example App

There is an example application provided in example/ and you can run it with the following steps:

  1. git clone https://github.com/opentok/opentok-react.git
  2. cd opentok-react/example/
  3. cp config.template.js config.js
  4. Edit config.js:
  5. Add your OpenTok API key, Session ID and Token (https://tokbox.com/account/)
  6. Add your Chrome Extension ID (https://tokbox.com/developer/guides/screen-sharing/js/)
  7. cd ..
  8. yarn (or npm install)
  9. npm run example
  10. Visit http://localhost:8000 in your browser

Refer to the App.js, Publisher.js and Subscriber.js files in example/components/ for library usage.

Usage

The following sections explains how to import and use opentok-react in your React application.

Importing opentok-react

Import the opentok-react components into your React application:

import { OTSession, OTPublisher, OTStreams, OTSubscriber } from 'opentok-react';

Or require it if you need to use CommonJS modules:

const { OTSession, OTPublisher, OTStreams, OTSubscriber } = require('opentok-react');

Example with OTSession Component

class MyApp extends React.Component {
  render() {
    return (
      <OTSession apiKey="your-api-key" sessionId="your-session-id" token="your-session-token">
        <OTPublisher />
        <OTStreams>
          <OTSubscriber />
        </OTStreams>
      </OTSession>
    );
  }
}

Example with createSession Helper

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { streams: [] };
  }

  componentWillMount() {
    this.sessionHelper = createSession({
      apiKey: 'your-api-key',
      sessionId: 'your-session-id',
      token: 'your-session-token',
      onStreamsUpdated: streams => { this.setState({ streams }); }
    });
  }

  componentWillUnmount() {
    this.sessionHelper.disconnect();
  }

  render() {
    return (
      <div>
        <OTPublisher session={this.sessionHelper.session} />

        {this.state.streams.map(stream => {
          return (
            <OTSubscriber
              key={stream.id}
              session={this.sessionHelper.session}
              stream={stream}
            />
          );
        })}
      </div>
    );
  }
}

API Reference

The opentok-react library comprises of:

  • OTSession Component
  • OTPublisher Component
  • OTStreams Component
  • OTSubscriber Component
  • createSession Helper
  • preloadScript Higher-Order Component

OTSession Component

Prop Type Required Description
apiKey String Yes TokBox API Key
sessionId String Yes TokBox Session ID
token String Yes TokBox token
options Object No TokBox options options
eventHandlers Object<Function> No Event handlers passed into session.on
onConnect Function() No Invoked when session.connect successfully completes
onError Function(err) No Invoked when session.connect fails

The OTSession component manages the connection to an OpenTok Session. It passes the Session instance as the session prop to its child components. It is recommended that you nest OTPublisher and OTStreams inside OTSession:

<OTSession apiKey="your-api-key" sessionId="your-session-id" token="your-session-token">
  <OTPublisher />
  <OTStreams>
    <OTSubscriber />
  </OTStreams>
</OTSession>

OTPublisher Component

Prop Type Required Description
session Session No OpenTok Session instance. This is auto populated by wrapping OTPublisher with OTSession
properties Object No Properties passed into OT.initPublisher
eventHandlers Object<Function> No Event handlers passed into publisher.on
onInit Function() No Invoked when OT.initPublisher successfully completes
onPublish Function() No Invoked when session.publish successfully completes
onError Function(err) No Invoked when either OT.initPublisher or session.publish fail

The OTPublisher component will initialise a publisher and publish to a specified session upon mounting. It will also ensure the Publisher video element is attached to the DOM inside the component rather than appending to the body (which is the Publisher's default behaviour).

<OTSession apiKey="your-api-key" sessionId="your-session-id" token="your-session-token">
  <OTPublisher />
</OTSession>

If you are not using OTSession then you must specify a Session object using the session prop.

<OTPublisher session={this.sessionHelper.session} />

Use the properties prop to specify a properties object for OT.initPublisher and the eventHandlers prop to specify an object of event handlers for Publisher#on.

class MyApp extends React.Component {
  constructor(props) {
    super(props);

    this.publisherProperties = {
      audioFallbackEnabled: false,
      showControls: false
    };

    this.publisherEventHandlers = {
      streamCreated: event => {
        console.log('Publisher stream created!');
      },
      streamDestroyed: event => {
        console.log('Publisher stream destroyed!');
      }
    };
  }

  render() {
    return (
      <OTSession apiKey="your-api-key" sessionId="your-session-id" token="your-session-token">
        <OTPublisher
          properties={this.publisherProperties}
          eventHandlers={this.publisherEventHandlers}
        />
      </OTSession>
    );
  }
}

The properties prop is used for initial set up of the Publisher and making changes to it will not update the Publisher, you will instead need to invoke Publisher methods. To facilitate this the Publisher instance is exposed via the getPublisher() component method. You should always call this method to get the latest Publisher instance instead of keeping a reference to it as it's possible for the Publisher instance to change, leaving you with a stale reference.

However, for convenience the OTPublisher does watch for changes on a few keys of the properties object and makes the necessary changes. Currently these are:

Publisher Property Action
videoSource Destroys and recreates the Publisher with the new video source. This is the only way to change the video source of a Publisher. This is used in the example application to allow the user to toggle between publishing their camera and publishing their screen
publishAudio Calls publisher.publishAudio() to toggle audio on and off
publishVideo Calls publisher.publishVideo() to toggle video on and off

There are plans to support more Publisher properties but for now you will have to call getPublisher() to retrieve the Publisher instance and make the necessary changes yourself.

You can also get access to the publisher object by calling the getPublisher method using a Ref. For example:

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      publisher: null,
    };
    this.otPublisher = React.createRef();
  }

  componentDidMount() {
    this.getPublisher();
  }

  getPublisher() {
    if (this.otPublisher) {
      this.setState({
        publisher: this.otPublisher.current.getPublisher(),
      });
    }
  }

  render() {
    return (
      <OTSession apiKey="your-api-key" sessionId="your-session-id" token="your-session-token">
        <OTPublisher
          ref={this.otPublisher}
        />
      </OTSession>
    );
  }
}

OTStreams Component

Prop Type Required Description
children ReactElement Yes Must have a single child component that accepts session and stream props, eg. OTSubscriber
session Session Yes OpenTok Session instance. This is auto populated by wrapping OTStreams with OTSession
streams Array<Stream> No Array of OpenTok Stream instances. This is auto populated by wrapping OTStreams with OTSession

OTSubscriber Component

Prop Type Required Description
session Session No OpenTok Session instance. This is auto populated by wrapping OTSubscriber with OTStreams
stream Stream No OpenTok Stream instance. This is auto populated by wrapping OTSubscriber with OTStreams
properties Object No Properties passed into session.subscribe
retry Boolean No Set true to retry the subscribe process in case of failure (Default: false)
maxRetryAttempts Number No Max retry attempts in case of subscribe failure (Default: 5)
retryAttemptTimeout Number No Timeout value between every subscribe retry attempt, expressed in ms (Default: 1000ms)
eventHandlers Object<Function> No Event handlers passed into subscriber.on
onSubscribe Function() No Invoked when session.subscribe successfully completes
onError Function(err) No Invoked when session.subscribe fails

The OTSubscriber component will subscribe to a specified stream from a specified session upon mounting. It will also ensure the Subscriber video element is attached to the DOM inside the component rather than appending to the body (which is the Subscriber's default behaviour).

<OTStreams>
  <OTSubscriber />
</OTStreams>

If you are not using OTStreams then you must provide a Stream object using the stream prop and a Session object using the session prop.

{this.sessionHelper.streams.map(stream => (
  <OTSubscriber
    key={stream.id}
    session={this.sessionHelper.session}
    stream={stream}
  />
))}

Use the properties prop to specify a properties object for session.subscribe and the eventHandlers prop to specify an object of event handlers for Subscriber#on.

class MyApp extends React.Component {
  constructor(props) {
    super(props);

    this.subscriberProperties = {
      preferredFrameRate: 15,
      showControls: false
    };

    this.subscriberEventHandlers = {
      videoDisabled: event => {
        console.log('Subscriber video disabled!');
      },
      videoEnabled: event => {
        console.log('Subscriber video enabled!');
      }
    };
  }

  render() {
    return (
      <OTSession apiKey="your-api-key" sessionId="your-session-id" token="your-session-token">
        <OTStreams>
          <OTSubscriber
            properties={this.subscriberProperties}
            eventHandlers={this.subscriberEventHandlers}
          />
        </OTStreams>
      </OTSession>
    );
  }
}

The properties prop is used for initial set up of the Subscriber and making changes to it will not update the Subscriber, you will instead need to invoke Subscriber methods. To facilitate this the Subscriber instance is exposed via the getSubscriber() component method. You should always call this method to get the latest Subscriber instance instead of keeping a reference to it as it's possible for the Subscriber instance to change, leaving you with a stale reference.

However, for convenience the OTSubscriber does watch for changes on a few keys of the properties object and makes the necessary changes. Currently these are:

Subscriber Property Action
subscribeToAudio Calls subscriber.subscribeToAudio() to toggle audio on and off
subscribeToVideo Calls subscriber.subscribeToVideo() to toggle video on and off

There are plans to support more Subscriber properties but for now you will have to call getSubscriber() to retrieve the Subscriber instance and make the necessary changes yourself.

You can also get access to the subscriber object by calling the getSubscriber method using a Ref. For example:

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      subscriber: null,
    };
    this.otSubscriber = React.createRef();
  }

  componentDidMount() {
    this.getSubscriber();
  }

  getSubscriber() {
    if (this.otSubscriber) {
      this.setState({
        subscriber: this.otSubscriber.current.getSubscriber(),
      });
    }
  }

  render() {
    return (
      <OTSession apiKey="your-api-key" sessionId="your-session-id" token="your-session-token">
        <OTStreams>
          <OTSubscriber
            ref={this.otSubscriber}
          />
        </OTStreams>
      </OTSession>
    );
  }
}

createSession Helper

The createSession helper has been provided to easily create a session and monitor the current list of subscriber streams.

class MyApp extends React.Component {
  componentWillMount() {
    this.sessionHelper = createSession({
      apiKey: 'your-api-key',
      sessionId: 'your-session-id',
      token: 'your-session-token',
      onStreamsUpdated: streams => {
        console.log('Current subscriber streams:', streams);
      }
    });
  }

  componentWillUnmount() {
    this.sessionHelper.disconnect();
  }
}

The createSession helper returns an object with the following properties:

  • session - The Session instance.
  • streams - An up-to-date array of Stream instances.
  • disconnect - A clean up function. Call this when your component unmounts.

Use of this helper is optional and you can instead use the OTSession component or directly call OT.initSession and listen to streamCreated events if you prefer.

preloadScript Higher-Order Component

Prop Type Required Description
opentokClientUrl String No The URL of the OpenTok client script to load. It defaults to https://static.opentok.com/v2/js/opentok.min.js.
loadingDelegate ReactElement No An element that will be displayed while the OpenTok client script is loading. It defaults to an empty <div />.

In larger applications, one might not want to load the opentok.js client with a <script> tag all the time. The preloadScript higher-order component will do this for you at the appropriate time.

For example, imagine you have a React Router application with the following route structure:

<Router>
  <Route path="/">
    <IndexRoute component="..." />
    <Route path="something" component="..." />
    <Route path="video" component={VideoChat} />
    <Route path="something-else" component="..." />
  </Route>
</Router>

What you'd like to do is delay the loading of opentok.js until the VideoChat component is being used. Here's how you can do this:

class VideoChat extends React.Component {
  // All the code of your component
}

export default preloadScript(App);

Custom Build

  1. git clone https://github.com/opentok/opentok-react.git
  2. cd opentok-react/
  3. yarn (or npm install)
  4. Modify code in src/
  5. npm run build
  6. Check that files in dist/ have been updated.

Contributing

If you make changes to the project that you would like to contribute back then please follow the contributing guidelines. All contributions are greatly appreciated!

Tests

Run the unit tests locally with the following command:

npm run unit

By default this will launch the Chrome browser. To run tests in Firefox use:

npm run unit -- --browsers Firefox

Run the linter with:

npm run lint

The unit tests are automatically run on Travis on both Chrome and Firefox and the current build status is shown at the top of this document.

About

Originally authored by Aiham Hammami. Currently maintained by OpenTok Engineers and community members. Please note that this is not officially supported by TokBox.

More Repositories

1

opentok-android-sdk-samples

Sample applications illustrating best practices using OpenTok Android SDK.
Java
211
star
2

opentok-react-native

OpenTok React Native - a library for OpenTok iOS and Android SDKs
Swift
211
star
3

opentok-ios-sdk-samples

Example applications that use the OpenTok iOS SDK
Objective-C
200
star
4

opentok-web-samples

Sample applications for using OpenTok.js
JavaScript
196
star
5

opentok-node

OpenTok Server SDK for node.js
JavaScript
165
star
6

OpenTok-PHP-SDK

OpenTok PHP Server SDK
PHP
140
star
7

opentok-ios-sdk-samples-swift

Sample applications using the OpenTok iOS SDK in Swift
Swift
136
star
8

opentok-network-test

Sample app to test network connectivity and statistics (bps, packet-lost)
Objective-C
111
star
9

CallKit

A sample app to demonstrate how to integrate Apple CallKit into OpenTok iOS SDK
Objective-C
110
star
10

OpenTok-Ruby-SDK

OpenTok Server SDK for Ruby
Ruby
110
star
11

opentok-rtc

OpenTok demo application
JavaScript
106
star
12

one-to-one-sample-apps

DEPRECATED: OpenTok One-to-One Communication Sample App
JavaScript
99
star
13

screensharing-extensions

Sample code for developing an OpenTok screen-sharing extension for Google Chrome and Firefox
HTML
80
star
14

Opentok-Python-SDK

OpenTok Python SDK
Python
73
star
15

Opentok-.NET-SDK

Official .NET Server SDK for OpenTok
C#
57
star
16

opentok-network-test-js

A node module that lets you check network connectivity to resources and services required to use OpenTok
TypeScript
57
star
17

broadcast-sample-app

OpenTok Broadcast Sample Application
JavaScript
54
star
18

opentok-react-native-samples

Sample applications using OpenTok and React Native
Java
52
star
19

accelerator-sample-apps-js

CSS
35
star
20

archiving-composer

Sample apps for using OpenTok archiving building blocks API and ffmpeg to generate composed files from individual archives
JavaScript
31
star
21

accelerator-core-ios

Syntax sugar of OpenTok iOS SDK with Audio/Video communication including screen sharing
Objective-C
31
star
22

learning-opentok-web

JavaScript
27
star
23

Opentok-Java-SDK

OpenTok Server SDK for Java
Java
26
star
24

learning-opentok-ios

Sample code for learning how to use the OpenTok iOS SDK
Objective-C
26
star
25

accelerator-core-js

Accelerator Core provides a simple way to integrate real-time audio/video into your web application using the OpenTok Platform
JavaScript
25
star
26

learning-opentok-php

PHP
25
star
27

learning-opentok-android

Java
25
star
28

opentok-video-call-center

Sample code for building a basic agent queuing system
Vue
20
star
29

opentok-elearning-samples

Sample applications highlighting integrations between OpenTok and Learning Management Systems (LMS)
JavaScript
19
star
30

opentok-linux-sdk-samples

OpenTok Linux SDK Samples
C++
16
star
31

web-components

Web Components to be used with OpenTok video
JavaScript
16
star
32

ARKitSample

Sample App using ARKit Apple framework
Swift
16
star
33

accelerator-screen-sharing-js

Accelerator Screen Sharing JS provides an easy way to get started in implementing interoperable screen sharing using the OpenTok platform.
JavaScript
16
star
34

opentok-hardware-setup.js

JavaScript
14
star
35

interactive-broadcast-js

JavaScript
13
star
36

accelerator-textchat-ios

OpenTok Text Chat Accelerator Pack enables text messages between mobile or browser-based devices.
Objective-C
13
star
37

learning-opentok-node

A sample app of OpenTok Node Server SDK
JavaScript
13
star
38

opentok-flutter-basic-video-chat

Kotlin
11
star
39

ARFrameMetadata

Sample application using the Frame Meta Data API on iOS with ARKit
Swift
10
star
40

opentok-webinar

Simple Webinar (1 to many broadcast) application powered by OpenTok WebRTC SDKs https://tokinar.herokuapp.com/
JavaScript
10
star
41

accelerator-sample-apps-ios

A comprehensive sample app built by OpenTok Accelerator Packs
Objective-C
10
star
42

json2code

Code generator for JSON serialization and deserialization on iOS and Android based on json schema
Java
9
star
43

opentok-windows-sdk-samples

Sample applications illustrating best practices using OpenTok Windows SDK
C#
9
star
44

accelerator-core-android

An easy way to integrate OpenTok SDK to any Android applications
Java
8
star
45

opentok-reconnection

Sample app to illustrate how reconnection feature works.
Java
7
star
46

insights-dashboard-sample

Sample React app utilizing the OpenTok Insights GraphQL API
JavaScript
6
star
47

accelerator-textchat-js

Accelerator Text Chat JS provides functionality you can add to your OpenTok applications that enables users to exchange text messages between mobile or browser-based devices.
JavaScript
6
star
48

opentok-archive-transcription-demo

Sample code for transcribing OpenTok video archives to text
JavaScript
5
star
49

interactive-broadcast-api

JavaScript
5
star
50

ux-components

Reusable React Components for TokBox
TypeScript
5
star
51

opentok-nexmo-sip

OpenTok SIP Interconnect samples with Nexmo Voice API
JavaScript
5
star
52

accelerator-sample-apps-android

A sample app built by OpenTok Accelerator Packs
Kotlin
4
star
53

accelerator-annotation-android

Java
4
star
54

interactive-broadcast-android

Java
3
star
55

accelerator-annotation-js

JavaScript
2
star
56

misc-opentok-accelerators

DEPRECATED: Old versions of the OpenTok Accelerator packs
JavaScript
2
star
57

accelerator-textchat-android

Accelerator Text Chat Android provides functionality you can add to your OpenTok applications that enables users to exchange text messages between mobile or browser-based devices.
Java
2
star
58

opentok-macos-sdk-samples

Objective-C
2
star
59

token-encoder

Generates tokens for `X-TB-TOKEN-AUTH` header when using OpenTok REST API.
JavaScript
2
star
60

opentok-swiftui-basic-video-chat

Swift
1
star
61

opentok-jwt

Node module to generate a JWT token given an apiKey and secret.
JavaScript
1
star
62

opentok-embed-appointment

A simple demo for setting up appointments with the OpenTok Embed
JavaScript
1
star