# QuickStart Guide

## Setting things up <a href="#setting-up" id="setting-up"></a>

### \*\*\*\*:key2: **Get your ApiRTC key and authorize your domain** <a href="#setting-up" id="setting-up"></a>

In order to connect to the ApiRTC services, you need an API key.

To find out your API key:

1. Register and log into your ApiRTC account on <https://cloud.apirtc.com>.
2. Go to the [API/Credentials section](https://cloud.apirtc.com/enterprise/api).
3. Grab it and keep it aside, we will soon use this key.
4. Enter 127.0.0.1 (for the purpose of this tutorial) or the targeted application domain in the list of authorized domains. You may use wildcards as \*.mydomain.com.

### :bricks:Create the project structure

This project is a simple Web Application consisting of an HTML file, a Javascript file and a CSS file.

Before delving into the code, you need to create a project directory ( `quickstart_apirtcjs/` for example) for your application.

This folder will eventually look as follows:

```shell
quickstart_apirtcjs/
├── css
│   └── app.css
├── index.html
└── js
    └── app.js
```

<details>

<summary>Command line instructions</summary>

```bash
mkdir css
mkdir js
touch index.html
touch css/app.css
touch js/app.js
```

</details>

**Now, let's build the app!**

## Create some placeholders for video streams

ApiRTC is to be used in a brower. It will use the DOM Elements to display the video streams.

In the `index.html` :

* Create a basic HTML markup structure
* Reference `app.css` and the latest version of the ApiRTC library
* Reference the `app.js` javascript file at the end just before the `</body>` closing tag
* Add 2 `div` elements identified as `remote` (that will contains all the video streams from remote participant) and `local` (that will contains your own camera display)

It should look something like below :point\_down:

```html
 <!DOCTYPE html>
 <html>
    <head>
      <title>ApiRTC Quickstart</title>
      <link rel="stylesheet" href="css/app.css"/>
      <script type="text/javascript" src="https://cdn.apirtc.com/apiRTC/apiRTC-latest.min.js"></script>
    </head>
    <body>
        <div id="conference">
            <div id="remote"></div>
            <video id="local" autoplay="true" muted="true" width="320" height="240" ></video>
        </div>
        <script type="text/javascript" src="js/app.js"></script>
    </body>
</html>
```

## Connect to the ApiRTC platform <a href="#create-a-user-agent" id="create-a-user-agent"></a>

Let's open the `app.js` file to develop the scripting part.

The first step is to create a `UserAgent` to connect to the ApiRTC server and manage media streams.

It requires to use your API key :key2:.

```javascript
var API_KEY = '#INSERT_YOUR_APIKEY_HERE#'; 

var userAgent = new apiRTC.UserAgent({ uri: 'apiKey:' + API_KEY })
let conversation = undefined

userAgent.register({
    cloudUrl: 'https://cloud.apirtc.com'
}).then( (session) => {
    alert("You're connected, well done!")
});
```

{% hint style="info" %}
You need to replace `#INSERT_YOUR_APIKEY_HERE#` by your ApiRTC key. Refer to the [#setting-up-1](#setting-up-1 "mention") section if you don’t already have your key available.
{% endhint %}

Launch a webserver pointing to `index.html`, open your browser and to see the magic!

<details>

<summary>Launch a webserver</summary>

```bash
npx http-server
```

Then navigate to <http://127.0.0.1:8080>.

</details>

TADAAA :tada:

<figure><img src="https://226856024-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F9RTy6zMGBeXToEHSXgv7%2Fuploads%2FIb7LZ049iHCj7mbDlSkA%2Fimage.png?alt=media&#x26;token=eabc15c4-cb0f-45a9-8a12-4f31af1965bf" alt=""><figcaption><p>Connect to the ApiRTC platform</p></figcaption></figure>

{% hint style="info" %}
See other connection mode in the [authentication](https://dev.apirtc.com/apirtc-developer-portal/apirtc-js-library/authentication "mention")section.
{% endhint %}

## Create an ApiRTC conversation and publish your local video <a href="#create-an-apirtc-conversation-and-publish-your-local-video" id="create-an-apirtc-conversation-and-publish-your-local-video"></a>

Now that you are connected to the ApiRTC plaform, we will:

1\. Retrieve a Conversation through its `convarsationName` (which is a simple string)

2\. Retrieve the local camera video stream and local audio stream

3\. Display the local video stream in the HTML page

4\. Join the Conversation

5\. Publish our local camera video stream into the Conversation to shared across all the participants.

Replace the `userAgent.register` call instruction in `app.js` by the code below:

<pre class="language-javascript"><code class="lang-javascript"><strong>userAgent.register({
</strong>    cloudUrl: 'https://cloud.apirtc.com'
}).then((session) => {

    //Prepare connection to conversation
    conversation = session.getOrCreateConversation('quickstart_conversation')
    
    // Define the way the local stream will be configured
    let streamOptions = {
        constraints: {
            audio: true,
            video: true
        }
    }

    //Get the stream for the local camera
    userAgent.createStream(streamOptions).then(function (stream) {
        
        //Display the stream (audio+video) in the &#x3C;video> element with id 'local'
        stream.attachToElement(document.getElementById('local'))
        
        //Join the conversation
        conversation.join().then(() => {
        
            //Publish the local stream in the conversation
            conversation.publish(stream)
        });
    });
});
</code></pre>

Reload the web page in your browser.

You should be prompted to allow mic and camera use.

<figure><img src="https://226856024-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F9RTy6zMGBeXToEHSXgv7%2Fuploads%2Fuzg1TuUh2xLGm8rQZlXN%2Fimage.png?alt=media&#x26;token=fc25629c-a80f-4079-b59d-3a0e59c99207" alt=""><figcaption><p>Authorisation prompt to enable mic and camera use</p></figcaption></figure>

Click on the "Allow" button.

<figure><img src="https://226856024-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F9RTy6zMGBeXToEHSXgv7%2Fuploads%2FNTWn1buxAGDD8XPoIuqy%2Fimage.png?alt=media&#x26;token=9110e12f-f109-4b66-862c-537940e63dc8" alt=""><figcaption><p>You should see yourself now (display may differ from photograph)</p></figcaption></figure>

And now you should see yourself! :clap:

Note that you should read `Subscribed to XXXXXXXXXXXXXXXXX` in your browser console.

## Subscribe to remote streams <a href="#subscribe-to-remote-stream" id="subscribe-to-remote-stream"></a>

Each time a new participant publishes their stream to the Conversation, you want to display it in your webpage.

3 events are triggered by the Conversation object to help us with it:

* `streamListChanged` : when any stream is added or remove to the Conversation's stream list, or when one of the stream's attributes changes.
* `streamAdded` : triggered when a new stream is added to the Conversation (only by streams you are subscribed to)
* `streamRemoved` triggered when a stream is removed from the Conversation (only by streams you are subscribed to)

To get it right with this, you need to:

1. Subscribe to new streams when the `streamListChanged` is triggered
2. Add a new participant's video to the HTML page when `streamAdded` is triggered
3. Remove a participant's video from the HTML page when `streamRemoved` is triggered

Let's code it now. Add the code below just below the `getOrCreateConversation` call :keyboard: :point\_down:

```javascript
//Any time the streamListChanged is triggered
    conversation.on('streamListChanged', (streamInfo) => {

        // when a new stream is added AND the added stream is not 
        if (streamInfo.listEventType === 'added' && streamInfo.isRemote === true) {

            //Subscribe to the new stream's events (triggered by the conversation object)
            conversation.subscribeToMedia(streamInfo.streamId).then((stream) => {
                console.log("Subscribed to " + stream.streamId)
            })
        }
    });

    //Any time a (subscribed) stream is added to the conversation
    conversation.on('streamAdded', (stream) => {
        
        //Add a video element in the 'remote' div element,  with the streamId in its id attribute
        stream.addInDiv('remote', 'remote-media-' + stream.streamId, {}, false)
    
    });

    //Any time a (subscribed) stream is removed from the conversation
    conversation.on('streamRemoved', (stream) => {
        
        //Remove a video element with the streamId in its id attribute
        stream.removeFromDiv('remote', 'remote-media-' + stream.streamId)
    });
```

Refresh your browser page, open another tab at the same URL and... :clap: clap your hand if you see yourself twice (and more if you open more tabs !)

<figure><img src="https://226856024-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F9RTy6zMGBeXToEHSXgv7%2Fuploads%2FYA02J1ExqzS8aKYZRjWN%2Fimage.png?alt=media&#x26;token=1315fb91-800f-4766-88be-f18fd0cd99f3" alt=""><figcaption><p>There is one local stream and one remote stream in each tab. Can you see the difference?</p></figcaption></figure>

{% hint style="info" %}
If your speakers and microphone are opened, you will get some shrieking feedback sound. Turn off your microphone and all should be fine.
{% endhint %}

{% hint style="info" %}
**Go deeper into the ApiRTC model**

Read the ApiRTC Javascript Reference documentation pages:

* [Conversation](https://apirtc.github.io/references/apirtc-js/Conversation.html) class
* [Stream](https://apirtc.github.io/references/apirtc-js/Stream.html) class
* [UserAgent](https://apirtc.github.io/references/apirtc-js/UserAgent.html) class
  {% endhint %}

## Final touch, get some style <a href="#customize-the-css" id="customize-the-css"></a>

Let's beautiful your first video app with some CSS styling. Edit the `app.css` file and add the following code:

```css
body {
    margin: 0;
}

#conference {
    position: relative;
    margin: 0;
    overflow: scroll;
    max-height: 100vh;
}

video {
    border-radius: 10px;
}

#local {
    position: absolute;
    width: 20%;
    min-width: 100px;
    max-width: 200px;
    bottom: 20px;
    right: 20px;
    z-index: 2;
    transform: rotateY(180deg);
    -webkit-transform:rotateY(180deg); /* Safari and Chrome */
    -moz-transform:rotateY(180deg); /* Firefox */
}

#remote {
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

#remote>video {
    flex: 1;
    max-height: 100vh;
}
```

Here should be the result:

<figure><img src="https://226856024-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F9RTy6zMGBeXToEHSXgv7%2Fuploads%2F36I4Cgog9YLsIiZNT55K%2Fimage.png?alt=media&#x26;token=46238b9f-3eaa-4df8-b946-ea0772c6734b" alt=""><figcaption><p>Thumbs up, we are done!</p></figcaption></figure>

**Congratulations, you are now ready to success!** :tada:\*\*\*\*

## What you can do next

* Read the [developer-guide](https://dev.apirtc.com/apirtc-developer-portal/apirtc-js-library/developer-guide "mention")and get a deeper understanding of ApiRTC workflow
* Get to know the [video-communication-lifecycle](https://dev.apirtc.com/apirtc-developer-portal/apirtc-js-library/video-communication-lifecycle "mention")run by ApiRTC
* Play with the[demo-app-and-resources](https://dev.apirtc.com/apirtc-developer-portal/apirtc-js-library/demo-app-and-resources "mention")
