Building a complete video conferencing application from scratch involves multiple components, including user authentication, authorization, real-time communication, and front-end integration with technologies like WebRTC. Below, I'll guide you through creating a Django-based video conferencing app with the following features:
- User Authentication: Only registered users can access the app.
- Admin Invitations: Only users invited by the admin can join specific conference rooms.
- Video Conferencing Capabilities: Real-time video and audio communication using WebRTC.
We'll use Django for the backend, Django Channels for handling WebSockets (necessary for real-time features), and WebRTC for peer-to-peer video/audio communication on the frontend.
Prerequisites
- Python 3.x installed
- Node.js installed (for serving static files if needed)
- Basic knowledge of Django, JavaScript, and HTML/CSS
Step 1: Set Up Django Project
- Create a Virtual Environment and Install Dependencies
python3 -m venv venv
source venv/bin/activate
pip install django djangorestframework channels channels_redis
Note: channels_redis is used as the channel layer backend. Ensure Redis is installed and running on your system.
- Create Django Project and App
django-admin startproject VideoConferenceApp
cd VideoConferenceApp
python manage.py startapp conference
- Configure
settings.py
In VideoConferenceApp/settings.py, add the necessary configurations.
# settings.py
import os
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
'rest_framework',
'channels',
'conference',
]
# Channels Configuration
ASGI_APPLICATION = 'VideoConferenceApp.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': [('127.0.0.1', 6379)],
},
},
}
# Static Files
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# Templates
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
},
]
# Authentication Redirects
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/login/'
- Configure ASGI
Create VideoConferenceApp/asgi.py for Channels.
# asgi.py
import os
import django
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
import conference.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'VideoConferenceApp.settings')
django.setup()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
conference.routing.websocket_urlpatterns
)
),
})
Step 2: Define the Models
We'll have Room and Invitation models to handle conference rooms and invitations.
# conference/models.py
from django.db import models
from django.contrib.auth.models import User
class Room(models.Model):
name = models.CharField(max_length=255)
created_by = models.ForeignKey(User, related_name='rooms', on_delete=models.CASCADE)
participants = models.ManyToManyField(User, related_name='participating_rooms', blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Invitation(models.Model):
room = models.ForeignKey(Room, related_name='invitations', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='invitations', on_delete=models.CASCADE)
invited_at = models.DateTimeField(auto_now_add=True)
accepted = models.BooleanField(default=False)
def __str__(self):
return f"{self.user.username} invited to {self.room.name}"
Run migrations:
python manage.py makemigrations
python manage.py migrate
Step 3: Create Admin Interface
Register models in the admin to manage rooms and invitations.
# conference/admin.py
from django.contrib import admin
from .models import Room, Invitation
admin.site.register(Room)
admin.site.register(Invitation)
Create a superuser:
python manage.py createsuperuser
Step 4: Implement User Authentication
Use Django's built-in authentication system.
- URLs Configuration
# VideoConferenceApp/urls.py
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
urlpatterns = [
path('admin/', admin.site.urls),
path('conference/', include('conference.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('', RedirectView.as_view(url='/conference/', permanent=True)),
]
- Templates for Authentication
Create templates/registration/login.html and logout.html.
Example login.html:
<!-- templates/registration/login.html -->
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</body>
</html>
Step 5: Create Views and URLs
- URLs
# conference/urls.py
from django.urls import path
from . import views
app_name = 'conference'
urlpatterns = [
path('', views.home, name='home'),
path('rooms/', views.RoomListView.as_view(), name='room_list'),
path('rooms/create/', views.RoomCreateView.as_view(), name='room_create'),
path('rooms/<int:pk>/', views.RoomDetailView.as_view(), name='room_detail'),
path('rooms/<int:pk>/invite/', views.invite_user, name='invite_user'),
path('rooms/<int:pk>/join/', views.join_room, name='join_room'),
]
- Views
# conference/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.views.generic import ListView, DetailView, CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Room, Invitation
from django.contrib.auth.models import User
from django.urls import reverse_lazy
from django.http import JsonResponse
from django.contrib import messages
class HomeView(LoginRequiredMixin, View):
def get(self, request):
return redirect('conference:room_list')
home = HomeView.as_view()
class RoomListView(LoginRequiredMixin, ListView):
model = Room
template_name = 'conference/room_list.html'
def get_queryset(self):
user = self.request.user
# Rooms the user is invited to or created
return Room.objects.filter(models.Q(created_by=user) | models.Q(participants=user)).distinct()
class RoomCreateView(LoginRequiredMixin, CreateView):
model = Room
fields = ['name']
template_name = 'conference/room_create.html'
success_url = reverse_lazy('conference:room_list')
def form_valid(self, form):
form.instance.created_by = self.request.user
response = super().form_valid(form)
# Optionally, add the creator as a participant
self.object.participants.add(self.request.user)
return response
class RoomDetailView(LoginRequiredMixin, DetailView):
model = Room
template_name = 'conference/room_detail.html'
def get(self, request, *args, **kwargs):
room = self.get_object()
user = request.user
# Check if user is allowed to view the room
if room.created_by != user and not room.participants.filter(id=user.id).exists():
messages.error(request, "You do not have access to this room.")
return redirect('conference:room_list')
return super().get(request, *args, **kwargs)
def invite_user(request, pk):
room = get_object_or_404(Room, pk=pk)
if request.user != room.created_by:
messages.error(request, "Only the creator can invite users.")
return redirect('conference:room_detail', pk=pk)
if request.method == 'POST':
username = request.POST.get('username')
try:
user = User.objects.get(username=username)
Invitation.objects.get_or_create(room=room, user=user)
messages.success(request, f"User {username} invited successfully.")
except User.DoesNotExist:
messages.error(request, "User does not exist.")
return redirect('conference:room_detail', pk=pk)
return render(request, 'conference/invite_user.html', {'room': room})
def join_room(request, pk):
room = get_object_or_404(Room, pk=pk)
user = request.user
# Check if user is invited
invitation = Invitation.objects.filter(room=room, user=user, accepted=True).first()
if room.created_by != user and not room.participants.filter(id=user.id).exists():
messages.error(request, "You do not have access to this room.")
return redirect('conference:room_list')
return render(request, 'conference/join_room.html', {'room': room})
- Templates
Create the necessary HTML templates in templates/conference/.
room_list.html
<!-- templates/conference/room_list.html -->
<!DOCTYPE html>
<html>
<head>
<title>Rooms</title>
</head>
<body>
<h2>Your Rooms</h2>
<a href="{% url 'conference:room_create' %}">Create New Room</a>
<ul>
{% for room in object_list %}
<li>
<a href="{% url 'conference:room_detail' room.pk %}">{{ room.name }}</a>
</li>
{% empty %}
<li>No rooms available.</li>
{% endfor %}
</ul>
<a href="{% url 'logout' %}">Logout</a>
</body>
</html>
room_create.html
<!-- templates/conference/room_create.html -->
<!DOCTYPE html>
<html>
<head>
<title>Create Room</title>
</head>
<body>
<h2>Create a New Room</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create</button>
</form>
<a href="{% url 'conference:room_list' %}">Back to Rooms</a>
</body>
</html>
room_detail.html
<!-- templates/conference/room_detail.html -->
<!DOCTYPE html>
<html>
<head>
<title>Room: {{ object.name }}</title>
</head>
<body>
<h2>Room: {{ object.name }}</h2>
<p>Created by: {{ object.created_by.username }}</p>
<h3>Participants:</h3>
<ul>
{% for participant in object.participants.all %}
<li>{{ participant.username }}</li>
{% empty %}
<li>No participants yet.</li>
{% endfor %}
</ul>
<h3>Invite User</h3>
<form method="post" action="{% url 'conference:invite_user' object.pk %}">
{% csrf_token %}
<input type="text" name="username" placeholder="Username to invite" required>
<button type="submit">Invite</button>
</form>
<h3>Join Room</h3>
<a href="{% url 'conference:join_room' object.pk %}">Enter Conference Room</a>
<br>
<a href="{% url 'conference:room_list' %}">Back to Rooms</a>
</body>
</html>
join_room.html
This template will include the frontend for video conferencing using WebRTC.
<!-- templates/conference/join_room.html -->
<!DOCTYPE html>
<html>
<head>
<title>Conference Room: {{ room.name }}</title>
<style>
#localVideo, #remoteVideo {
width: 45%;
border: 1px solid black;
margin: 2%;
}
</style>
</head>
<body>
<h2>Conference Room: {{ room.name }}</h2>
<video id="localVideo" autoplay muted></video>
<video id="remoteVideo" autoplay></video>
<script>
const roomName = "{{ room.name }}";
const wsScheme = window.location.protocol === "https:" ? "wss" : "ws";
const socket = new WebSocket(wsScheme + '://' + window.location.host + '/ws/conference/' + roomName + '/');
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
let localStream;
let pc;
const configuration = {
'iceServers': [
{ 'urls': 'stun:stun.l.google.com:19302' }
]
};
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => {
localVideo.srcObject = stream;
localStream = stream;
call();
})
.catch(error => {
console.error('Error accessing media devices.', error);
});
socket.onmessage = async function(event) {
const data = JSON.parse(event.data);
const message = data['message'];
if (!pc) {
createPeerConnection();
}
if (message.type === 'offer') {
await pc.setRemoteDescription(new RTCSessionDescription(message));
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
socket.send(JSON.stringify({ 'message': pc.localDescription }));
} else if (message.type === 'answer') {
await pc.setRemoteDescription(new RTCSessionDescription(message));
} else if (message.type === 'candidate') {
try {
await pc.addIceCandidate(message.candidate);
} catch (e) {
console.error('Error adding received ice candidate', e);
}
}
};
function createPeerConnection() {
pc = new RTCPeerConnection(configuration);
pc.onicecandidate = function(event) {
if (event.candidate) {
socket.send(JSON.stringify({
'message': {
'type': 'candidate',
'candidate': event.candidate
}
}));
}
};
pc.ontrack = function(event) {
remoteVideo.srcObject = event.streams[0];
};
localStream.getTracks().forEach(track => pc.addTrack(track, localStream));
}
async function call() {
if (!pc) {
createPeerConnection();
}
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
socket.send(JSON.stringify({ 'message': pc.localDescription }));
}
</script>
</body>
</html>
Step 6: Implement WebSockets for Signaling
WebRTC requires a signaling mechanism to exchange session descriptions and ICE candidates. We'll use Django Channels to handle WebSocket connections.
- Routing
# conference/routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/conference/(?P<room_name>\w+)/$', consumers.ConferenceConsumer.as_asgi()),
]
- Consumer
Create a consumer to handle WebSocket connections.
# conference/consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ConferenceConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = f'conference_{self.room_name}'
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
async def receive(self, text_data):
data = json.loads(text_data)
message = data.get('message')
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'conference_message',
'message': message
}
)
# Receive message from room group
async def conference_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
Step 7: Finalize and Test
- Run Redis Server
Ensure that Redis is running on your system as it's required for Channels.
redis-server
- Run Django Development Server
python manage.py runserver
- Access the Application
- Navigate to
http://127.0.0.1:8000/admin/ and log in with the superuser credentials.
- Create some users or allow users to register via Django's authentication system.
- Create a room via the admin or through the frontend by navigating to
/conference/rooms/create/.
- Invite users to the room.
- Users can then join the room and start video conferencing.
Additional Enhancements
The above implementation provides a basic structure for a video conferencing app. However, real-world applications require more features and robustness. Here are some enhancements you might consider:
-
User Registration: Implement user registration views and templates to allow users to sign up.
-
Room Access Control: Improve access control by handling invitations and accepted invitations properly.
-
Multiple Participants: The current WebRTC setup handles a single remote video. To support multiple participants, consider implementing a Mesh network or using an MCU/SFU server.
-
Chat Feature: Add real-time text chat within conference rooms using Channels.
-
UI/UX Enhancements: Improve the frontend with better styling and user experience.
-
Scalability: For handling more significant traffic and multiple rooms, optimize the Channels setup and consider using scalable backend services.
-
Security: Implement security best practices, such as HTTPS, proper authentication, and authorization mechanisms.
Conclusion
Creating a full-fledged video conferencing app involves integrating various technologies and handling real-time data transmission. The above guide provides a foundational structure using Django, Django Channels, and WebRTC. Depending on your specific requirements and scale, you may need to incorporate additional features and optimizations.