Build a Scalable Video Chat App with Agora in Django
Tags: django, python, agora, videocall
Published: 2021-04-13 18:01:27



#Introduction
Django is a high-level Python Web framework that takes care of much of the hassle of Web development so that you can focus on writing your app without needing to reinvent the wheel. While Agora takes away the hassle of building a video chat application from scratch.


WebRTC is only one of the ways that people can implement video chat features. Companies like <a href="https://www.agora.io/en/" target="_blank">Agora</a> also provide a fully packaged video chat SDK to provide a high-quality Real-Time Engagement video chat experience. As someone who has WebRTC development experience, I can tell you there are some limitations with WebRTC, such as:

<ol>
<li><strong>Quality of experience:</strong> Since WebRTC is transmitted over the Internet, which is a public domain, the quality of experience is hard to guarantee.</li>
<li><strong>Scalability:</strong> Scalability is fairly limited on group video calls due to the peer-to-peer nature of WebRTC.</li>
</ol>

After I was introduced to the Agora platform, I was impressed that setting up the same video call feature is easier with the Agora SDK than with WebRTC. I went ahead to build a video chat application with Agora and Laravel. In this article, however, I don't want Django developers to be left out so we are going to implement a video chat application with Django and Agora.


# Why Agora Is the Preferred Solution
After building a video chat app with Agora, I want to highlight some of the advantages:

<ol>
<li>There's one SDK for everything - voice, video, live streaming, screen sharing, and so on.</li>
</li>

<li>I didn't have to set up a turn server with <a href="https://github.com/coturn/coturn" target="_blank">coturn</a> on Amazon EC2 as I did in the other implementation to relay traffic between peers on different networks.</li>

<li>You get <a href="https://www.agora.io/en/pricing/" target="_blank">10,000 minutes every month </a>free, and this gives you the flexibility to develop your solution prototype for free.</li>

<li>You don't have the challenge of managing the underlying infrastructure supporting the video call functionality.</li>

<li>Intuitive API documentation is available.</li>
</ol>

# Prerequisites
<ul>
<li>Python 3.8.5</li>
<li>An average knowledge about how to create a Django project and app. The following tutorial can help you: <a href="https://docs.djangoproject.com/en/3.1/intro/tutorial01/
" target="_blank">Writing your first Django app</a>.</li>

<li>A free pusher account on <a href="https://pusher.com/" target="_blank">pusher.com</a></li>

<li>An understanding of <a href="https://pusher.com/docs/channels/using_channels/presence-channels" target="_blank">pusher presence channels</a> and the <a href="https://github.com/pusher/pusher-http-python#installation" target="_blank">python server library</a>.</li>

<li>Agora Developer Account: (See <a href="https://www.agora.io/en/blog/how-to-get-started-with-agora" target="_blank">How to get started with Agora</a>)</li>
</ul>


# Project Setup

1. Create and activate a python3 virtual environment for this project.

2. Open your terminal or command prompt and navigate to your Django project directory. We will use <strong>mysite</strong> as the project name for this tutorial.

3. Install the necessary packages from your terminal or command prompt.

    ```

        pip install pusher python-dotenv

    ```
4. Create a new app called agora. Run the following from your terminal.

    ```

       python manage.py startapp agora

    ```
5. In the project directory i.e <strong>mysite</strong>, run your migrations and create new super users by running the following command from your terminal.

    ```

        python manage.py migrate
 // run the next command multiple times to create more users
        python manage.py createsuperuser

    ```

6. Download the AgoraDynamicKey Python3 code from the Agora repository: <a href="https://github.com/AgoraIO/Tools/tree/master/DynamicKey/AgoraDynamicKey/python3" target="_blank">AgoraDynamicKey</a>

Keep the downloaded folder in a location outside the project folder. Some of these files from the folder will be copied into our project when we're configuring the back end.


# Configuring the Backend
We will create the views and classes with the methods needed to generate the Agora token to establish a call. We will set up Pusher at the server-side as well.

### 1. Add agora to the installed apps in mysite/settings.py
{% gist https://gist.github.com/Mupati/c4a0aaf26307cf39d28b7a401730a285 %}

### 2. Add application routes
Create a file named <strong>urls.py</strong> in the agora directory and add the following code.
From your terminal or command prompt:

    ```bash

       touch agora/urls.py

    ```
Add the following to <strong>agora/urls.py</strong>

{% gist https://gist.github.com/Mupati/63efa07768142920f497aeb9d09e81a1 %}

Register the agora app routes at the project level. Add the following code to <strong>mysite/urls.py</strong>.
{% gist https://gist.github.com/Mupati/04c08013414beb970039147e224639ac %}

### 3. Add the downloaded AgoraDynamicKey generator files
* Open your command prompt, and in the <strong>agora</strong> directory, create a sub-directory named <strong>agora_key</strong>.

    ```bash

       cd agora
       mkdir agora_key

    ```
* Copy <strong>AccessToken.py<strong> and <strong>RtcTokenBuilder.py</strong> from the <strong>src</strong> directory in the downloaded files and add them to the <strong>agora_key</strong> directory.

### 4. Create the views for the Agora app in agora/views.py
Add the following block of code to the <strong>agora/views.py</strong> file.

{% gist https://gist.github.com/Mupati/67888a62c61b66b45a977be338305de5 %}

#### Breakdown of Methods in agora/views.py
<ul>
<li><strong>index:</strong> To view the video call page. Only authenticated users can view the page but non-authenticated users are redirected to the login page. We return a list of all the users apart from the currently authenticated user to be rendered on the front end.</li>

<li><strong>pusher_auth:</strong> It serves as the endpoint for authenticating the logged-in user as they join the pusher's presence channel. The ID and name of the user are returned after successful authentication with the pusher.</li>

<li><strong>generate_agora_token:</strong> To generate the Agora dynamic token. The token is used to authenticate app users when they join the agora channel to establish a call.</li>

<li><strong>call_user:</strong> This triggers a <strong>make-agora-call</strong> event on the <strong>presence-online-channel</strong> to which all logged-in users are subscribed.</li>
</ul>

The data broadcast with the <strong>make-agora-call</strong> event across the <strong>presence-online-channel</strong> contains the following:
<ul>
<li><strong>userToCall:</strong> This is the ID of the user who is supposed to receive a call from a caller.</li>
<li><strong>channelName:</strong> This is the call channel that the caller has already joined on the front end. This is a channel created with the Agora SDK on the client-side. It is the room the caller has already joined, waiting for the callee to also join to establish a call connection.</li>
<li><strong>from:</strong> The ID of the caller.</li>
</ul>

From the <strong>make-agora-call</strong> event, a user can determine whether they are being called if the userToCall value matches their ID. We show an incoming call notification with a button to accept the call. They know who the caller is by the value of from.


# Configuring the Front End
We are going to create the user interface for making and receiving the video call with the ability to toggle the on and off states of the camera and the microphone.

### 1. Create the HTML file for the index view.
The HTML file will contain the links to the CDN for Agora SDK, Vue.js, Pusher, Bootstrap for styling, and our custom CSS and Javascript.

In your terminal navigate to the <strong>agora</strong> directory, create a <strong>templates</strong> directory and an <strong>agora</strong> subdirectory within it.
Create your <strong>index.html</strong> file in the <strong>agora</strong> subdirectory.

```
    cd agora
    mkdir -p templates/agora
    touch templates/agora/index.html
```

Add the following to the <strong>index.html</strong> file:

{% gist https://gist.github.com/Mupati/312d05a71104903757ce0ab66c39424c %}

NOTE:<br/>
In the Pusher instance, replace the `key` with your own Pusher Key. Replace "420e941c25574fda6378"  with yours.
 
```
      window.pusher = new Pusher("420e941c25574fda6378", {
        cluster: "APP_CLUSTER",
        authEndpoint: "{% url 'agora-pusher-auth' %}",
        auth: {
          headers: {
            "X-CSRFToken": "{{ csrf_token }}",
          },
        },
      });
```

### 2. Create the static files
We have <strong>index.css</strong> for custom styling and <strong>index.js;</strong> our script for handling the call logic.

Add the following to <strong>index.js</strong>

{% gist https://gist.github.com/Mupati/de2fb91e88911a870f7f42c02586d77c %}


Add the following to index.css
{% gist https://gist.github.com/Mupati/1886ba973693c1ba8248d730e87e5005 %}


#### Breakdown of the Agora Call Page
On the video call page, i.e <strong>app/templates/agora/ndex.html</strong>, we display buttons that bear the name of each registered user and whether they are online or offline at the moment.

To place a call, we click the button of a user with online status. An online user indicates one who is available to receive a call. For our demo, we see a list of users. The user named <strong>Bar</strong> is indicated as being online. The caller named <strong>Foo</strong> can call <strong>Bar</strong> by clicking the button.

![Users with Call Buttons](https://cdn-images-1.medium.com/max/800/0*P2jNnqj_GriDK5eL)

<strong>Bar</strong> gets an incoming call notification with Accept and Decline buttons and the name of the caller.

![Incoming Call Notification](https://cdn-images-1.medium.com/max/800/0*uLdMRCpbatnuyyt7)


From the call notification image above, we see that the caller's name is <strong>Foo</strong>. <strong>Bar</strong> can then accept the call for a connection to be established.

The following diagram explains the call logic in terms of the code:

![Call Logic](https://cdn-images-1.medium.com/max/2560/1*WWf_DkRuKz0-cFywT7uXBg.jpeg)

### 3. Update env variables with Pusher and Agora keys
The <strong>.env</strong> file is located at the root of your project folder. Add the credentials you got from Agora and Pusher.

```
PUSHER_APP_ID=
PUSHER_KEY=
PUSHER_SECRET=
PUSHER_CLUSTER=

AGORA_APP_ID=
AGORA_APP_CERTIFICATE=
```

# Testing
1. Start the Django development server from your terminal.
    ```bash

        python manage.py runserver

    ```
2. Open two different browsers or two instances of the same browser, with one instance in incognito mode, and go to <a href="http://127.0.0.1:8000
 target="_blank">http://127.0.0.1:8000</a>

3. You are presented with the Django admin login page if you are not already logged in.

4. After successful login, you will be taken to the Django admin dashboard. Click on the VIEW SITE link at the top right to navigate to the video call page.

5. In each of the browsers you opened, the other users registered on the application are displayed.

6. In one browser, you can call the user who is logged in and on the other browser by clicking the button that bears their name.

7. The other user is prompted to click the Accept button to fully establish the call.


# Video Demonstration of the Video Call
To confirm that your demo is functioning properly, see my demo video as an example of how the finished project should look and function:
{% youtube KAjVu51BKUY %}


# Conclusion
You have now implemented the video call feature in your Django application! It's not that hard, right?

To include video calling functionality in your web app, you don't have to build it from scratch.

Agora provides a lot of great features out of the box. It also helps businesses save development hours when implementing video chat into existing projects. The only thing a developer has to do is build a compelling front end - Agora handles the video chat back end.

Link to project repository: [https://github.com/Mupati/agora-django-video-call](https://github.com/Mupati/agora-django-video-call)

Online Demo Link: [https://fleet-server.herokuapp.com/agora/login/?next=/agora/dashboard/](https://fleet-server.herokuapp.com/agora/login/?next=/agora/dashboard/)

Make sure the demo link or production version is served on HTTPS.


Test accounts:<br/>
foo@example.com: DY6m7feJtbnx3ud<br/>
bar@example.com: Me3tm5reQpWcn3Q<br/>

# Other Resources
<ul>
<li><a href="https://docs.agora.io/en/Video/API%20Reference/web/interfaces/agorartc.client.html#agorartc.client.html%23on" target="_blank">Available events on the Agora Client</a></li>
<li>For more information about Agora.io applications, take a look at the: <a href="https://docs.agora.io/en/Video/run_demo_video_call_web?platform=Web" target="_blank">Agora Quickstart Guides</a></li>
<li>Take a look at the complete documentation for the functions discussed above and many more: <a href="https://docs.agora.io/en/Video/API%20Reference/web/index.html" target="_blank">Agora Web SDK API</a></li>
</ul>

I also invite you to <a href="https://app.slack.com/client/T265K8ZT9/C263V5MFV/thread/CPQP4GMJ9-1585749906.115600" target="_blank">join the Agora.io Developer Slack community</a>.