Skip to content
This repository has been archived by the owner on Feb 15, 2023. It is now read-only.

Commit

Permalink
refactor!: add initSessionAndConnect and remove setCredentials in ope…
Browse files Browse the repository at this point in the history
…nTokMethods (#9)

- dd initSessionAndConnect and remove setCredentials in openTokMethods (#9)
- add docs
- add test

BREAKING CHANGE: add initSessionAndConnect and remove setCredentials in API
  • Loading branch information
pjchender committed Feb 5, 2020
1 parent 8823913 commit 845735c
Show file tree
Hide file tree
Showing 11 changed files with 380 additions and 240 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
dist
site
204 changes: 188 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,21 @@ yarn add react-use-opentok

> NOTE: remember to install the peer dependency of [@opentok/client](https://www.npmjs.com/package/@opentok/client)
## Getting Start
## Getting Started

1. Get utilities from `useOpenTok` hook
2. Fetch `apiKey`, `sessionId`, and `token` from server
3. Connect to session with `token`

```js
import React, { useEffect } from 'react';
import useOpenTok from 'react-use-opentok';

const Component = () => {
const [opentokProps, opentokMethods, setCredentials] = useOpenTok();
// STEP 1: get utilities from useOpenTok;
const [opentokProps, opentokMethods] = useOpenTok();

const {
// credentials
apiKey,
sessionId,
token,

// connection info
connectionId,
isSessionConnected,
Expand All @@ -62,7 +62,7 @@ const Component = () => {
} = opentokProps;

const {
connectSession,
initSessionAndConnect,
disconnectSession,
publish,
unpublish,
Expand All @@ -71,18 +71,18 @@ const Component = () => {
sendSignal,
} = opentokMethods;

// Mockup fetching credentials from server
// STEP 2: Mockup fetching apiKey, sessionId, and token from server
useEffect(() => {
fetch('<get credentials from server>').then(
({ apiKey, sessionId, token }) => {
setCredentials({
initSessionAndConnect({
apiKey,
sessionId,
token,
});
}
);
}, [setCredentials]);
}, [initSessionAndConnect]);

return <div>...</div>;
};
Expand All @@ -92,15 +92,187 @@ export default Component;

## Guide

### useOpenTok Hook
### Get all utilities from useOpenTok Hook

You can get all utilities from `useOpenTok` hook.

```js
const [opentokProps, opentokMethods] = useOpenTok();

const {
// connection info
connectionId,
isSessionConnected,

// connected data
session,
connections,
streams,
subscribers,
publisher,
} = opentokProps;

const {
initSessionAndConnect,
disconnectSession,
publish,
unpublish,
subscribe,
unsubscribe,
sendSignal,
} = opentokMethods;
```

### Connect and disconnect to session

Before starting use openTok session object, remember to initialize session with `apiKey` and `sessionId` by `initSessionAndConnect` method:

```js
const [opentokProps, opentokMethods] = useOpenTok();
const { initSessionAndConnect } = opentokMethods;

// apiKey, sessionId, and token could get from your server or tokbox dashboard
initSessionAndConnect({
apiKey,
sessionId,
token,
});
```

After connect to session, you can get the `session`, `connectionId` , `isSessionConnected`, and `connections` properties from `opentokProps`:

- `session`: a session object from [`OT.initSession()`](https://tokbox.com/developer/sdks/js/reference/OT.html#initSession)
- `connectionId`: your own connectionId
- `isSessionConnected`: whether you are connected to the session
- `connections`: all connections in the session

```js
const [opentokProps, opentokMethods] = useOpenTok();
const { session, connectionId, isSessionConnected, connections } = opentokProps;
```

By `disconnectSession`, you can disconnect from the session:

```js
const [opentokProps, opentokMethods] = useOpenTok();
const { disconnectSession } = opentokMethods;

disconnectSession();
```

### Publish and unpublished stream to the session

You can publish stream from camera or screen to session through the `publish` method.

- `name`: should be unique every time you invoke publish method which is for `unpublish` stream later.
- `element`: should be a DOM element or the `id` attribute of the existing DOM element.
- `options`: (optional) other optional properties which will pass into [OT.initPublisher](https://tokbox.com/developer/sdks/js/reference/OT.html#initPublisher).

```js
const [opentokProps, opentokMethods] = useOpenTok();
const { publish } = opentokMethods;

// publish stream from the camera
publish({
name: 'camera',
element: 'camera',
});

// publish stream from screen sharing
publish({
name: 'screen',
element: 'screen',
options: {
insertMode: 'append',
width: '100%',
height: '100%',
videoSource: 'screen',
},
});
```

According to the `name` you publish, you could use the same name to unpublish it:

```js
const [opentokProps, opentokMethods] = useOpenTok();
const { unpublish } = opentokMethods;

// unpublish stream from the name 'camera'
unpublish({ name: 'camera' }
```
### Subscribe and Unsubscribe
You can get all streams in the session through `streams` property in `opentokProps`. After finding the stream for subscribing, use the `subscribe` method to subscribe to the stream:
- `stream`: the Stream Object wanted to subscribe
- `element`: should be a DOM element or the `id` attribute of the existing DOM element.
```js
const [opentokProps, opentokMethods] = useOpenTok();
const { streams } = opentokProps;
const { subscribe } = opentokMethods;

const streamToSubscribe = streams[0];
subscribe({ stream: streamToSubscribe, element: 'subscriber' });
```
For each stream be subscribed, a [subscriber object](https://tokbox.com/developer/sdks/js/reference/Session.html#subscribe) will be created and save as `subscribers` in `opentokProps`:
```js
const [opentokProps, opentokMethods] = useOpenTok();
const { streams, subscribers } = opentokProps;
```
You can stop subscribing the stream with `unsubscribe` method:
```js
const [opentokProps, opentokMethods] = useOpenTok();
const { unsubscribe } = opentokMethods;

const streamToUnsubscribe = streams[0];
unsubscribe({ stream: streamToUnsubscribe });
```
### Send signal
You can send signal in session with `sendSignal` method:
```js
const [opentokProps, opentokMethods] = useOpenTok();
const { sendSignal } = opentokMethods;

sendSignal({
type: 'foo',
data: 'bar',
});
```
### Register session events
You can get all utilities of [@opentok/client](https://www.npmjs.com/package/@opentok/client) from `useOpenTok` hook.
You could register all valid [session events](https://tokbox.com/developer/sdks/js/reference/Session.html#events) on `session` object. Take registering signal event, as an example, use the `session` object in `opentokProps`, register the session event with `on`, and unregister the event with `off`:
```js
const [opentokProps, opentokMethods, setCredentials] = useOpenTok();
const [opentokProps, opentokMethods] = useOpenTok();
const { session } = opentokProps;

const handleSignal = useCallback(e => {
console.log('handleSignal', e);
}, []);

useEffect(() => {
if (!isSessionConnected) {
return;
}

session.on('signal', handleSignal);
return () => {
session.off('signal', handleSignal);
};
}, [handleSignal, isSessionConnected, session]);
```
### connect to
> NOTICE: for `sessionDisconnected` event, you can you `session.once('sessionDisconnected', <eventHandler>)`
## Development
Expand All @@ -118,7 +290,7 @@ $ npm test
```sh
$ cd site
$ npm install
$ npm start # start gatsby develope server
$ npm start # start gatsby develop server
```
## Contributors
Expand Down
5 changes: 0 additions & 5 deletions site/.eslintrc

This file was deleted.

41 changes: 19 additions & 22 deletions site/src/components/demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
Box,
Label,
Input,
Select,
Textarea,
Button,
Badge,
Expand All @@ -25,26 +24,21 @@ const defaultOpenTokOptions = {
};

export default () => {
const [opentokProps, opentokMethods, setCredentials] = useOpenTok();
const [opentokProps, opentokMethods] = useOpenTok();

const {
apiKey,
sessionId,
token,

connectionId,
isSessionConnected,

session,
connections,
streams,

subscribers,
publisher,
} = opentokProps;

const {
connectSession,
initSessionAndConnect,
disconnectSession,
publish,
unpublish,
Expand All @@ -59,9 +53,15 @@ export default () => {
sessionId: SESSION_ID,
token: TOKEN,
},
onSubmit: values => {
// STEP 1-1: set credentials to init opentok session
setCredentials({ ...values });
onSubmit: async (values, { setSubmitting }) => {
const { apiKey, sessionId, token } = values;
await initSessionAndConnect({
apiKey,
sessionId,
token,
});

setSubmitting(false);
},
});

Expand Down Expand Up @@ -93,22 +93,20 @@ export default () => {
console.log('handleSignal', e);
}, []);

const handleSessionDisconnected = useCallback(e => {
console.log('handle session disconnected', e);
}, []);

useEffect(() => {
if (!isSessionConnected) {
return;
}
session.on('signal', handleSignal);
session.once('sessionDisconnected', handleSessionDisconnected);
return () => {
session.off('signal', handleSignal);
};
}, [handleSignal, isSessionConnected, session]);

// STEP 1-2: session will be initiated after credentials set
useEffect(() => {
if (session) {
connectSession();
}
}, [session]);
}, [handleSignal, handleSessionDisconnected, isSessionConnected, session]);

const streamGroups =
streams &&
Expand All @@ -119,7 +117,6 @@ export default () => {
return groups;
}, {});


if (typeof window === 'undefined') return null;

return (
Expand Down Expand Up @@ -179,7 +176,7 @@ export default () => {
></div>
</div>
<div>
{(session && session.currentState) === 'connected' ? (
{isSessionConnected ? (
<>
<div
sx={{
Expand Down Expand Up @@ -304,7 +301,7 @@ export default () => {
<Button
variant="secondary"
type="submit"
disabled={isSessionConnected}
disabled={credentialsFormik.isSubmitting}
sx={{
display: 'block',
marginLeft: 'auto',
Expand Down
2 changes: 1 addition & 1 deletion site/src/constants.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion site/src/gatsby-plugin-theme-ui/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ export default {
'&:hover': {
background: '#eee',
},
cursor: 'pointer',
fontSize: 1,
'&:focus': {
outline: '0 none',
Expand Down
Loading

0 comments on commit 845735c

Please sign in to comment.