# Reactoo Watch Together SDK for JavaScript

[Overview](#description)
- [Description](#description)
- [Plugin for OTT providers](#plugin-for-ott-providers)
- [Browser support](#browser-support)
- [API Documentation](#api-documentation)

[Usage](#usage)
- [Installation](#installation)
- [Example](#example)
- [Video room events](#video-room-events)
    - [kicked](#kicked)
    - [addLocalParticipant](#addlocalparticipant)
    - [addRemoteParticipant](#addremoteparticipant)
    - [removeLocalParticipant](#removelocalparticipant)
    - [removeRemoteParticipant](#removeremoteparticipant)
    - [localMuted](#localmuted)
    - [remoteMuted](#remotemuted)
    - [chatMessage](#chatmessage)
    - [systemMessage](#systemmessage)
    - [error](#error)

[Questions and feedback](#questions-and-feedback)

## Description

Reactoo Watch Together SDK for JavaScript provides a rich set of client-side functionality that:
* Enables you to manage and join Watch Together video rooms 
* Makes it easy to call Reactoo API directly
* Allows OTT broadcasters to synchronise the live stream
* Capture the reactions of participants to key moments
* Facilitates real-time communication between video room participants when you're implementing custom events

[Reactoo Watch Together](https://reactoo.com) is a technology that allows you to create a video room and invite up to five participants to share the emotion of watching a live video. Those in the room will be able to see, hear and chat while watching the live action, allowing them to debate the talking points and celebrate as if they were all together. The person who sets up the room can invite others by simply sharing a link by text, WhatsApp, email or on social media.

Check out our [API Reference](https://api.reactoo.com/v2/) for more detailed information.

## Plugin for OTT providers

This SDK can be implemented as a plugin for OTT services to deliver an interactive watch together experience for their audiences (a video chat room where all users are synchronized to the live stream so they can see and chat to each other while watching the content). Reactoo also allow this to be broadcast live to others (effectively a multi-party Twitch-style live casting experience) and can capture the reactions of participants to key moments in the stream as they watch which are made available for social sharing. 

## Browser support
![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_24x24.png) | ![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_24x24.png) | ![Opera](https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_24x24.png) | ![Android WebView](https://raw.githubusercontent.com/alrra/browser-logos/master/src/android-webview-beta/android-webview-beta_24x24.png) | ![IE](https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_24x24.png) | ![Safari](https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_24x24.png)
--- | --- | --- | --- | --- | --- |
56+ ✔ | 44+ ✔ | 43+ ✔ | 67+ ✔ | ❌ | ❌ |

## API documentation

[API Documentation](https://api.reactoo.com/v2/) is hosted on Reactoo API pages, and is generated using [ReDoc](https://github.com/Rebilly/ReDoc) following [OpenAPI Specification](https://swagger.io/docs/specification/about/). We support both [JSON](https://api.reactoo.com/v2/swagger.json) and [YAML](https://api.reactoo.com/v2/swagger.yml) formats. 

This SDK does not come bundled with Reactoo API specification as latest version will be fetch on initial SDK load instead. 


# Usage

## Installation
Reactoo Watch Together SDK for JavaScript is available from `npm` or `unpkg`.
```bash
npm install --save @reactoo/watchtogether-sdk-js
```
```html
<!-- standalone (420KB) -->
<script src="https://unpkg.com/@reactoo/watchtogether-sdk-js"></script>
```

## Example

### Join an existing videoroom
```js
let WT = WatchTogetherSDK({ debug: true })({ instanceType: 'reactooDemo' });
WT.auth.deviceLogin()
    .then(r => WT.room.createSession({ roomId: "...", pinHash: "..." }))
    .then(session => {
        session.attachPlayer(hls);
        return session.connect().then(() => session.publishLocal())       
    })
 
```

### Full example

```html
<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Reactoo Watch Together - Demo</title>
    <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
    <script src="https://unpkg.com/@reactoo/watchtogether-sdk-js"></script>
<body>
<div class="content">
    <video class="contentVideo" autoplay playsinline controls style="width: 400px" muted="muted"></video>
    <div>
        <button onclick="startRoom()">Connect and publish</button>
        <button onclick="disconnectRoom()">Disconnect</button>
        <button onclick="publish()">publish</button>
        <button onclick="unpublish()">unpublish</button>
        <button onclick="toggleVideo()">toggle video</button>
        <button onclick="toggleAudio()">toggle audio</button>
    </div>

</div>
<div class="participants"></div>

      <script>
    
            let participants = document.querySelector('.participants');
            var video = document.querySelector('.contentVideo');
    
            if(Hls.isSupported()) {
                var hls = new Hls();
                hls.loadSource('https://hls-demo.reactoo.com/4/index.m3u8');
                hls.attachMedia(video);
                hls.on(Hls.Events.MANIFEST_PARSED, function () {
                    video.play();
                });
            }
    
            function createParticipant(data, isRemote = false) {
    
                let id = `part_${data.id}`;
                let el = document.querySelector(`.${id}`);
                if(!el) {
                    el = document.createElement("video");
                    el.autoplay = true;
                    el.playsInline = true;
                    el.muted = !isRemote;
                    el.controls = true;
                    el.className = id;
                    participants.appendChild(el);
                }
    
                try {
                    el.srcObject = data.stream;
                } catch (error) {
                    el.src = URL.createObjectURL(data.stream);
                }
            }
    
            function removeParticipant(data) {
                let id = `part_${data.id}`;
                let el = document.querySelector(`.${id}`);
                el && el.parentNode.removeChild(el);
            }
    
    
            function disconnectRoom() {
                sessionHandler.disconnect();
            }
    
            function startRoom() {
                sessionHandler.connect()
                    .then(() => sessionHandler.publishLocal())
            }
    
            function unpublish() {
                sessionHandler.unpublishLocal()
            }
    
            function publish() {
                sessionHandler.publishLocal()
            }
    
            function toggleVideo() {
                sessionHandler.toggleVideo();
            }
    
            function toggleAudio() {
                sessionHandler.toggleAudio();
            }
    
    
            let Instance = WatchTogetherSDK({debug:true})({instanceType:'reactooDemo'});
            let sessionHandler = null;
    
            Instance.auth.$on('login', () => {
                console.log('We are in');
            });
    
            Instance.iot.$on('connected', () => {
               console.log('Iot connected');
            });
    
            Instance.iot.$on('error', (e) => {
                console.log('Iot error' ,e);
            });
    
            Instance.iot.$on('disconnected', () => {
                console.log('Iot disconnected');
            });
    
            Instance.iot.$on('message', (r) => {
                console.log('Iot message:', r);
            });
    
            Instance.auth.deviceLogin() // login as browser
                .then(r => Instance.iot.iotLogin()) // login to mqtt
                .then(r => {
    
                    // get our room or create one if it doesn't exist yet
    
                    return Instance.room.getRoomsList({type:'owner'})
                        .then(r => r.data.items.length ? r.data.items[0] : Instance.room.createRoom({title:'Demo Room'}).then(r => r.data))
                        .then(r => Instance.room.getInviteUrl(r._id)) // getting info about invite params
                        .then((r) => {
    
                            console.log('-----------------------------------------------------');
                            console.log('TO CONNECT TO THIS ROOM ON ANOTHER DEVICE USE:');
                            console.log('roomId:', r.data.roomId);
                            console.log('pinHash:', r.data.pinHash);
                            console.log('-----------------------------------------------------');
    
                            return r.data;
    
                        })
    
                })
                .then(r => Instance.room.createSession({roomId:r.roomId, pinHash: r.pinHash})) // pin hash is not needed if you're owner of the room
                .then(session => {
    
                    sessionHandler = session;
    
                    session.$on('connecting', (status) => {
                        console.log('connecting', status);
                    });
    
                    session.$on('reconnecting', (status) => {
                        console.log('reconnecting', status);
                    });
    
                    session.$on('joining', status => {
                        console.log('joining', status); // use 'connecting' instead, 'joining' is here for sentimental purposes
                    });
    
                    session.$on('joined', status => {
                        console.log('joined', status); // joined room
                    });
    
                    session.$on('published', ({status, hasStream}) => {
                        console.log('published', status, hasStream); // published yourself (either with stream or dataChannel only, you're now able to sync the player)
                    });
    
                    session.$on('publishing', status => {
                        console.log('publishing', status);
                    });
    
                    session.$on('disconnect', () => {
                        console.log('disconnect');
                    });
    
                    session.$on('addLocalParticipant', (participant) => {
                        createParticipant(participant); // our stream is available
                    });
    
                    session.$on('removeLocalParticipant', (participant) => {
                        removeParticipant(participant); // our stream is gone
                    });
    
                    session.$on('addRemoteParticipant', (participant) => {
                        createParticipant(participant); // remote stream is available (someone else published himself)
                    });
    
                    session.$on('removeRemoteParticipant', (participant) => {
                        removeParticipant(participant); // remote stream is gone
                    });
    
                    session.$on('userUpdate', (userId) => {
                        console.log('userUpdate', userId); // User "${userId}" updated it's profile, we might do a get request to see what've changed
                    });
    
                    session.$on('chatMessage', (messageData) => {
                        console.log('chatMessage', messageData); // legacy chat message, now replaced with mqtt chat
                    });
    
                    session.$on('iceState', ([handleId, isItMe, iceState]) => {
                        console.log('ICE state', handleId, isItMe, iceState); // ICE state change, mostly for debuging
                    });
    
                    session.$on('playerSyncing', (value) => {
                        console.log('playerSyncing', value); // tells us that we're in the process of syncing with other users
                    });
    
                    session.$on('localMuted', (data) => {
                        console.log('localMuted', data); // we've muted our video/audio stream
                    });
    
                    session.$on('remoteMuted', (data) => {
                        console.log('remoteMuted', data); // remote participant muted it's video/audio stream
                    });
    
                    session.$on('localHasVideo', (value) => {
                        console.log('localHasVideo', value); // local stream contains video track
                    });
    
                    session.$on('localHasAudio', (value) => {
                        console.log('localHasAudio', value); // local stream contains audio track
                    });
    
                    session.$on('observerIds', (value) => {
                        console.log('observerIds', value) // list of observer userIds available for this room
                    });
    
                    session.$on('error', (e) => {
                        if(e && e.type === 'error') {
                            session.disconnect().catch(e => console.log(e));
                        }
                    });
    
                    session.$on('kicked', () => {
                        console.log('kicked') // you have been kicked out
                    });
    
                    //attaching player
                    sessionHandler.attachPlayer(hls);
    
                })
                .catch(e => {
    
                    if(e && e.response && e.response.data) {
                        console.log(e.response.data);
                    }
                    else {
                        console.log(e);
                    }
    
                });
    
    
        </script>

</body>
</html>
```

## Video room events

### `kicked`
Local participant was kicked from the video room. By default a user can only join one video room at a time on any device. This can be increased per user for some non-standard integrations - please get in touch with us

#### Callback parameters
`NULL`

#### Example
```js
session.$on('kicked', () => {
    // Please check that you're not signed in on any other devices
    console.log(`Connection terminated`);
});
```

---
&nbsp;

### `addLocalParticipant`
A local `MediaStream` is available and ready to be displayed.

#### Callback parameters
|Name|Type|Comments
--- | --- | ---------
|participant|`Object`|Object containing `id`, `userId` and `stream` attributes described bellow
|participant.id|`Number`|Unique session handle ID
|participant.userId|`String`|Reactoo userId
|participant.stream|`MediaStream`|More info on [MediaStream](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream)

#### Example
```js
session.$on('addLocalParticipant', ({ id, userId, stream } = {}) => {
    console.log(`I have joined the video room`);
    let el = document.querySelector(`#myVideo`);
    try {
        el.srcObject = stream;
    } catch (error) {
        el.src = URL.createObjectURL(stream);
    }
});
```

---
&nbsp;

### `addRemoteParticipant`
Remote participant has joined a video room and `MediaStream` is available and ready to be displayed.

#### Callback parameters
|Name|Type|Comments
--- | --- | ---------
|participant|`Object`|Object containing `id`, `userId` and `stream` attributes described bellow
|participant.id|`Number`|Unique session handle ID
|participant.userId|`String`|Reactoo userId
|participant.stream|`MediaStream`|More info on [MediaStream](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream)

#### Example
```js
session.$on('addRemoteParticipant', ({ id, userId, stream } = {}) => {
    console.log(`User ${userId} has joined the video room`);
    let elId = `part_${id}`;
    let el = document.querySelector(`.${elId}`);
    if(!el) {
        el = document.createElement("video");
        el.autoplay = true;
        el.playsInline = true;
        el.muted = false;
        el.controls = true;
        el.className = elId;
        participants.appendChild(el);
    }
    try {
        el.srcObject = stream;
    } catch (error) {
        el.src = URL.createObjectURL(stream);
    }
});
```

---
&nbsp;

### `removeLocalParticipant`
Local participant has left a video room.

#### Callback parameters
|Name|Type|Comments
--- | --- | ---------
|participant|`Object`|Object containing `id` attribute described bellow
|participant.id|`Number`|Unique session handle ID

#### Example
```js
session.$on('removeRemoteParticipant', ({ id } = {}) => {
    console.log(`I have left the video room`);
    let el = document.querySelector(`#myVideo`);
    el.innerHTML = "";
});
```

---
&nbsp;

### `removeRemoteParticipant`
Remote participant has left a video room.

#### Callback parameters
|Name|Type|Comments
--- | --- | ---------
|participant|`Object`|Object containing `id` attribute described bellow
|participant.id|`Number`|Unique session handle ID

#### Example
```js
session.$on('removeRemoteParticipant', ({ id } = {}) => {
    console.log(`User with handle "${id}" has left the video room`);
    let elId = `part_${id}`;
    let el = document.querySelector(`.${elId}`);
    el.parentNode.removeChild(el);
});
```

---
&nbsp;

### `localMuted`
Local participant muted the stream

#### Callback parameters
|Name|Type|Comments
--- | --- | ---------
|mute|`Object`|Object containing `type` and `value` attributes described bellow
|mute.type|`String`|Can be `audio` or `video`
|mute.value|`Boolean`|Is muted

#### Example
```js
session.$on('localMuted', ({ type, value } = {}) => {
    console.log(`I have ${(value ? 'muted' : 'unmuted')} my ${type}`);
});
```

---
&nbsp;

### `remoteMuted`
Local participant muted the stream

Experimental feature

---
&nbsp;

### `chatMessage`
Received a chat message from local or remote user. Chat history is not being currently saved on server-side.

#### Callback parameters
|Name|Type|Comments
--- | --- | ---------
|message|`Object`|Object containing `from`, `timestamp`, `text` and `whisper` attributes described bellow
|message.from|`String`|Reactoo User Id of message sender
|message.timestamp|`Number`|UNIX Epoch time
|message.text|`String`|
|message.whisper|`Boolean`|Message sent privately (default=false)

#### Example
```js
session.$on('chatMessage', ({ type, value } = {}) => {
    console.log(`Received a message from "${userId}"`);
    let chat = $('#chatroom');
    chat.append(`<p>[${date.toISOString().substring(11,19)}] <strong>${participants[userId].displayname}</strong>: ${message}</p>`);
    chat.get(0).scrollTop = chat.get(0).scrollHeight;
});
```

---
&nbsp;

### `systemMessage`
Received a system message from server.

#### Callback parameters
|Name|Type|Comments
------------ | ------ | -------
|type|`String`|Can be `user_update_displayname`, `user_update_avatar`, `observer_connecting`, `pending_shutdown`, `shutting_down`
|data|`String`&#124;`NULL`|Additional text data, depends on `type` parameter


#### Example
```js
session.$on('systemMessage', (type, data) => {
    console.log(`Received a system message "${type}"`);
    if(type === 'user_update_displayname' || type === 'user_update_avatar') {
        // Reload user, data will contain userId
        emitEvent('userUpdate', data);
    } else if(type === 'observer_connecting') {
        // Reload video room with updated "allowedObservers" to not show observer as a participant
        emitEvent('roomUpdate');
    } else if(type === 'pending_shutdown') {
        // Current videoroom was reassigned to a different WebRTC instance
        emitEvent('reconnect');
    } else if(type === 'shutting_down') {
        // Current WebRTC videoroom instance will be terminated 5s
        emitEvent('reconnect');
    }
});
```

---
&nbsp;

### `error`
Received an error event.

#### Callback parameters
|Name|Type|Comments
--- | --- | -------
|error|`Object`|Object containing `type`, `id`, `message` and `data` attributes described below
|error.type|`String`|Can be `error` or `warning`
|error.id|`Number`|Error ID
|error.message|`String`|Error description
|error.data|`Object`&#124;`NULL`|Debug information

#### Example
```js
session.$on('error', ({ type, id, message, data } = {}) => {
    if(type !== 'warning') {
        console.log(`Error #${id}: ${message}`, data);
    }
});
```
&nbsp;

## Error messages
|id|type|message
--- | --- | -------
|0|`error`|WebRTC is not supported on this platform
|1|`error`|sendMessage failed
|2|`error`|send failed
|3|`error`|send timeout
|4|`error`|lost connection
|5|`warning`|keepalive response suspicious
|6|`warning`|keepalive dead
|7|`error`|local participant error
|8|`error`|remote participant error
|9|`error`|data event error
|10|`error`|data message parse error'
|11|`error`|reconnection error
|12|`error`|ws reconnection error
|13|`error`|connection error
|14|`error`|ws connection error
|15|`warning`|id non-existent
|16|`warning`|id non-existent
|17|`warning`|id non-existent
|18|`warning`|id non-existent
|19|`warning`|publish remote participant
|20|`error`|no stream
|21|`error`|no local id, connect before publishing
|22|`warning`|rtc peer
|23|`warning`|setRemoteDescription
|24|`warning`|setLocalDescription
|25|`warning`|`String`



# Questions and feedback

Please raise questions, requests for help etc. via [tech@reactoo.com](mailto:tech@reactoo.com).
Feedback and suggestions for improvement always welcome :)
