npm package: @reactoo/watchtogether-sdk-js
Description: Javascript SDK for Reactoo
Author: Roman Labis
Latest version: 2.8.82

# 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)


[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('hlsjs', {hlsInstance:hls});
    
                })
                .catch(e => {
    
                    if(e && e.response && e.response.data) {
                        console.log(e.response.data);
                    }
                    else {
                        console.log(e);
                    }
    
                });
    
    
        </script>

</body>
</html>
```


# 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 :)